diff options
Diffstat (limited to 'source/blender/editors')
54 files changed, 3944 insertions, 948 deletions
diff --git a/source/blender/editors/gpencil/gpencil_data.c b/source/blender/editors/gpencil/gpencil_data.c index c76c2e55d2b..039bc50fcc9 100644 --- a/source/blender/editors/gpencil/gpencil_data.c +++ b/source/blender/editors/gpencil/gpencil_data.c @@ -1676,7 +1676,7 @@ void GPENCIL_OT_stroke_arrange(wmOperatorType *ot) /* identifiers */ ot->name = "Arrange Stroke"; ot->idname = "GPENCIL_OT_stroke_arrange"; - ot->description = "Arrange selected strokes up/down in the drawing order of the active layer"; + ot->description = "Arrange selected strokes up/down in the display order of the active layer"; /* callbacks */ ot->exec = gpencil_stroke_arrange_exec; diff --git a/source/blender/editors/gpencil/gpencil_select.c b/source/blender/editors/gpencil/gpencil_select.c index e01c1ec54d7..aab08e9c8c4 100644 --- a/source/blender/editors/gpencil/gpencil_select.c +++ b/source/blender/editors/gpencil/gpencil_select.c @@ -1847,7 +1847,7 @@ static bool gpencil_generic_stroke_select(bContext *C, bGPDspoint *pt; int i; bool hit = false; - for (i = 0, pt = gps->points; i < gps->totpoints; i++, pt++) { + for (i = 0, pt = gps_active->points; i < gps_active->totpoints; i++, pt++) { bGPDspoint *pt_active = (pt->runtime.pt_orig) ? pt->runtime.pt_orig : pt; /* convert point coords to screenspace */ @@ -2252,12 +2252,12 @@ static int gpencil_select_exec(bContext *C, wmOperator *op) int i; /* firstly, check for hit-point */ - for (i = 0, pt = gps->points; i < gps->totpoints; i++, pt++) { + for (i = 0, pt = gps_active->points; i < gps_active->totpoints; i++, pt++) { int xy[2]; bGPDspoint pt2; gpencil_point_to_parent_space(pt, gpstroke_iter.diff_mat, &pt2); - gpencil_point_to_xy(&gsc, gps, &pt2, &xy[0], &xy[1]); + gpencil_point_to_xy(&gsc, gps_active, &pt2, &xy[0], &xy[1]); /* do boundbox check first */ if (!ELEM(V2D_IS_CLIPPED, xy[0], xy[1])) { diff --git a/source/blender/editors/gpencil/gpencil_uv.c b/source/blender/editors/gpencil/gpencil_uv.c index 677451eaabc..6bd0540a9d4 100644 --- a/source/blender/editors/gpencil/gpencil_uv.c +++ b/source/blender/editors/gpencil/gpencil_uv.c @@ -44,6 +44,7 @@ #include "ED_numinput.h" #include "ED_screen.h" #include "ED_space_api.h" +#include "ED_util.h" #include "ED_view3d.h" #include "DEG_depsgraph.h" diff --git a/source/blender/editors/include/ED_screen.h b/source/blender/editors/include/ED_screen.h index deb6b7502c7..61e1f0fdf7d 100644 --- a/source/blender/editors/include/ED_screen.h +++ b/source/blender/editors/include/ED_screen.h @@ -123,8 +123,6 @@ void ED_region_info_draw_multiline(ARegion *region, const char *text_array[], float fill_color[4], const bool full_redraw); -void ED_region_image_metadata_draw( - int x, int y, struct ImBuf *ibuf, const rctf *frame, float zoomx, float zoomy); void ED_region_image_metadata_panel_draw(struct ImBuf *ibuf, struct uiLayout *layout); void ED_region_grid_draw(struct ARegion *region, float zoomx, float zoomy, float x0, float y0); float ED_region_blend_alpha(struct ARegion *region); diff --git a/source/blender/editors/include/ED_space_api.h b/source/blender/editors/include/ED_space_api.h index c50bbc2f1e9..fc474ea464d 100644 --- a/source/blender/editors/include/ED_space_api.h +++ b/source/blender/editors/include/ED_space_api.h @@ -76,11 +76,6 @@ void ED_region_draw_cb_exit(struct ARegionType *, void *); void ED_region_draw_cb_remove_by_type(struct ARegionType *art, void *draw_fn, void (*free)(void *)); -/* generic callbacks */ -/* ed_util.c */ -void ED_region_draw_mouse_line_cb(const struct bContext *C, - struct ARegion *region, - void *arg_info); #ifdef __cplusplus } diff --git a/source/blender/editors/include/ED_util.h b/source/blender/editors/include/ED_util.h index 073186f6335..953f26aa45f 100644 --- a/source/blender/editors/include/ED_util.h +++ b/source/blender/editors/include/ED_util.h @@ -53,6 +53,14 @@ void ED_spacedata_id_remap(struct ScrArea *area, void ED_operatortypes_edutils(void); +/* Drawing */ +void ED_region_draw_mouse_line_cb(const struct bContext *C, + struct ARegion *region, + void *arg_info); + +void ED_region_image_metadata_draw( + int x, int y, struct ImBuf *ibuf, const rctf *frame, float zoomx, float zoomy); + /* ************** XXX OLD CRUFT WARNING ************* */ void apply_keyb_grid( diff --git a/source/blender/editors/include/UI_interface.h b/source/blender/editors/include/UI_interface.h index 81641239c6a..5620d39ab16 100644 --- a/source/blender/editors/include/UI_interface.h +++ b/source/blender/editors/include/UI_interface.h @@ -499,10 +499,14 @@ typedef int (*uiButCompleteFunc)(struct bContext *C, char *str, void *arg); typedef struct ARegion *(*uiButSearchCreateFn)(struct bContext *C, struct ARegion *butregion, struct uiButSearch *search_but); +/* `is_first` is typically used to ignore search filtering when the menu is first opened in order + * to display the full list of options. The value will be false after the button's text is edited + * (for every call except the first). */ typedef void (*uiButSearchUpdateFn)(const struct bContext *C, void *arg, const char *str, - uiSearchItems *items); + uiSearchItems *items, + const bool is_first); typedef void (*uiButSearchArgFreeFn)(void *arg); typedef bool (*uiButSearchContextMenuFn)(struct bContext *C, void *arg, @@ -1602,6 +1606,7 @@ void UI_but_func_search_set(uiBut *but, void UI_but_func_search_set_context_menu(uiBut *but, uiButSearchContextMenuFn context_menu_fn); void UI_but_func_search_set_tooltip(uiBut *but, uiButSearchTooltipFn tooltip_fn); void UI_but_func_search_set_sep_string(uiBut *but, const char *search_sep_string); +void UI_but_func_search_set_results_are_suggestions(uiBut *but, const bool value); /* height in pixels, it's using hardcoded values still */ int UI_searchbox_size_y(void); diff --git a/source/blender/editors/interface/interface.c b/source/blender/editors/interface/interface.c index 6e25ec9d275..c7f5385eac3 100644 --- a/source/blender/editors/interface/interface.c +++ b/source/blender/editors/interface/interface.c @@ -6661,11 +6661,20 @@ void UI_but_func_search_set_tooltip(uiBut *but, uiButSearchTooltipFn tooltip_fn) but_search->item_tooltip_fn = tooltip_fn; } +void UI_but_func_search_set_results_are_suggestions(uiBut *but, const bool value) +{ + uiButSearch *but_search = (uiButSearch *)but; + BLI_assert(but->type == UI_BTYPE_SEARCH_MENU); + + but_search->results_are_suggestions = value; +} + /* Callbacks for operator search button. */ static void operator_enum_search_update_fn(const struct bContext *C, void *but, const char *str, - uiSearchItems *items) + uiSearchItems *items, + const bool UNUSED(is_first)) { wmOperatorType *ot = ((uiBut *)but)->optype; PropertyRNA *prop = ot->prop; diff --git a/source/blender/editors/interface/interface_handlers.c b/source/blender/editors/interface/interface_handlers.c index 5de330d7136..75ee3300e63 100644 --- a/source/blender/editors/interface/interface_handlers.c +++ b/source/blender/editors/interface/interface_handlers.c @@ -3408,8 +3408,12 @@ static void ui_textedit_end(bContext *C, uiBut *but, uiHandleButtonData *data) if (data->searchbox) { if (data->cancel == false) { + BLI_assert(but->type == UI_BTYPE_SEARCH_MENU); + uiButSearch *but_search = (uiButSearch *)but; + if ((ui_searchbox_apply(but, data->searchbox) == false) && - (ui_searchbox_find_index(data->searchbox, but->editstr) == -1)) { + (ui_searchbox_find_index(data->searchbox, but->editstr) == -1) && + !but_search->results_are_suggestions) { data->cancel = true; /* ensure menu (popup) too is closed! */ diff --git a/source/blender/editors/interface/interface_intern.h b/source/blender/editors/interface/interface_intern.h index 3da66d45abd..c39e2b3ff8a 100644 --- a/source/blender/editors/interface/interface_intern.h +++ b/source/blender/editors/interface/interface_intern.h @@ -31,6 +31,10 @@ #include "UI_interface.h" #include "UI_resources.h" +#ifdef __cplusplus +extern "C" { +#endif + struct ARegion; struct AnimationEvalContext; struct CurveMapping; @@ -316,6 +320,12 @@ typedef struct uiButSearch { struct PointerRNA rnasearchpoin; struct PropertyRNA *rnasearchprop; + + /** + * The search box only provides suggestions, it does not force + * the string to match one of the search items when applying. + */ + bool results_are_suggestions; } uiButSearch; /** Derived struct for #UI_BTYPE_DECORATOR */ @@ -1193,10 +1203,15 @@ typedef struct uiRNACollectionSearch { void ui_rna_collection_search_update_fn(const struct bContext *C, void *arg, const char *str, - uiSearchItems *items); + uiSearchItems *items, + const bool is_first); /* interface_ops.c */ bool ui_jump_to_target_button_poll(struct bContext *C); /* interface_queries.c */ void ui_interface_tag_script_reload_queries(void); + +#ifdef __cplusplus +} +#endif diff --git a/source/blender/editors/interface/interface_region_search.c b/source/blender/editors/interface/interface_region_search.c index 2c07f5c3c03..12044863b8c 100644 --- a/source/blender/editors/interface/interface_region_search.c +++ b/source/blender/editors/interface/interface_region_search.c @@ -468,7 +468,8 @@ static void ui_searchbox_update_fn(bContext *C, wmWindow *win = CTX_wm_window(C); WM_tooltip_clear(C, win); } - search_but->items_update_fn(C, search_but->arg, str, items); + const bool is_first_search = !search_but->but.changed; + search_but->items_update_fn(C, search_but->arg, str, items, is_first_search); } /* region is the search box itself */ @@ -1052,14 +1053,16 @@ void ui_but_search_refresh(uiButSearch *search_but) ui_searchbox_update_fn(but->block->evil_C, search_but, but->drawstr, items); - /* Only red-alert when we are sure of it, this can miss cases when >10 matches. */ - if (items->totitem == 0) { - UI_but_flag_enable(but, UI_BUT_REDALERT); - } - else if (items->more == 0) { - if (UI_search_items_find_index(items, but->drawstr) == -1) { + if (!search_but->results_are_suggestions) { + /* Only red-alert when we are sure of it, this can miss cases when >10 matches. */ + if (items->totitem == 0) { UI_but_flag_enable(but, UI_BUT_REDALERT); } + else if (items->more == 0) { + if (UI_search_items_find_index(items, but->drawstr) == -1) { + UI_but_flag_enable(but, UI_BUT_REDALERT); + } + } } for (x1 = 0; x1 < items->maxitem; x1++) { diff --git a/source/blender/editors/interface/interface_template_search_menu.c b/source/blender/editors/interface/interface_template_search_menu.c index 25cf2e12377..e1f8f63dcbf 100644 --- a/source/blender/editors/interface/interface_template_search_menu.c +++ b/source/blender/editors/interface/interface_template_search_menu.c @@ -990,7 +990,8 @@ static void menu_search_exec_fn(bContext *C, void *UNUSED(arg1), void *arg2) static void menu_search_update_fn(const bContext *UNUSED(C), void *arg, const char *str, - uiSearchItems *items) + uiSearchItems *items, + const bool UNUSED(is_first)) { struct MenuSearch_Data *data = arg; diff --git a/source/blender/editors/interface/interface_template_search_operator.c b/source/blender/editors/interface/interface_template_search_operator.c index ff0f9a2e5cd..2c83f184ff0 100644 --- a/source/blender/editors/interface/interface_template_search_operator.c +++ b/source/blender/editors/interface/interface_template_search_operator.c @@ -59,7 +59,8 @@ static void operator_search_exec_fn(bContext *C, void *UNUSED(arg1), void *arg2) static void operator_search_update_fn(const bContext *C, void *UNUSED(arg), const char *str, - uiSearchItems *items) + uiSearchItems *items, + const bool UNUSED(is_first)) { GHashIterator iter; diff --git a/source/blender/editors/interface/interface_templates.c b/source/blender/editors/interface/interface_templates.c index 67446ca681f..c5e67e0334e 100644 --- a/source/blender/editors/interface/interface_templates.c +++ b/source/blender/editors/interface/interface_templates.c @@ -393,7 +393,8 @@ static bool id_search_add(const bContext *C, TemplateID *template_ui, uiSearchIt static void id_search_cb(const bContext *C, void *arg_template, const char *str, - uiSearchItems *items) + uiSearchItems *items, + const bool UNUSED(is_first)) { TemplateID *template_ui = (TemplateID *)arg_template; ListBase *lb = template_ui->idlb; @@ -464,7 +465,8 @@ static void id_search_cb_tagged(const bContext *C, static void id_search_cb_objects_from_scene(const bContext *C, void *arg_template, const char *str, - uiSearchItems *items) + uiSearchItems *items, + const bool UNUSED(is_first)) { TemplateID *template_ui = (TemplateID *)arg_template; ListBase *lb = template_ui->idlb; @@ -518,7 +520,7 @@ static uiBlock *id_search_menu(bContext *C, ARegion *region, void *arg_litem) static TemplateID template_ui; PointerRNA active_item_ptr; void (*id_search_update_fn)( - const bContext *, void *, const char *, uiSearchItems *) = id_search_cb; + const bContext *, void *, const char *, uiSearchItems *, const bool) = id_search_cb; /* arg_litem is malloced, can be freed by parent button */ template_ui = *((TemplateID *)arg_litem); @@ -3985,7 +3987,7 @@ static void curvemap_tools_dofunc(bContext *C, void *cumap_v, int event) BKE_curvemapping_changed(cumap, false); break; case UICURVE_FUNC_RESET_VIEW: - cumap->curr = cumap->clipr; + BKE_curvemapping_reset_view(cumap); break; case UICURVE_FUNC_HANDLE_VECTOR: /* set vector */ BKE_curvemap_handle_set(cuma, HD_VECT); diff --git a/source/blender/editors/interface/interface_utils.c b/source/blender/editors/interface/interface_utils.c index 5311bb57da9..877800c1ba2 100644 --- a/source/blender/editors/interface/interface_utils.c +++ b/source/blender/editors/interface/interface_utils.c @@ -405,7 +405,8 @@ static bool add_collection_search_item(CollItemSearch *cis, void ui_rna_collection_search_update_fn(const struct bContext *C, void *arg, const char *str, - uiSearchItems *items) + uiSearchItems *items, + const bool is_first) { uiRNACollectionSearch *data = arg; const int flag = RNA_property_flag(data->target_prop); @@ -415,7 +416,7 @@ void ui_rna_collection_search_update_fn(const struct bContext *C, * match the RNA name exactly. So only for pointer properties, the name can be modified to add * further UI hints. */ const bool requires_exact_data_name = !is_ptr_target; - const bool skip_filter = data->search_but && !data->search_but->changed; + const bool skip_filter = is_first; char name_buf[UI_MAX_DRAW_STR]; char *name; bool has_id_icon = false; diff --git a/source/blender/editors/mesh/editmesh_bevel.c b/source/blender/editors/mesh/editmesh_bevel.c index 66a7b97b440..340a7ae92ff 100644 --- a/source/blender/editors/mesh/editmesh_bevel.c +++ b/source/blender/editors/mesh/editmesh_bevel.c @@ -50,6 +50,7 @@ #include "ED_screen.h" #include "ED_space_api.h" #include "ED_transform.h" +#include "ED_util.h" #include "ED_view3d.h" #include "mesh_intern.h" /* own include */ diff --git a/source/blender/editors/mesh/editmesh_inset.c b/source/blender/editors/mesh/editmesh_inset.c index 9000a942e50..73d79805f60 100644 --- a/source/blender/editors/mesh/editmesh_inset.c +++ b/source/blender/editors/mesh/editmesh_inset.c @@ -46,6 +46,7 @@ #include "ED_screen.h" #include "ED_space_api.h" #include "ED_transform.h" +#include "ED_util.h" #include "ED_view3d.h" #include "mesh_intern.h" /* own include */ diff --git a/source/blender/editors/screen/area.c b/source/blender/editors/screen/area.c index 2c71345699f..bd2b1c4c553 100644 --- a/source/blender/editors/screen/area.c +++ b/source/blender/editors/screen/area.c @@ -3516,297 +3516,6 @@ void ED_region_info_draw(ARegion *region, ED_region_info_draw_multiline(region, text_array, fill_color, full_redraw); } -#define MAX_METADATA_STR 1024 - -static const char *meta_data_list[] = { - "File", - "Strip", - "Date", - "RenderTime", - "Note", - "Marker", - "Time", - "Frame", - "Camera", - "Scene", -}; - -BLI_INLINE bool metadata_is_valid(ImBuf *ibuf, char *r_str, short index, int offset) -{ - return (IMB_metadata_get_field( - ibuf->metadata, meta_data_list[index], r_str + offset, MAX_METADATA_STR - offset) && - r_str[0]); -} - -BLI_INLINE bool metadata_is_custom_drawable(const char *field) -{ - /* Metadata field stored by Blender for multilayer EXR images. Is rather - * useless to be viewed all the time. Can still be seen in the Metadata - * panel. */ - if (STREQ(field, "BlenderMultiChannel")) { - return false; - } - /* Is almost always has value "scanlineimage", also useless to be seen - * all the time. */ - if (STREQ(field, "type")) { - return false; - } - return !BKE_stamp_is_known_field(field); -} - -typedef struct MetadataCustomDrawContext { - int fontid; - int xmin, ymin; - int vertical_offset; - int current_y; -} MetadataCustomDrawContext; - -static void metadata_custom_draw_fields(const char *field, const char *value, void *ctx_v) -{ - if (!metadata_is_custom_drawable(field)) { - return; - } - MetadataCustomDrawContext *ctx = (MetadataCustomDrawContext *)ctx_v; - char temp_str[MAX_METADATA_STR]; - BLI_snprintf(temp_str, MAX_METADATA_STR, "%s: %s", field, value); - BLF_position(ctx->fontid, ctx->xmin, ctx->ymin + ctx->current_y, 0.0f); - BLF_draw(ctx->fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX); - ctx->current_y += ctx->vertical_offset; -} - -static void metadata_draw_imbuf(ImBuf *ibuf, const rctf *rect, int fontid, const bool is_top) -{ - char temp_str[MAX_METADATA_STR]; - int ofs_y = 0; - const float height = BLF_height_max(fontid); - const float margin = height / 8; - const float vertical_offset = (height + margin); - - /* values taking margins into account */ - const float descender = BLF_descender(fontid); - const float xmin = (rect->xmin + margin); - const float xmax = (rect->xmax - margin); - const float ymin = (rect->ymin + margin) - descender; - const float ymax = (rect->ymax - margin) - descender; - - if (is_top) { - for (int i = 0; i < 4; i++) { - /* first line */ - if (i == 0) { - bool do_newline = false; - int len = BLI_snprintf_rlen(temp_str, MAX_METADATA_STR, "%s: ", meta_data_list[0]); - if (metadata_is_valid(ibuf, temp_str, 0, len)) { - BLF_position(fontid, xmin, ymax - vertical_offset, 0.0f); - BLF_draw(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX); - do_newline = true; - } - - len = BLI_snprintf_rlen(temp_str, MAX_METADATA_STR, "%s: ", meta_data_list[1]); - if (metadata_is_valid(ibuf, temp_str, 1, len)) { - int line_width = BLF_width(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX); - BLF_position(fontid, xmax - line_width, ymax - vertical_offset, 0.0f); - BLF_draw(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX); - do_newline = true; - } - - if (do_newline) { - ofs_y += vertical_offset; - } - } /* Strip */ - else if (ELEM(i, 1, 2)) { - int len = BLI_snprintf_rlen(temp_str, MAX_METADATA_STR, "%s: ", meta_data_list[i + 1]); - if (metadata_is_valid(ibuf, temp_str, i + 1, len)) { - BLF_position(fontid, xmin, ymax - vertical_offset - ofs_y, 0.0f); - BLF_draw(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX); - ofs_y += vertical_offset; - } - } /* Note (wrapped) */ - else if (i == 3) { - int len = BLI_snprintf_rlen(temp_str, MAX_METADATA_STR, "%s: ", meta_data_list[i + 1]); - if (metadata_is_valid(ibuf, temp_str, i + 1, len)) { - struct ResultBLF info; - BLF_enable(fontid, BLF_WORD_WRAP); - BLF_wordwrap(fontid, ibuf->x - (margin * 2)); - BLF_position(fontid, xmin, ymax - vertical_offset - ofs_y, 0.0f); - BLF_draw_ex(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX, &info); - BLF_wordwrap(fontid, 0); - BLF_disable(fontid, BLF_WORD_WRAP); - ofs_y += vertical_offset * info.lines; - } - } - else { - int len = BLI_snprintf_rlen(temp_str, MAX_METADATA_STR, "%s: ", meta_data_list[i + 1]); - if (metadata_is_valid(ibuf, temp_str, i + 1, len)) { - int line_width = BLF_width(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX); - BLF_position(fontid, xmax - line_width, ymax - vertical_offset - ofs_y, 0.0f); - BLF_draw(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX); - ofs_y += vertical_offset; - } - } - } - } - else { - MetadataCustomDrawContext ctx; - ctx.fontid = fontid; - ctx.xmin = xmin; - ctx.ymin = ymin; - ctx.current_y = ofs_y; - ctx.vertical_offset = vertical_offset; - IMB_metadata_foreach(ibuf, metadata_custom_draw_fields, &ctx); - int ofs_x = 0; - ofs_y = ctx.current_y; - for (int i = 5; i < 10; i++) { - int len = BLI_snprintf_rlen(temp_str, MAX_METADATA_STR, "%s: ", meta_data_list[i]); - if (metadata_is_valid(ibuf, temp_str, i, len)) { - BLF_position(fontid, xmin + ofs_x, ymin + ofs_y, 0.0f); - BLF_draw(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX); - - ofs_x += BLF_width(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX) + UI_UNIT_X; - } - } - } -} - -typedef struct MetadataCustomCountContext { - int count; -} MetadataCustomCountContext; - -static void metadata_custom_count_fields(const char *field, const char *UNUSED(value), void *ctx_v) -{ - if (!metadata_is_custom_drawable(field)) { - return; - } - MetadataCustomCountContext *ctx = (MetadataCustomCountContext *)ctx_v; - ctx->count++; -} - -static float metadata_box_height_get(ImBuf *ibuf, int fontid, const bool is_top) -{ - const float height = BLF_height_max(fontid); - const float margin = (height / 8); - char str[MAX_METADATA_STR] = ""; - short count = 0; - - if (is_top) { - if (metadata_is_valid(ibuf, str, 0, 0) || metadata_is_valid(ibuf, str, 1, 0)) { - count++; - } - for (int i = 2; i < 5; i++) { - if (metadata_is_valid(ibuf, str, i, 0)) { - if (i == 4) { - struct { - struct ResultBLF info; - rctf rect; - } wrap; - - BLF_enable(fontid, BLF_WORD_WRAP); - BLF_wordwrap(fontid, ibuf->x - (margin * 2)); - BLF_boundbox_ex(fontid, str, sizeof(str), &wrap.rect, &wrap.info); - BLF_wordwrap(fontid, 0); - BLF_disable(fontid, BLF_WORD_WRAP); - - count += wrap.info.lines; - } - else { - count++; - } - } - } - } - else { - for (int i = 5; i < 10; i++) { - if (metadata_is_valid(ibuf, str, i, 0)) { - count = 1; - break; - } - } - MetadataCustomCountContext ctx; - ctx.count = 0; - IMB_metadata_foreach(ibuf, metadata_custom_count_fields, &ctx); - count += ctx.count; - } - - if (count) { - return (height + margin) * count; - } - - return 0; -} - -#undef MAX_METADATA_STR - -void ED_region_image_metadata_draw( - int x, int y, ImBuf *ibuf, const rctf *frame, float zoomx, float zoomy) -{ - const uiStyle *style = UI_style_get_dpi(); - - if (!ibuf->metadata) { - return; - } - - /* find window pixel coordinates of origin */ - GPU_matrix_push(); - - /* offset and zoom using ogl */ - GPU_matrix_translate_2f(x, y); - GPU_matrix_scale_2f(zoomx, zoomy); - - BLF_size(blf_mono_font, style->widgetlabel.points * 1.5f * U.pixelsize, U.dpi); - - /* *** upper box*** */ - - /* get needed box height */ - float box_y = metadata_box_height_get(ibuf, blf_mono_font, true); - - if (box_y) { - /* set up rect */ - rctf rect; - BLI_rctf_init(&rect, frame->xmin, frame->xmax, frame->ymax, frame->ymax + box_y); - /* draw top box */ - GPUVertFormat *format = immVertexFormat(); - uint pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT); - immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR); - immUniformThemeColor(TH_METADATA_BG); - immRectf(pos, rect.xmin, rect.ymin, rect.xmax, rect.ymax); - immUnbindProgram(); - - BLF_clipping(blf_mono_font, rect.xmin, rect.ymin, rect.xmax, rect.ymax); - BLF_enable(blf_mono_font, BLF_CLIPPING); - - UI_FontThemeColor(blf_mono_font, TH_METADATA_TEXT); - metadata_draw_imbuf(ibuf, &rect, blf_mono_font, true); - - BLF_disable(blf_mono_font, BLF_CLIPPING); - } - - /* *** lower box*** */ - - box_y = metadata_box_height_get(ibuf, blf_mono_font, false); - - if (box_y) { - /* set up box rect */ - rctf rect; - BLI_rctf_init(&rect, frame->xmin, frame->xmax, frame->ymin - box_y, frame->ymin); - /* draw top box */ - GPUVertFormat *format = immVertexFormat(); - uint pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT); - immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR); - immUniformThemeColor(TH_METADATA_BG); - immRectf(pos, rect.xmin, rect.ymin, rect.xmax, rect.ymax); - immUnbindProgram(); - - BLF_clipping(blf_mono_font, rect.xmin, rect.ymin, rect.xmax, rect.ymax); - BLF_enable(blf_mono_font, BLF_CLIPPING); - - UI_FontThemeColor(blf_mono_font, TH_METADATA_TEXT); - metadata_draw_imbuf(ibuf, &rect, blf_mono_font, false); - - BLF_disable(blf_mono_font, BLF_CLIPPING); - } - - GPU_matrix_pop(); -} - typedef struct MetadataPanelDrawContext { uiLayout *layout; } MetadataPanelDrawContext; diff --git a/source/blender/editors/sculpt_paint/CMakeLists.txt b/source/blender/editors/sculpt_paint/CMakeLists.txt index fff8d27ef5b..fff172c0707 100644 --- a/source/blender/editors/sculpt_paint/CMakeLists.txt +++ b/source/blender/editors/sculpt_paint/CMakeLists.txt @@ -61,10 +61,12 @@ set(SRC sculpt_cloth.c sculpt_detail.c sculpt_dyntopo.c + sculpt_expand.c sculpt_face_set.c sculpt_filter_color.c sculpt_filter_mask.c sculpt_filter_mesh.c + sculpt_geodesic.c sculpt_mask_expand.c sculpt_multiplane_scrape.c sculpt_paint_color.c diff --git a/source/blender/editors/sculpt_paint/paint_cursor.c b/source/blender/editors/sculpt_paint/paint_cursor.c index e9f33d2fbd3..b44f2f66d92 100644 --- a/source/blender/editors/sculpt_paint/paint_cursor.c +++ b/source/blender/editors/sculpt_paint/paint_cursor.c @@ -1626,6 +1626,16 @@ static void paint_cursor_draw_3d_view_brush_cursor_inactive(PaintCursorContext * paint_cursor_pose_brush_origins_draw(pcontext); } + /* Expand operation origin. */ + if (pcontext->ss->expand_cache) { + cursor_draw_point_screen_space( + pcontext->pos, + pcontext->region, + SCULPT_vertex_co_get(pcontext->ss, pcontext->ss->expand_cache->initial_active_vertex), + pcontext->vc.obact->obmat, + 2); + } + if (brush->sculpt_tool == SCULPT_TOOL_BOUNDARY) { paint_cursor_preview_boundary_data_update(pcontext, update_previews); paint_cursor_preview_boundary_data_pivot_draw(pcontext); diff --git a/source/blender/editors/sculpt_paint/paint_ops.c b/source/blender/editors/sculpt_paint/paint_ops.c index f4586fa130d..e1dc8fa30b9 100644 --- a/source/blender/editors/sculpt_paint/paint_ops.c +++ b/source/blender/editors/sculpt_paint/paint_ops.c @@ -1393,4 +1393,7 @@ void ED_keymap_paint(wmKeyConfig *keyconf) /* paint stroke */ keymap = paint_stroke_modal_keymap(keyconf); WM_modalkeymap_assign(keymap, "SCULPT_OT_brush_stroke"); + + /* sculpt expand. */ + sculpt_expand_modal_keymap(keyconf); } diff --git a/source/blender/editors/sculpt_paint/sculpt.c b/source/blender/editors/sculpt_paint/sculpt.c index 3a18d7a10de..631327ddfe8 100644 --- a/source/blender/editors/sculpt_paint/sculpt.c +++ b/source/blender/editors/sculpt_paint/sculpt.c @@ -1103,6 +1103,12 @@ void SCULPT_floodfill_add_initial(SculptFloodFill *flood, int index) BLI_gsqueue_push(flood->queue, &index); } +void SCULPT_floodfill_add_and_skip_initial(SculptFloodFill *flood, int index) +{ + BLI_gsqueue_push(flood->queue, &index); + BLI_BITMAP_ENABLE(flood->visited_vertices, index); +} + void SCULPT_floodfill_add_initial_with_symmetry( Sculpt *sd, Object *ob, SculptSession *ss, SculptFloodFill *flood, int index, float radius) { @@ -9006,7 +9012,7 @@ static bool SCULPT_connected_components_floodfill_cb( return true; } -static void sculpt_connected_components_ensure(Object *ob) +void SCULPT_connected_components_ensure(Object *ob) { SculptSession *ss = ob->sculpt; @@ -9081,7 +9087,7 @@ void SCULPT_fake_neighbors_ensure(Sculpt *sd, Object *ob, const float max_dist) return; } - sculpt_connected_components_ensure(ob); + SCULPT_connected_components_ensure(ob); SCULPT_fake_neighbor_init(ss, max_dist); for (int i = 0; i < totvert; i++) { @@ -9790,4 +9796,6 @@ void ED_operatortypes_sculpt(void) WM_operatortype_append(SCULPT_OT_color_filter); WM_operatortype_append(SCULPT_OT_mask_by_color); WM_operatortype_append(SCULPT_OT_dyntopo_detail_size_edit); + + WM_operatortype_append(SCULPT_OT_expand); } diff --git a/source/blender/editors/sculpt_paint/sculpt_boundary.c b/source/blender/editors/sculpt_paint/sculpt_boundary.c index fca19c04b98..f1fb402ae41 100644 --- a/source/blender/editors/sculpt_paint/sculpt_boundary.c +++ b/source/blender/editors/sculpt_paint/sculpt_boundary.c @@ -518,11 +518,13 @@ SculptBoundary *SCULPT_boundary_data_init(Object *object, SculptBoundary *boundary = MEM_callocN(sizeof(SculptBoundary), "Boundary edit data"); - const bool init_boundary_distances = brush->boundary_falloff_type != - BRUSH_BOUNDARY_FALLOFF_CONSTANT; + const bool init_boundary_distances = brush ? brush->boundary_falloff_type != + BRUSH_BOUNDARY_FALLOFF_CONSTANT : + false; + sculpt_boundary_indices_init(ss, boundary, init_boundary_distances, boundary_initial_vertex); - const float boundary_radius = radius * (1.0f + brush->boundary_offset); + const float boundary_radius = brush ? radius * (1.0f + brush->boundary_offset) : radius; sculpt_boundary_edit_data_init(ss, boundary, boundary_initial_vertex, boundary_radius); return boundary; diff --git a/source/blender/editors/sculpt_paint/sculpt_expand.c b/source/blender/editors/sculpt_paint/sculpt_expand.c new file mode 100644 index 00000000000..aaa4bed0d2e --- /dev/null +++ b/source/blender/editors/sculpt_paint/sculpt_expand.c @@ -0,0 +1,2173 @@ +/* + * 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 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * 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) 2021 Blender Foundation. + * All rights reserved. + */ + +/** \file + * \ingroup edsculpt + */ + +#include "MEM_guardedalloc.h" + +#include "BLI_blenlib.h" +#include "BLI_linklist_stack.h" +#include "BLI_math.h" +#include "BLI_task.h" + +#include "BLT_translation.h" + +#include "DNA_brush_types.h" +#include "DNA_mesh_types.h" +#include "DNA_meshdata_types.h" +#include "DNA_object_types.h" + +#include "BKE_brush.h" +#include "BKE_ccg.h" +#include "BKE_colortools.h" +#include "BKE_context.h" +#include "BKE_image.h" +#include "BKE_mesh.h" +#include "BKE_mesh_mapping.h" +#include "BKE_multires.h" +#include "BKE_node.h" +#include "BKE_object.h" +#include "BKE_paint.h" +#include "BKE_pbvh.h" +#include "BKE_report.h" +#include "BKE_scene.h" +#include "BKE_subdiv_ccg.h" + +#include "DEG_depsgraph.h" + +#include "WM_api.h" +#include "WM_message.h" +#include "WM_toolsystem.h" +#include "WM_types.h" + +#include "RNA_access.h" +#include "RNA_define.h" + +#include "ED_object.h" +#include "ED_screen.h" +#include "ED_sculpt.h" +#include "ED_view3d.h" +#include "paint_intern.h" +#include "sculpt_intern.h" + +#include "IMB_colormanagement.h" +#include "IMB_imbuf.h" + +#include "bmesh.h" + +#include <math.h> +#include <stdlib.h> + +/* Sculpt Expand. */ +/* Operator for creating selections and patterns in Sculpt Mode. Expand can create masks, face sets + * and fill vertex colors. */ +/* The main functionality of the operator + * - The operator initializes a value per vertex, called "falloff". There are multiple algorithms + * to generate these falloff values which will create different patterns in the result when using + * the operator. These falloff values require algorithms that rely on mesh connectivity, so they + * are only valid on parts of the mesh that are in the same connected component as the given + * initial vertices. If needed, these falloff values are propagated from vertex or grids into the + * base mesh faces. + * - On each modal callback, the operator gets the active vertex and face and gets its falloff + * value from its precalculated falloff. This is now the active falloff value. + * - Using the active falloff value and the settings of the expand operation (which can be modified + * during execution using the modal keymap), the operator loops over all elements in the mesh to + * check if they are enabled of not. + * - Based on each element state after evaluating the settings, the desired mesh data (mask, face + * sets, colors...) is updated. + */ + +/* Used for defining an invalid vertex state (for example, when the cursor is not over the mesh). + */ +#define SCULPT_EXPAND_VERTEX_NONE -1 + +/* Used for defining an uninitialized active component index for an unused symmetry pass. */ + +#define EXPAND_ACTIVE_COMPONENT_NONE -1 +/* Defines how much each time the texture distortion is increased/decreased when using the modal + * keymap. */ +#define SCULPT_EXPAND_TEXTURE_DISTORTION_STEP 0.01f + +/* This threshold offsets the required falloff value to start a new loop. This is needed because in + * some situations, vertices which have the same falloff value as max_falloff will start a new + * loop, which is undesired. */ +#define SCULPT_EXPAND_LOOP_THRESHOLD 0.00001f + +/* Defines how much changes in curvature in the mesh affect the falloff shape when using normal + * falloff. This default was found experimentally and it works well in most cases, but can be + * exposed for tweaking if needed. */ +#define SCULPT_EXPAND_NORMALS_FALLOFF_EDGE_SENSITIVITY 300 + +/* Expand Modal Keymap. */ +enum { + SCULPT_EXPAND_MODAL_CONFIRM = 1, + SCULPT_EXPAND_MODAL_CANCEL, + SCULPT_EXPAND_MODAL_INVERT, + SCULPT_EXPAND_MODAL_PRESERVE_TOGGLE, + SCULPT_EXPAND_MODAL_GRADIENT_TOGGLE, + SCULPT_EXPAND_MODAL_FALLOFF_CYCLE, + SCULPT_EXPAND_MODAL_RECURSION_STEP_GEODESIC, + SCULPT_EXPAND_MODAL_RECURSION_STEP_TOPOLOGY, + SCULPT_EXPAND_MODAL_MOVE_TOGGLE, + SCULPT_EXPAND_MODAL_FALLOFF_GEODESIC, + SCULPT_EXPAND_MODAL_FALLOFF_TOPOLOGY, + SCULPT_EXPAND_MODAL_FALLOFF_TOPOLOGY_DIAGONALS, + SCULPT_EXPAND_MODAL_FALLOFF_SPHERICAL, + SCULPT_EXPAND_MODAL_SNAP_TOGGLE, + SCULPT_EXPAND_MODAL_LOOP_COUNT_INCREASE, + SCULPT_EXPAND_MODAL_LOOP_COUNT_DECREASE, + SCULPT_EXPAND_MODAL_BRUSH_GRADIENT_TOGGLE, + SCULPT_EXPAND_MODAL_TEXTURE_DISTORTION_INCREASE, + SCULPT_EXPAND_MODAL_TEXTURE_DISTORTION_DECREASE, +}; + +/* Functions for getting the state of mesh elements (vertices and base mesh faces). When the main + * functions for getting the state of an element return true it means that data associated to that + * element will be modified by expand. */ + +/* Returns true if the vertex is in a connected component with correctly initialized falloff + * values. */ +static bool sculpt_expand_is_vert_in_active_component(SculptSession *ss, + ExpandCache *expand_cache, + const int v) +{ + for (int i = 0; i < EXPAND_SYMM_AREAS; i++) { + if (ss->vertex_info.connected_component[v] == expand_cache->active_connected_components[i]) { + return true; + } + } + return false; +} + +/* Returns true if the face is in a connected component with correctly initialized falloff values. + */ +static bool sculpt_expand_is_face_in_active_component(SculptSession *ss, + ExpandCache *expand_cache, + const int f) +{ + const MLoop *loop = &ss->mloop[ss->mpoly[f].loopstart]; + return sculpt_expand_is_vert_in_active_component(ss, expand_cache, loop->v); +} + +/* Returns the falloff value of a vertex. This function includes texture distortion, which is not + * precomputed into the initial falloff values. */ +static float sculpt_expand_falloff_value_vertex_get(SculptSession *ss, + ExpandCache *expand_cache, + const int v) +{ + if (expand_cache->texture_distortion_strength == 0.0f) { + return expand_cache->vert_falloff[v]; + } + + if (!expand_cache->brush->mtex.tex) { + return expand_cache->vert_falloff[v]; + } + + float rgba[4]; + const float *vertex_co = SCULPT_vertex_co_get(ss, v); + const float avg = BKE_brush_sample_tex_3d( + expand_cache->scene, expand_cache->brush, vertex_co, rgba, 0, ss->tex_pool); + + const float distortion = (avg - 0.5f) * expand_cache->texture_distortion_strength * + expand_cache->max_vert_falloff; + return expand_cache->vert_falloff[v] + distortion; +} + +/* Returns the maximum valid falloff value stored in the falloff array, taking the maximum possible + * texture distortion into account. */ +static float sculpt_expand_max_vertex_falloff_get(ExpandCache *expand_cache) +{ + if (expand_cache->texture_distortion_strength == 0.0f) { + return expand_cache->max_vert_falloff; + } + + if (!expand_cache->brush->mtex.tex) { + return expand_cache->max_vert_falloff; + } + + return expand_cache->max_vert_falloff + + (0.5f * expand_cache->texture_distortion_strength * expand_cache->max_vert_falloff); +} + +/* Main function to get the state of a vertex for the current state and settings of a ExpandCache. + * Retruns true when the target data should be modified by expand. + */ +static bool sculpt_expand_state_get(SculptSession *ss, ExpandCache *expand_cache, const int v) +{ + if (!SCULPT_vertex_visible_get(ss, v)) { + return false; + } + + if (!sculpt_expand_is_vert_in_active_component(ss, expand_cache, v)) { + return false; + } + + if (expand_cache->all_enabled) { + return true; + } + + bool enabled = false; + + if (expand_cache->snap) { + /* Face Sets are not being modified when using this function, so it is ok to get this directly + * from the Sculpt API instead of implementing a custom function to get them from + * expand_cache->original_face_sets. */ + const int face_set = SCULPT_vertex_face_set_get(ss, v); + enabled = BLI_gset_haskey(expand_cache->snap_enabled_face_sets, POINTER_FROM_INT(face_set)); + } + else { + const float max_falloff_factor = sculpt_expand_max_vertex_falloff_get(expand_cache); + const float loop_len = (max_falloff_factor / expand_cache->loop_count) + + SCULPT_EXPAND_LOOP_THRESHOLD; + + const float vertex_falloff_factor = sculpt_expand_falloff_value_vertex_get( + ss, expand_cache, v); + const float active_factor = fmod(expand_cache->active_falloff, loop_len); + const float falloff_factor = fmod(vertex_falloff_factor, loop_len); + + enabled = falloff_factor < active_factor; + } + + if (expand_cache->invert) { + enabled = !enabled; + } + return enabled; +} + +/* Main function to get the state of a face for the current state and settings of a ExpandCache. + * Returs true when the traget data should be modified by expand. */ +static bool sculpt_expand_face_state_get(SculptSession *ss, ExpandCache *expand_cache, const int f) +{ + if (ss->face_sets[f] <= 0) { + return false; + } + + if (!sculpt_expand_is_face_in_active_component(ss, expand_cache, f)) { + return false; + } + + if (expand_cache->all_enabled) { + return true; + } + + bool enabled = false; + + if (expand_cache->snap_enabled_face_sets) { + const int face_set = expand_cache->original_face_sets[f]; + enabled = BLI_gset_haskey(expand_cache->snap_enabled_face_sets, POINTER_FROM_INT(face_set)); + } + else { + const float loop_len = (expand_cache->max_face_falloff / expand_cache->loop_count) + + SCULPT_EXPAND_LOOP_THRESHOLD; + + const float active_factor = fmod(expand_cache->active_falloff, loop_len); + const float falloff_factor = fmod(expand_cache->face_falloff[f], loop_len); + enabled = falloff_factor < active_factor; + } + + if (expand_cache->falloff_type == SCULPT_EXPAND_FALLOFF_ACTIVE_FACE_SET) { + if (ss->face_sets[f] == expand_cache->initial_active_face_set) { + enabled = false; + } + } + + if (expand_cache->invert) { + enabled = !enabled; + } + + return enabled; +} + +/* For target modes that support gradients (such as sculpt masks or colors), this function returns + * the corresponding gradient value for an enabled vertex. */ +static float sculpt_expand_gradient_value_get(SculptSession *ss, + ExpandCache *expand_cache, + const int v) +{ + if (!expand_cache->falloff_gradient) { + return 1.0f; + } + + const float max_falloff_factor = sculpt_expand_max_vertex_falloff_get(expand_cache); + const float loop_len = (max_falloff_factor / expand_cache->loop_count) + + SCULPT_EXPAND_LOOP_THRESHOLD; + + const float vertex_falloff_factor = sculpt_expand_falloff_value_vertex_get(ss, expand_cache, v); + const float active_factor = fmod(expand_cache->active_falloff, loop_len); + const float falloff_factor = fmod(vertex_falloff_factor, loop_len); + + float linear_falloff; + + if (expand_cache->invert) { + /* Active factor is the result of a modulus operation using loop_len, so they will never be + * equal and loop_len - active_factor should never be 0. */ + BLI_assert((loop_len - active_factor) != 0.0f); + linear_falloff = (falloff_factor - active_factor) / (loop_len - active_factor); + } + else { + linear_falloff = 1.0f - (falloff_factor / active_factor); + } + + if (!expand_cache->brush_gradient) { + return linear_falloff; + } + + return BKE_brush_curve_strength(expand_cache->brush, linear_falloff, 1.0f); +} + +/* Utility functions for getting all vertices state during expand. */ + +/* Returns a bitmap indexed by vertex index which contains if the vertex was enabled or not for a + * give expand_cache state. */ +static BLI_bitmap *sculpt_expand_bitmap_from_enabled(SculptSession *ss, ExpandCache *expand_cache) +{ + const int totvert = SCULPT_vertex_count_get(ss); + BLI_bitmap *enabled_vertices = BLI_BITMAP_NEW(totvert, "enabled vertices"); + for (int i = 0; i < totvert; i++) { + const bool enabled = sculpt_expand_state_get(ss, expand_cache, i); + BLI_BITMAP_SET(enabled_vertices, i, enabled); + } + return enabled_vertices; +} + +/* Returns a bitmap indexed by vertex index which contains if the vertex is in the boundary of the + * enabled vertices. This is defined as vertices that are enabled and at least have one connected + * vertex that is not enabled. */ +static BLI_bitmap *sculpt_expand_boundary_from_enabled(SculptSession *ss, + BLI_bitmap *enabled_vertices, + const bool use_mesh_boundary) +{ + const int totvert = SCULPT_vertex_count_get(ss); + BLI_bitmap *boundary_vertices = BLI_BITMAP_NEW(totvert, "boundary vertices"); + for (int i = 0; i < totvert; i++) { + if (!BLI_BITMAP_TEST(enabled_vertices, i)) { + continue; + } + + bool is_expand_boundary = false; + SculptVertexNeighborIter ni; + SCULPT_VERTEX_NEIGHBORS_ITER_BEGIN (ss, i, ni) { + if (!BLI_BITMAP_TEST(enabled_vertices, ni.index)) { + is_expand_boundary = true; + } + } + SCULPT_VERTEX_NEIGHBORS_ITER_END(ni); + + if (use_mesh_boundary && SCULPT_vertex_is_boundary(ss, i)) { + is_expand_boundary = true; + } + + BLI_BITMAP_SET(boundary_vertices, i, is_expand_boundary); + } + + return boundary_vertices; +} + +/* Functions implementing different algorithms for initializing falloff values. */ + +/* Utility function to get the closet vertex after flipping an original vertex possition based on + * an symmetry pass iteration index. */ +static int sculpt_expand_get_vertex_index_for_symmetry_pass(Object *ob, + const char symm_it, + const int original_vertex) +{ + SculptSession *ss = ob->sculpt; + int symm_vertex = SCULPT_EXPAND_VERTEX_NONE; + if (symm_it == 0) { + symm_vertex = original_vertex; + } + else { + float location[3]; + flip_v3_v3(location, SCULPT_vertex_co_get(ss, original_vertex), symm_it); + symm_vertex = SCULPT_nearest_vertex_get(NULL, ob, location, FLT_MAX, false); + } + return symm_vertex; +} + +/* Geodesic: Initializes the falloff with geodesic distances from the given active vertex, taking + * symmetry into account. */ +static float *sculpt_expand_geodesic_falloff_create(Sculpt *sd, Object *ob, const int v) +{ + return SCULPT_geodesic_from_vertex_and_symm(sd, ob, v, FLT_MAX); +} + +/* Topology: Initializes the falloff using a floodfill operation, increasing the falloff value by 1 + * when visiting a new vertex. */ +typedef struct ExpandFloodFillData { + float original_normal[3]; + float edge_sensitivity; + float *dists; + float *edge_factor; +} ExpandFloodFillData; + +static bool expand_topology_floodfill_cb( + SculptSession *UNUSED(ss), int from_v, int to_v, bool is_duplicate, void *userdata) +{ + ExpandFloodFillData *data = userdata; + if (!is_duplicate) { + const float to_it = data->dists[from_v] + 1.0f; + data->dists[to_v] = to_it; + } + else { + data->dists[to_v] = data->dists[from_v]; + } + return true; +} + +static float *sculpt_expand_topology_falloff_create(Sculpt *sd, Object *ob, const int v) +{ + SculptSession *ss = ob->sculpt; + const int totvert = SCULPT_vertex_count_get(ss); + float *dists = MEM_calloc_arrayN(sizeof(float), totvert, "topology dist"); + + SculptFloodFill flood; + SCULPT_floodfill_init(ss, &flood); + SCULPT_floodfill_add_initial_with_symmetry(sd, ob, ss, &flood, v, FLT_MAX); + + ExpandFloodFillData fdata; + fdata.dists = dists; + + SCULPT_floodfill_execute(ss, &flood, expand_topology_floodfill_cb, &fdata); + SCULPT_floodfill_free(&flood); + + return dists; +} + +/* Normals: Floodfills the mesh and reduces the falloff depending on the normal difference between + * each vertex and the previous one. This creates falloff pattens that follow and snap to the hard + * edges of the object. */ + +static bool mask_expand_normal_floodfill_cb( + SculptSession *ss, int from_v, int to_v, bool is_duplicate, void *userdata) +{ + ExpandFloodFillData *data = userdata; + if (!is_duplicate) { + float current_normal[3], prev_normal[3]; + SCULPT_vertex_normal_get(ss, to_v, current_normal); + SCULPT_vertex_normal_get(ss, from_v, prev_normal); + const float from_edge_factor = data->edge_factor[from_v]; + data->edge_factor[to_v] = dot_v3v3(current_normal, prev_normal) * from_edge_factor; + data->dists[to_v] = dot_v3v3(data->original_normal, current_normal) * + powf(from_edge_factor, data->edge_sensitivity); + CLAMP(data->dists[to_v], 0.0f, 1.0f); + } + else { + /* PBVH_GRIDS duplicate handling. */ + data->edge_factor[to_v] = data->edge_factor[from_v]; + data->dists[to_v] = data->dists[from_v]; + } + + return true; +} + +static float *sculpt_expand_normal_falloff_create(Sculpt *sd, + Object *ob, + const int v, + const float edge_sensitivity) +{ + SculptSession *ss = ob->sculpt; + const int totvert = SCULPT_vertex_count_get(ss); + float *dists = MEM_malloc_arrayN(sizeof(float), totvert, "normal dist"); + float *edge_factor = MEM_callocN(sizeof(float) * totvert, "mask edge factor"); + for (int i = 0; i < totvert; i++) { + edge_factor[i] = 1.0f; + } + + SculptFloodFill flood; + SCULPT_floodfill_init(ss, &flood); + SCULPT_floodfill_add_initial_with_symmetry(sd, ob, ss, &flood, v, FLT_MAX); + + ExpandFloodFillData fdata; + fdata.dists = dists; + fdata.edge_factor = edge_factor; + fdata.edge_sensitivity = edge_sensitivity; + SCULPT_vertex_normal_get(ss, v, fdata.original_normal); + + SCULPT_floodfill_execute(ss, &flood, mask_expand_normal_floodfill_cb, &fdata); + SCULPT_floodfill_free(&flood); + + for (int repeat = 0; repeat < 2; repeat++) { + for (int i = 0; i < totvert; i++) { + float avg = 0.0f; + SculptVertexNeighborIter ni; + SCULPT_VERTEX_NEIGHBORS_ITER_BEGIN (ss, i, ni) { + avg += dists[ni.index]; + } + SCULPT_VERTEX_NEIGHBORS_ITER_END(ni); + dists[i] = avg / ni.size; + } + } + + MEM_SAFE_FREE(edge_factor); + + return dists; +} + +/* Spherical: Initializes the falloff based on the distance from a vertex, taking symmetry into + * account. */ + +static float *sculpt_expand_spherical_falloff_create(Object *ob, const int v) +{ + SculptSession *ss = ob->sculpt; + const int totvert = SCULPT_vertex_count_get(ss); + + float *dists = MEM_malloc_arrayN(sizeof(float), totvert, "spherical dist"); + for (int i = 0; i < totvert; i++) { + dists[i] = FLT_MAX; + } + const char symm = SCULPT_mesh_symmetry_xyz_get(ob); + + for (char symm_it = 0; symm_it <= symm; symm_it++) { + if (!SCULPT_is_symmetry_iteration_valid(symm_it, symm)) { + continue; + } + const int symm_vertex = sculpt_expand_get_vertex_index_for_symmetry_pass(ob, symm_it, v); + if (symm_vertex != -1) { + const float *co = SCULPT_vertex_co_get(ss, symm_vertex); + for (int i = 0; i < totvert; i++) { + dists[i] = min_ff(dists[i], len_v3v3(co, SCULPT_vertex_co_get(ss, i))); + } + } + } + + return dists; +} + +/* Boundary: This falloff mode uses the code from sculpt_boundary to initialize the closest mesh + * boundary to a falloff value of 0. Then, it propagates that falloff to the rest of the mesh so it + * stays parallel to the boundary, increasing the falloff value by 1 on each step. */ +static float *sculpt_expand_boundary_topology_falloff_create(Object *ob, const int v) +{ + SculptSession *ss = ob->sculpt; + const int totvert = SCULPT_vertex_count_get(ss); + float *dists = MEM_calloc_arrayN(sizeof(float), totvert, "spherical dist"); + BLI_bitmap *visited_vertices = BLI_BITMAP_NEW(totvert, "visited vertices"); + GSQueue *queue = BLI_gsqueue_new(sizeof(int)); + + /* Search and initialize a boundary per symmetry pass, then mark those vertices as visited. */ + const char symm = SCULPT_mesh_symmetry_xyz_get(ob); + for (char symm_it = 0; symm_it <= symm; symm_it++) { + if (!SCULPT_is_symmetry_iteration_valid(symm_it, symm)) { + continue; + } + + const int symm_vertex = sculpt_expand_get_vertex_index_for_symmetry_pass(ob, symm_it, v); + + SculptBoundary *boundary = SCULPT_boundary_data_init(ob, NULL, symm_vertex, FLT_MAX); + if (!boundary) { + continue; + } + + for (int i = 0; i < boundary->num_vertices; i++) { + BLI_gsqueue_push(queue, &boundary->vertices[i]); + BLI_BITMAP_ENABLE(visited_vertices, boundary->vertices[i]); + } + SCULPT_boundary_data_free(boundary); + } + + /* If there are no boundaries, return a falloff with all values set to 0. */ + if (BLI_gsqueue_is_empty(queue)) { + return dists; + } + + /* Propagate the values from the boundaries to the rest of the mesh. */ + while (!BLI_gsqueue_is_empty(queue)) { + int v_next; + BLI_gsqueue_pop(queue, &v_next); + + SculptVertexNeighborIter ni; + SCULPT_VERTEX_NEIGHBORS_ITER_BEGIN (ss, v_next, ni) { + if (BLI_BITMAP_TEST(visited_vertices, ni.index)) { + continue; + } + dists[ni.index] = dists[v_next] + 1.0f; + BLI_BITMAP_ENABLE(visited_vertices, ni.index); + BLI_gsqueue_push(queue, &ni.index); + } + SCULPT_VERTEX_NEIGHBORS_ITER_END(ni); + } + + BLI_gsqueue_free(queue); + MEM_freeN(visited_vertices); + return dists; +} + +/* Topology diagonals. This falloff is similar to topology, but it also considers the diagonals of + * the base mesh faces when checking a vertex neighbor. For this reason, this is not implement + * using the general floodfill and sculpt neighbors accessors. */ +static float *sculpt_expand_diagonals_falloff_create(Object *ob, const int v) +{ + SculptSession *ss = ob->sculpt; + const int totvert = SCULPT_vertex_count_get(ss); + float *dists = MEM_calloc_arrayN(sizeof(float), totvert, "spherical dist"); + + /* This algorithm uses mesh data (polys and loops), so this falloff type can't be initialized for + * Multires. It also does not make sense to implement it for dyntopo as the result will be the + * same as Topology falloff. */ + if (BKE_pbvh_type(ss->pbvh) != PBVH_FACES) { + return dists; + } + + /* Search and mask as visited the initial vertices using the enabled symmetry passes. */ + BLI_bitmap *visited_vertices = BLI_BITMAP_NEW(totvert, "visited vertices"); + GSQueue *queue = BLI_gsqueue_new(sizeof(int)); + const char symm = SCULPT_mesh_symmetry_xyz_get(ob); + for (char symm_it = 0; symm_it <= symm; symm_it++) { + if (!SCULPT_is_symmetry_iteration_valid(symm_it, symm)) { + continue; + } + + const int symm_vertex = sculpt_expand_get_vertex_index_for_symmetry_pass(ob, symm_it, v); + + BLI_gsqueue_push(queue, &symm_vertex); + BLI_BITMAP_ENABLE(visited_vertices, symm_vertex); + } + + if (BLI_gsqueue_is_empty(queue)) { + return dists; + } + + /* Propagate the falloff increasing the value by 1 each time a new vertex is visited. */ + Mesh *mesh = ob->data; + while (!BLI_gsqueue_is_empty(queue)) { + int v_next; + BLI_gsqueue_pop(queue, &v_next); + for (int j = 0; j < ss->pmap[v_next].count; j++) { + MPoly *p = &ss->mpoly[ss->pmap[v_next].indices[j]]; + for (int l = 0; l < p->totloop; l++) { + const int neighbor_v = mesh->mloop[p->loopstart + l].v; + if (BLI_BITMAP_TEST(visited_vertices, neighbor_v)) { + continue; + } + dists[neighbor_v] = dists[v_next] + 1.0f; + BLI_BITMAP_ENABLE(visited_vertices, neighbor_v); + BLI_gsqueue_push(queue, &neighbor_v); + } + } + } + + BLI_gsqueue_free(queue); + MEM_freeN(visited_vertices); + return dists; +} + +/* Functions to update the max_falloff value in the ExpandCache. These funcions are called after + * initializing a new falloff to make sure that this value is always updated. */ + +/* Updates the max_falloff value for vertices in a ExpandCache based on the current values of the + * falloff, skipping any invalid values initialized to FLT_MAX and not initialized components. */ +static void sculpt_expand_update_max_vert_falloff_value(SculptSession *ss, + ExpandCache *expand_cache) +{ + const int totvert = SCULPT_vertex_count_get(ss); + expand_cache->max_vert_falloff = -FLT_MAX; + for (int i = 0; i < totvert; i++) { + if (expand_cache->vert_falloff[i] == FLT_MAX) { + continue; + } + + if (!sculpt_expand_is_vert_in_active_component(ss, expand_cache, i)) { + continue; + } + + expand_cache->max_vert_falloff = max_ff(expand_cache->max_vert_falloff, + expand_cache->vert_falloff[i]); + } +} + +/* Updates the max_falloff value for faces in a ExpandCache based on the current values of the + * falloff, skipping any invalid values initialized to FLT_MAX and not initialized components. */ +static void sculpt_expand_update_max_face_falloff_factor(SculptSession *ss, + ExpandCache *expand_cache) +{ + const int totface = ss->totfaces; + expand_cache->max_face_falloff = -FLT_MAX; + for (int i = 0; i < totface; i++) { + if (expand_cache->face_falloff[i] == FLT_MAX) { + continue; + } + + if (!sculpt_expand_is_face_in_active_component(ss, expand_cache, i)) { + continue; + } + + expand_cache->max_face_falloff = max_ff(expand_cache->max_face_falloff, + expand_cache->face_falloff[i]); + } +} + +/* Functions to get falloff values for faces from the values from the vertices. This is used for + * expanding Face Sets. Depending on the data type of the SculptSession, this needs to get the per + * face falloff value from the connected vertices of each face or from the grids stored per loops + * for each face. */ +static void sculpt_expand_grids_to_faces_falloff(SculptSession *ss, + Mesh *mesh, + ExpandCache *expand_cache) +{ + + const CCGKey *key = BKE_pbvh_get_grid_key(ss->pbvh); + + for (int p = 0; p < mesh->totpoly; p++) { + MPoly *poly = &mesh->mpoly[p]; + float accum = 0.0f; + for (int l = 0; l < poly->totloop; l++) { + const int grid_loop_index = (poly->loopstart + l) * key->grid_area; + for (int g = 0; g < key->grid_area; g++) { + accum += expand_cache->vert_falloff[grid_loop_index + g]; + } + } + expand_cache->face_falloff[p] = accum / (poly->totloop * key->grid_area); + } +} + +static void sculpt_expand_vertex_to_faces_falloff(Mesh *mesh, ExpandCache *expand_cache) +{ + for (int p = 0; p < mesh->totpoly; p++) { + MPoly *poly = &mesh->mpoly[p]; + float accum = 0.0f; + for (int l = 0; l < poly->totloop; l++) { + MLoop *loop = &mesh->mloop[l + poly->loopstart]; + accum += expand_cache->vert_falloff[loop->v]; + } + expand_cache->face_falloff[p] = accum / poly->totloop; + } +} + +/* Main function to update the faces falloff from a already calculated vertex falloff. */ +static void sculpt_expand_mesh_face_falloff_from_vertex_falloff(SculptSession *ss, + Mesh *mesh, + ExpandCache *expand_cache) +{ + BLI_assert(expand_cache->vert_falloff != NULL); + + if (!expand_cache->face_falloff) { + expand_cache->face_falloff = MEM_malloc_arrayN( + mesh->totpoly, sizeof(float), "face falloff factors"); + } + + if (BKE_pbvh_type(ss->pbvh) == PBVH_FACES) { + sculpt_expand_vertex_to_faces_falloff(mesh, expand_cache); + } + else if (BKE_pbvh_type(ss->pbvh) == PBVH_GRIDS) { + sculpt_expand_grids_to_faces_falloff(ss, mesh, expand_cache); + } + else { + BLI_assert(false); + } +} + +/* Recursions. These functions will generate new falloff values based on the state of the vertices + * from the current ExpandCache options and falloff values. */ + +/* Geodesic recursion: Initializes falloff values using geodesic distances from the boundary of the + * current vertices state. */ +static void sculpt_expand_geodesics_from_state_boundary(Object *ob, + ExpandCache *expand_cache, + BLI_bitmap *enabled_vertices) +{ + SculptSession *ss = ob->sculpt; + BLI_assert(BKE_pbvh_type(ss->pbvh) == PBVH_FACES); + + GSet *initial_vertices = BLI_gset_int_new("initial_vertices"); + BLI_bitmap *boundary_vertices = sculpt_expand_boundary_from_enabled(ss, enabled_vertices, false); + const int totvert = SCULPT_vertex_count_get(ss); + for (int i = 0; i < totvert; i++) { + if (!BLI_BITMAP_TEST(boundary_vertices, i)) { + continue; + } + BLI_gset_add(initial_vertices, POINTER_FROM_INT(i)); + } + MEM_freeN(boundary_vertices); + + MEM_SAFE_FREE(expand_cache->vert_falloff); + MEM_SAFE_FREE(expand_cache->face_falloff); + + expand_cache->vert_falloff = SCULPT_geodesic_distances_create(ob, initial_vertices, FLT_MAX); + BLI_gset_free(initial_vertices, NULL); +} + +/* Topology recursion: Initializes falloff values using topology steps from the boundary of the + * current vertices state, increasing the value by 1 each time a new vertex is visited. */ +static void sculpt_expand_topology_from_state_boundary(Object *ob, + ExpandCache *expand_cache, + BLI_bitmap *enabled_vertices) +{ + MEM_SAFE_FREE(expand_cache->vert_falloff); + MEM_SAFE_FREE(expand_cache->face_falloff); + + SculptSession *ss = ob->sculpt; + const int totvert = SCULPT_vertex_count_get(ss); + + float *dists = MEM_calloc_arrayN(sizeof(float), totvert, "topology dist"); + BLI_bitmap *boundary_vertices = sculpt_expand_boundary_from_enabled(ss, enabled_vertices, false); + + SculptFloodFill flood; + SCULPT_floodfill_init(ss, &flood); + for (int i = 0; i < totvert; i++) { + if (!BLI_BITMAP_TEST(boundary_vertices, i)) { + continue; + } + SCULPT_floodfill_add_and_skip_initial(&flood, i); + } + MEM_freeN(boundary_vertices); + + ExpandFloodFillData fdata; + fdata.dists = dists; + SCULPT_floodfill_execute(ss, &flood, expand_topology_floodfill_cb, &fdata); + SCULPT_floodfill_free(&flood); + + expand_cache->vert_falloff = dists; +} + +/* Main function to create a recursion step from the current ExpandCache state. */ +static void sculpt_expand_resursion_step_add(Object *ob, + ExpandCache *expand_cache, + const eSculptExpandRecursionType recursion_type) +{ + SculptSession *ss = ob->sculpt; + if (BKE_pbvh_type(ss->pbvh) != PBVH_FACES) { + return; + } + + BLI_bitmap *enabled_vertices = sculpt_expand_bitmap_from_enabled(ss, expand_cache); + + /* Each time a new recursion step is created, reset the distortion strength. This is the expected + * result from the recursion, as otherwise the new falloff will render with undesired distortion + * from the beginning. */ + expand_cache->texture_distortion_strength = 0.0f; + + switch (recursion_type) { + case SCULPT_EXPAND_RECURSION_GEODESICS: + sculpt_expand_geodesics_from_state_boundary(ob, expand_cache, enabled_vertices); + break; + case SCULPT_EXPAND_RECURSION_TOPOLOGY: + sculpt_expand_topology_from_state_boundary(ob, expand_cache, enabled_vertices); + break; + } + + sculpt_expand_update_max_vert_falloff_value(ss, expand_cache); + if (expand_cache->target == SCULPT_EXPAND_TARGET_FACE_SETS) { + sculpt_expand_mesh_face_falloff_from_vertex_falloff(ss, ob->data, expand_cache); + sculpt_expand_update_max_face_falloff_factor(ss, expand_cache); + } + + MEM_freeN(enabled_vertices); +} + +/* Face Set Boundary falloff. */ +/* When internal falloff is set to true, the falloff will fill the active Face Set with a gradient, + * otherwise the active Face Set will be filled with a constant falloff of 0.0f. */ +static void sculpt_expand_initialize_from_face_set_boundary(Object *ob, + ExpandCache *expand_cache, + const int active_face_set, + const bool internal_falloff) +{ + SculptSession *ss = ob->sculpt; + const int totvert = SCULPT_vertex_count_get(ss); + + BLI_bitmap *enabled_vertices = BLI_BITMAP_NEW(totvert, "enabled vertices"); + for (int i = 0; i < totvert; i++) { + if (!SCULPT_vertex_has_unique_face_set(ss, i)) { + continue; + } + if (!SCULPT_vertex_has_face_set(ss, i, active_face_set)) { + continue; + } + BLI_BITMAP_ENABLE(enabled_vertices, i); + } + + if (BKE_pbvh_type(ss->pbvh) == PBVH_FACES) { + sculpt_expand_geodesics_from_state_boundary(ob, expand_cache, enabled_vertices); + } + else { + sculpt_expand_topology_from_state_boundary(ob, expand_cache, enabled_vertices); + } + + MEM_freeN(enabled_vertices); + + if (internal_falloff) { + for (int i = 0; i < totvert; i++) { + if (!(SCULPT_vertex_has_face_set(ss, i, active_face_set) && + SCULPT_vertex_has_unique_face_set(ss, i))) { + continue; + } + expand_cache->vert_falloff[i] *= -1.0f; + } + + float min_factor = FLT_MAX; + for (int i = 0; i < totvert; i++) { + min_factor = min_ff(expand_cache->vert_falloff[i], min_factor); + } + + const float additional_falloff = fabsf(min_factor); + for (int i = 0; i < totvert; i++) { + expand_cache->vert_falloff[i] += additional_falloff; + } + } + else { + for (int i = 0; i < totvert; i++) { + if (!SCULPT_vertex_has_face_set(ss, i, active_face_set)) { + continue; + } + expand_cache->vert_falloff[i] = 0.0f; + } + } +} + +/* Main function to initialize new falloff values in a ExpandCache given an initial vertex and a + * falloff type. */ +static void sculpt_expand_falloff_factors_from_vertex_and_symm_create( + ExpandCache *expand_cache, + Sculpt *sd, + Object *ob, + const int v, + eSculptExpandFalloffType falloff_type) +{ + MEM_SAFE_FREE(expand_cache->vert_falloff); + expand_cache->falloff_type = falloff_type; + + SculptSession *ss = ob->sculpt; + const bool has_topology_info = BKE_pbvh_type(ss->pbvh) == PBVH_FACES; + + switch (falloff_type) { + case SCULPT_EXPAND_FALLOFF_GEODESIC: + expand_cache->vert_falloff = has_topology_info ? + sculpt_expand_geodesic_falloff_create(sd, ob, v) : + sculpt_expand_spherical_falloff_create(ob, v); + break; + case SCULPT_EXPAND_FALLOFF_TOPOLOGY: + expand_cache->vert_falloff = sculpt_expand_topology_falloff_create(sd, ob, v); + break; + case SCULPT_EXPAND_FALLOFF_TOPOLOGY_DIAGONALS: + expand_cache->vert_falloff = has_topology_info ? + sculpt_expand_diagonals_falloff_create(ob, v) : + sculpt_expand_topology_falloff_create(sd, ob, v); + break; + case SCULPT_EXPAND_FALLOFF_NORMALS: + expand_cache->vert_falloff = sculpt_expand_normal_falloff_create( + sd, ob, v, SCULPT_EXPAND_NORMALS_FALLOFF_EDGE_SENSITIVITY); + break; + case SCULPT_EXPAND_FALLOFF_SPHERICAL: + expand_cache->vert_falloff = sculpt_expand_spherical_falloff_create(ob, v); + break; + case SCULPT_EXPAND_FALLOFF_BOUNDARY_TOPOLOGY: + expand_cache->vert_falloff = sculpt_expand_boundary_topology_falloff_create(ob, v); + break; + case SCULPT_EXPAND_FALLOFF_BOUNDARY_FACE_SET: + sculpt_expand_initialize_from_face_set_boundary( + ob, expand_cache, expand_cache->initial_active_face_set, true); + break; + case SCULPT_EXPAND_FALLOFF_ACTIVE_FACE_SET: + sculpt_expand_initialize_from_face_set_boundary( + ob, expand_cache, expand_cache->initial_active_face_set, false); + break; + } + + /* Update max falloff values and propagate to base mesh faces if needed. */ + sculpt_expand_update_max_vert_falloff_value(ss, expand_cache); + if (expand_cache->target == SCULPT_EXPAND_TARGET_FACE_SETS) { + sculpt_expand_mesh_face_falloff_from_vertex_falloff(ss, ob->data, expand_cache); + sculpt_expand_update_max_face_falloff_factor(ss, expand_cache); + } +} + +/* Adds to the snapping Face Set gset all Face Sets which contain all enabled vertices for the + * current ExpandCache state. This improves the usability of snapping, as already enabled elements + * won't switch their state when toggling snapping with the modal keymap.*/ +static void sculpt_expand_snap_initialize_from_enabled(SculptSession *ss, + ExpandCache *expand_cache) +{ + if (BKE_pbvh_type(ss->pbvh) != PBVH_FACES) { + return; + } + + /* Make sure this code runs with snapping and invert disabled. This simplifies the code and + * prevents using this function with snapping already enabled. */ + const bool prev_snap_state = expand_cache->snap; + const bool prev_invert_state = expand_cache->invert; + expand_cache->snap = false; + expand_cache->invert = false; + + BLI_bitmap *enabled_vertices = sculpt_expand_bitmap_from_enabled(ss, expand_cache); + + const int totface = ss->totfaces; + for (int i = 0; i < totface; i++) { + const int face_set = expand_cache->original_face_sets[i]; + BLI_gset_add(expand_cache->snap_enabled_face_sets, POINTER_FROM_INT(face_set)); + } + + for (int p = 0; p < totface; p++) { + MPoly *poly = &ss->mpoly[p]; + bool any_disabled = false; + for (int l = 0; l < poly->totloop; l++) { + MLoop *loop = &ss->mloop[l + poly->loopstart]; + if (!BLI_BITMAP_TEST(enabled_vertices, loop->v)) { + any_disabled = true; + break; + } + } + if (any_disabled) { + const int face_set = expand_cache->original_face_sets[p]; + BLI_gset_remove(expand_cache->snap_enabled_face_sets, POINTER_FROM_INT(face_set), NULL); + } + } + + MEM_freeN(enabled_vertices); + expand_cache->snap = prev_snap_state; + expand_cache->invert = prev_invert_state; +} + +/* Functions to free a ExpandCache. */ +static void sculpt_expand_cache_data_free(ExpandCache *expand_cache) +{ + if (expand_cache->snap_enabled_face_sets) { + BLI_gset_free(expand_cache->snap_enabled_face_sets, NULL); + } + MEM_SAFE_FREE(expand_cache->nodes); + MEM_SAFE_FREE(expand_cache->vert_falloff); + MEM_SAFE_FREE(expand_cache->face_falloff); + MEM_SAFE_FREE(expand_cache->original_mask); + MEM_SAFE_FREE(expand_cache->original_face_sets); + MEM_SAFE_FREE(expand_cache->initial_face_sets); + MEM_SAFE_FREE(expand_cache->original_colors); + MEM_SAFE_FREE(expand_cache); +} + +static void sculpt_expand_cache_free(SculptSession *ss) +{ + sculpt_expand_cache_data_free(ss->expand_cache); + /* Needs to be set to NULL as the paint cursor relies on checking this pointer detecting if an + * expand operation is running. */ + ss->expand_cache = NULL; +} + +/* Functions to restore the original state from the ExpandCache when canceling the operator. */ +static void sculpt_expand_restore_face_set_data(SculptSession *ss, ExpandCache *expand_cache) +{ + PBVHNode **nodes; + int totnode; + BKE_pbvh_search_gather(ss->pbvh, NULL, NULL, &nodes, &totnode); + for (int n = 0; n < totnode; n++) { + PBVHNode *node = nodes[n]; + BKE_pbvh_node_mark_redraw(node); + } + MEM_freeN(nodes); + for (int i = 0; i < ss->totfaces; i++) { + ss->face_sets[i] = expand_cache->original_face_sets[i]; + } +} + +static void sculpt_expand_restore_color_data(SculptSession *ss, ExpandCache *expand_cache) +{ + PBVHNode **nodes; + int totnode; + BKE_pbvh_search_gather(ss->pbvh, NULL, NULL, &nodes, &totnode); + for (int n = 0; n < totnode; n++) { + PBVHNode *node = nodes[n]; + PBVHVertexIter vd; + BKE_pbvh_vertex_iter_begin(ss->pbvh, node, vd, PBVH_ITER_UNIQUE) + { + copy_v4_v4(vd.col, expand_cache->original_colors[vd.index]); + } + BKE_pbvh_vertex_iter_end; + BKE_pbvh_node_mark_redraw(node); + } + MEM_freeN(nodes); +} + +static void sculpt_expand_restore_mask_data(SculptSession *ss, ExpandCache *expand_cache) +{ + PBVHNode **nodes; + int totnode; + BKE_pbvh_search_gather(ss->pbvh, NULL, NULL, &nodes, &totnode); + for (int n = 0; n < totnode; n++) { + PBVHNode *node = nodes[n]; + PBVHVertexIter vd; + BKE_pbvh_vertex_iter_begin(ss->pbvh, node, vd, PBVH_ITER_UNIQUE) + { + *vd.mask = expand_cache->original_mask[vd.index]; + } + BKE_pbvh_vertex_iter_end; + BKE_pbvh_node_mark_redraw(node); + } + MEM_freeN(nodes); +} + +/* Main function to restore the original state of the data to how it was before starting the expand + * operation. */ +static void sculpt_expand_restore_original_state(bContext *C, + Object *ob, + ExpandCache *expand_cache) +{ + + SculptSession *ss = ob->sculpt; + switch (expand_cache->target) { + case SCULPT_EXPAND_TARGET_MASK: + sculpt_expand_restore_mask_data(ss, expand_cache); + SCULPT_flush_update_step(C, SCULPT_UPDATE_MASK); + SCULPT_flush_update_done(C, ob, SCULPT_UPDATE_MASK); + SCULPT_tag_update_overlays(C); + break; + case SCULPT_EXPAND_TARGET_FACE_SETS: + sculpt_expand_restore_face_set_data(ss, expand_cache); + SCULPT_flush_update_step(C, SCULPT_UPDATE_MASK); + SCULPT_flush_update_done(C, ob, SCULPT_UPDATE_MASK); + SCULPT_tag_update_overlays(C); + break; + case SCULPT_EXPAND_TARGET_COLORS: + sculpt_expand_restore_color_data(ss, expand_cache); + SCULPT_flush_update_step(C, SCULPT_UPDATE_COLOR); + SCULPT_flush_update_done(C, ob, SCULPT_UPDATE_COLOR); + break; + } +} + +/* Cancel operator callback. */ +static void sculpt_expand_cancel(bContext *C, wmOperator *UNUSED(op)) +{ + Object *ob = CTX_data_active_object(C); + SculptSession *ss = ob->sculpt; + + sculpt_expand_restore_original_state(C, ob, ss->expand_cache); + + SCULPT_undo_push_end(); + sculpt_expand_cache_free(ss); +} + +/* Functions to update the sculpt mesh data. */ + +/* Callback to update mask data per PBVH node. */ +static void sculpt_expand_mask_update_task_cb(void *__restrict userdata, + const int i, + const TaskParallelTLS *__restrict UNUSED(tls)) +{ + SculptThreadedTaskData *data = userdata; + SculptSession *ss = data->ob->sculpt; + PBVHNode *node = data->nodes[i]; + ExpandCache *expand_cache = ss->expand_cache; + + bool any_changed = false; + + PBVHVertexIter vd; + BKE_pbvh_vertex_iter_begin(ss->pbvh, node, vd, PBVH_ITER_ALL) + { + const float initial_mask = *vd.mask; + const bool enabled = sculpt_expand_state_get(ss, expand_cache, vd.index); + + float new_mask; + + if (enabled) { + new_mask = sculpt_expand_gradient_value_get(ss, expand_cache, vd.index); + } + else { + new_mask = 0.0f; + } + + if (expand_cache->preserve) { + new_mask = max_ff(new_mask, expand_cache->original_mask[vd.index]); + } + + if (new_mask == initial_mask) { + continue; + } + + *vd.mask = clamp_f(new_mask, 0.0f, 1.0f); + any_changed = true; + if (vd.mvert) { + vd.mvert->flag |= ME_VERT_PBVH_UPDATE; + } + } + BKE_pbvh_vertex_iter_end; + if (any_changed) { + BKE_pbvh_node_mark_update_mask(node); + } +} + +/* Update Face Set data. Not multithreaded per node as nodes don't contain face arrays. */ +static void sculpt_expand_face_sets_update(SculptSession *ss, ExpandCache *expand_cache) +{ + const int totface = ss->totfaces; + for (int f = 0; f < totface; f++) { + const bool enabled = sculpt_expand_face_state_get(ss, expand_cache, f); + if (!enabled) { + continue; + } + if (expand_cache->preserve) { + ss->face_sets[f] += expand_cache->next_face_set; + } + else { + ss->face_sets[f] = expand_cache->next_face_set; + } + } + + for (int i = 0; i < expand_cache->totnode; i++) { + BKE_pbvh_node_mark_redraw(ss->expand_cache->nodes[i]); + } +} + +/* Callback to update vertex colors per PBVH node. */ +static void sculpt_expand_colors_update_task_cb(void *__restrict userdata, + const int i, + const TaskParallelTLS *__restrict UNUSED(tls)) +{ + SculptThreadedTaskData *data = userdata; + SculptSession *ss = data->ob->sculpt; + PBVHNode *node = data->nodes[i]; + ExpandCache *expand_cache = ss->expand_cache; + + bool any_changed = false; + + PBVHVertexIter vd; + BKE_pbvh_vertex_iter_begin(ss->pbvh, node, vd, PBVH_ITER_ALL) + { + float initial_color[4]; + copy_v4_v4(initial_color, vd.col); + + const bool enabled = sculpt_expand_state_get(ss, expand_cache, vd.index); + float fade; + + if (enabled) { + fade = sculpt_expand_gradient_value_get(ss, expand_cache, vd.index); + } + else { + fade = 0.0f; + } + + fade *= 1.0f - *vd.mask; + fade = clamp_f(fade, 0.0f, 1.0f); + + float final_color[4]; + float final_fill_color[4]; + mul_v4_v4fl(final_fill_color, expand_cache->fill_color, fade); + IMB_blend_color_float(final_color, + expand_cache->original_colors[vd.index], + final_fill_color, + expand_cache->blend_mode); + + if (equals_v4v4(initial_color, final_color)) { + continue; + } + + copy_v4_v4(vd.col, final_color); + any_changed = true; + if (vd.mvert) { + vd.mvert->flag |= ME_VERT_PBVH_UPDATE; + } + } + BKE_pbvh_vertex_iter_end; + if (any_changed) { + BKE_pbvh_node_mark_update_color(node); + } +} + +static void sculpt_expand_flush_updates(bContext *C) +{ + Object *ob = CTX_data_active_object(C); + SculptSession *ss = ob->sculpt; + switch (ss->expand_cache->target) { + case SCULPT_EXPAND_TARGET_MASK: + SCULPT_flush_update_step(C, SCULPT_UPDATE_MASK); + break; + case SCULPT_EXPAND_TARGET_FACE_SETS: + SCULPT_flush_update_step(C, SCULPT_UPDATE_MASK); + break; + case SCULPT_EXPAND_TARGET_COLORS: + SCULPT_flush_update_step(C, SCULPT_UPDATE_COLOR); + break; + default: + break; + } +} + +/* Store the original mesh data state in the expand cache. */ +static void sculpt_expand_original_state_store(Object *ob, ExpandCache *expand_cache) +{ + SculptSession *ss = ob->sculpt; + const int totvert = SCULPT_vertex_count_get(ss); + const int totface = ss->totfaces; + + /* Face Sets are always stored as they are needed for snapping. */ + expand_cache->initial_face_sets = MEM_malloc_arrayN(totface, sizeof(int), "initial face set"); + expand_cache->original_face_sets = MEM_malloc_arrayN(totface, sizeof(int), "original face set"); + for (int i = 0; i < totface; i++) { + expand_cache->initial_face_sets[i] = ss->face_sets[i]; + expand_cache->original_face_sets[i] = ss->face_sets[i]; + } + + if (expand_cache->target == SCULPT_EXPAND_TARGET_MASK) { + expand_cache->original_mask = MEM_malloc_arrayN(totvert, sizeof(float), "initial mask"); + for (int i = 0; i < totvert; i++) { + expand_cache->original_mask[i] = SCULPT_vertex_mask_get(ss, i); + } + } + + if (expand_cache->target == SCULPT_EXPAND_TARGET_COLORS) { + expand_cache->original_colors = MEM_malloc_arrayN(totvert, sizeof(float[4]), "initial colors"); + for (int i = 0; i < totvert; i++) { + copy_v4_v4(expand_cache->original_colors[i], SCULPT_vertex_color_get(ss, i)); + } + } +} + +/* Restore the state of the Face Sets before a new update. */ +static void sculpt_expand_face_sets_restore(SculptSession *ss, ExpandCache *expand_cache) +{ + const int totfaces = ss->totfaces; + for (int i = 0; i < totfaces; i++) { + ss->face_sets[i] = expand_cache->initial_face_sets[i]; + } +} + +static void sculpt_expand_update_for_vertex(bContext *C, Object *ob, const int vertex) +{ + SculptSession *ss = ob->sculpt; + Sculpt *sd = CTX_data_tool_settings(C)->sculpt; + ExpandCache *expand_cache = ss->expand_cache; + + /* Update the active factor in the cache. */ + if (vertex == SCULPT_EXPAND_VERTEX_NONE) { + /* This means that the cursor is not over the mesh, so a valid active falloff can't be + * determined. In this situations, don't evaluate enabled states and default all vertices in + * connected components to enabled. */ + expand_cache->active_falloff = expand_cache->max_vert_falloff; + expand_cache->all_enabled = true; + } + else { + expand_cache->active_falloff = expand_cache->vert_falloff[vertex]; + expand_cache->all_enabled = false; + } + + if (expand_cache->target == SCULPT_EXPAND_TARGET_FACE_SETS) { + /* Face sets needs to be restored their initial state on each iteration as the overwrite + * existing data. */ + sculpt_expand_face_sets_restore(ss, expand_cache); + } + + /* Update the mesh sculpt data. */ + SculptThreadedTaskData data = { + .sd = sd, + .ob = ob, + .nodes = expand_cache->nodes, + }; + + TaskParallelSettings settings; + BKE_pbvh_parallel_range_settings(&settings, true, expand_cache->totnode); + + switch (expand_cache->target) { + case SCULPT_EXPAND_TARGET_MASK: + BLI_task_parallel_range( + 0, expand_cache->totnode, &data, sculpt_expand_mask_update_task_cb, &settings); + break; + case SCULPT_EXPAND_TARGET_FACE_SETS: + sculpt_expand_face_sets_update(ss, expand_cache); + break; + case SCULPT_EXPAND_TARGET_COLORS: + BLI_task_parallel_range( + 0, expand_cache->totnode, &data, sculpt_expand_colors_update_task_cb, &settings); + break; + } + + sculpt_expand_flush_updates(C); +} + +/* Updates the SculptSession cursor data and gets the active vertex if the cursor is over the mesh. + */ +static int sculpt_expand_target_vertex_update_and_get(bContext *C, + Object *ob, + const float mouse[2]) +{ + SculptSession *ss = ob->sculpt; + SculptCursorGeometryInfo sgi; + if (SCULPT_cursor_geometry_info_update(C, &sgi, mouse, false)) { + return SCULPT_active_vertex_get(ss); + } + else { + return SCULPT_EXPAND_VERTEX_NONE; + } +} + +/* Moves the sculpt pivot to the average point of the boundary enabled vertices of the current + * expand state. Take symmetry and active components into account. */ +static void sculpt_expand_reposition_pivot(bContext *C, Object *ob, ExpandCache *expand_cache) +{ + SculptSession *ss = ob->sculpt; + const char symm = SCULPT_mesh_symmetry_xyz_get(ob); + const int totvert = SCULPT_vertex_count_get(ss); + + const bool initial_invert_state = expand_cache->invert; + expand_cache->invert = false; + BLI_bitmap *enabled_vertices = sculpt_expand_bitmap_from_enabled(ss, expand_cache); + + /* For boundary topology, position the pivot using only the boundary of the enabled vertices, + * without taking mesh boundary into account. This allows to creat deformations like bending the + * mesh from the boundary of the mask that was just created. */ + const float use_mesh_boundary = expand_cache->falloff_type != + SCULPT_EXPAND_FALLOFF_BOUNDARY_TOPOLOGY; + + BLI_bitmap *boundary_vertices = sculpt_expand_boundary_from_enabled( + ss, enabled_vertices, use_mesh_boundary); + + /* Ignore invert state, as this is the expected behaviour in most cases and mask are created in + * inverted state by default. */ + expand_cache->invert = initial_invert_state; + + int total = 0; + float avg[3] = {0.0f}; + + const float *expand_init_co = SCULPT_vertex_co_get(ss, expand_cache->initial_active_vertex); + + for (int i = 0; i < totvert; i++) { + if (!BLI_BITMAP_TEST(boundary_vertices, i)) { + continue; + } + + if (!sculpt_expand_is_vert_in_active_component(ss, expand_cache, i)) { + continue; + } + + const float *vertex_co = SCULPT_vertex_co_get(ss, i); + + if (!SCULPT_check_vertex_pivot_symmetry(vertex_co, expand_init_co, symm)) { + continue; + } + + add_v3_v3(avg, vertex_co); + total++; + } + + MEM_freeN(enabled_vertices); + MEM_freeN(boundary_vertices); + + if (total > 0) { + mul_v3_v3fl(ss->pivot_pos, avg, 1.0f / total); + } + + WM_event_add_notifier(C, NC_GEOM | ND_SELECT, ob->data); +} + +static void sculpt_expand_finish(bContext *C) +{ + Object *ob = CTX_data_active_object(C); + SculptSession *ss = ob->sculpt; + SCULPT_undo_push_end(); + + /* Tag all nodes to redraw to avoid artifacts after the fast partial updates. */ + PBVHNode **nodes; + int totnode; + BKE_pbvh_search_gather(ss->pbvh, NULL, NULL, &nodes, &totnode); + for (int n = 0; n < totnode; n++) { + BKE_pbvh_node_mark_update_mask(nodes[n]); + } + MEM_freeN(nodes); + + switch (ss->expand_cache->target) { + case SCULPT_EXPAND_TARGET_MASK: + SCULPT_flush_update_done(C, ob, SCULPT_UPDATE_MASK); + break; + case SCULPT_EXPAND_TARGET_FACE_SETS: + SCULPT_flush_update_done(C, ob, SCULPT_UPDATE_MASK); + break; + case SCULPT_EXPAND_TARGET_COLORS: + SCULPT_flush_update_done(C, ob, SCULPT_UPDATE_COLOR); + break; + } + + sculpt_expand_cache_free(ss); + ED_workspace_status_text(C, NULL); +} + +/* Finds and stores in the ExpandCache the sculpt connected component index for each symmetry pass + * needed for expand. */ +static void sculpt_expand_find_active_connected_components_from_vert(Object *ob, + ExpandCache *expand_cache, + const int initial_vertex) +{ + SculptSession *ss = ob->sculpt; + for (int i = 0; i < EXPAND_SYMM_AREAS; i++) { + expand_cache->active_connected_components[i] = EXPAND_ACTIVE_COMPONENT_NONE; + } + + const char symm = SCULPT_mesh_symmetry_xyz_get(ob); + for (char symm_it = 0; symm_it <= symm; symm_it++) { + if (!SCULPT_is_symmetry_iteration_valid(symm_it, symm)) { + continue; + } + + const int symm_vertex = sculpt_expand_get_vertex_index_for_symmetry_pass( + ob, symm_it, initial_vertex); + + expand_cache->active_connected_components[(int)symm_it] = + ss->vertex_info.connected_component[symm_vertex]; + } +} + +/* Stores the active vertex, Face Set and mouse coordinates in the ExpandCache based on the current + * cursor position. */ +static void sculpt_expand_set_initial_components_for_mouse(bContext *C, + Object *ob, + ExpandCache *expand_cache, + const float mouse[2]) +{ + SculptSession *ss = ob->sculpt; + int initial_vertex = sculpt_expand_target_vertex_update_and_get(C, ob, mouse); + if (initial_vertex == SCULPT_EXPAND_VERTEX_NONE) { + /* Cursor not over the mesh, for creating valid initial falloffs, fallback to the last active + * vertex in the sculpt session. */ + initial_vertex = SCULPT_active_vertex_get(ss); + } + copy_v2_v2(ss->expand_cache->initial_mouse, mouse); + expand_cache->initial_active_vertex = initial_vertex; + expand_cache->initial_active_face_set = SCULPT_active_face_set_get(ss); + + if (expand_cache->next_face_set == SCULPT_FACE_SET_NONE) { + /* Only set the next face set once, otherwise this ID will constantly update to a new one each + * time this function is called for using a new initial vertex from a different cursor + * position. */ + if (expand_cache->modify_active_face_set) { + expand_cache->next_face_set = SCULPT_active_face_set_get(ss); + } + else { + expand_cache->next_face_set = ED_sculpt_face_sets_find_next_available_id(ob->data); + } + } + + /* The new mouse position can be over a different connected component, so this needs to be + * updated. */ + sculpt_expand_find_active_connected_components_from_vert(ob, expand_cache, initial_vertex); +} + +/* Displaces the initial mouse coordinates using the new mouse position to get a new active vertex. + * After that, initializes a new falloff of the same type with the new active vertex. */ +static void sculpt_expand_move_propagation_origin(bContext *C, + Object *ob, + const wmEvent *event, + ExpandCache *expand_cache) +{ + Sculpt *sd = CTX_data_tool_settings(C)->sculpt; + + const float mouse[2] = {event->mval[0], event->mval[1]}; + float move_disp[2]; + sub_v2_v2v2(move_disp, mouse, expand_cache->initial_mouse_move); + + float new_mouse[2]; + add_v2_v2v2(new_mouse, move_disp, expand_cache->original_mouse_move); + + sculpt_expand_set_initial_components_for_mouse(C, ob, expand_cache, new_mouse); + sculpt_expand_falloff_factors_from_vertex_and_symm_create( + expand_cache, + sd, + ob, + expand_cache->initial_active_vertex, + expand_cache->move_preview_falloff_type); +} + +/* Ensures that the SculptSession contains the required data needed for Expand. */ +static void sculpt_expand_ensure_sculptsession_data(Object *ob) +{ + SculptSession *ss = ob->sculpt; + SCULPT_vertex_random_access_ensure(ss); + SCULPT_connected_components_ensure(ob); + SCULPT_boundary_info_ensure(ob); + if (!ss->tex_pool) { + ss->tex_pool = BKE_image_pool_new(); + } +} + +/* Returns the active Face Sets ID from the enabled face or grid in the SculptSession. */ +static int sculpt_expand_active_face_set_id_get(SculptSession *ss, ExpandCache *expand_cache) +{ + switch (BKE_pbvh_type(ss->pbvh)) { + case PBVH_FACES: + return expand_cache->original_face_sets[ss->active_face_index]; + case PBVH_GRIDS: { + const int face_index = BKE_subdiv_ccg_grid_to_face_index(ss->subdiv_ccg, + ss->active_grid_index); + return expand_cache->original_face_sets[face_index]; + } + case PBVH_BMESH: { + /* Dyntopo does not support Face Set functionality. */ + BLI_assert(false); + } + } + return SCULPT_FACE_SET_NONE; +} + +static int sculpt_expand_modal(bContext *C, wmOperator *op, const wmEvent *event) +{ + Object *ob = CTX_data_active_object(C); + SculptSession *ss = ob->sculpt; + Sculpt *sd = CTX_data_tool_settings(C)->sculpt; + + /* Skips INBETWEEN_MOUSEMOVE events and other events that may cause unnecessary updates. */ + if (!ELEM(event->type, MOUSEMOVE, EVT_MODAL_MAP)) { + return OPERATOR_RUNNING_MODAL; + } + + /* Update SculptSession data. */ + Depsgraph *depsgraph = CTX_data_depsgraph_pointer(C); + BKE_sculpt_update_object_for_edit(depsgraph, ob, true, true, false); + sculpt_expand_ensure_sculptsession_data(ob); + + /* Update and get the active vertex (and face) from the cursor. */ + const float mouse[2] = {event->mval[0], event->mval[1]}; + const int target_expand_vertex = sculpt_expand_target_vertex_update_and_get(C, ob, mouse); + + /* Handle the modal keymap state changes. */ + ExpandCache *expand_cache = ss->expand_cache; + if (event->type == EVT_MODAL_MAP) { + switch (event->val) { + case SCULPT_EXPAND_MODAL_CANCEL: { + sculpt_expand_cancel(C, op); + return OPERATOR_FINISHED; + } + case SCULPT_EXPAND_MODAL_INVERT: { + expand_cache->invert = !expand_cache->invert; + break; + } + case SCULPT_EXPAND_MODAL_PRESERVE_TOGGLE: { + expand_cache->preserve = !expand_cache->preserve; + break; + } + case SCULPT_EXPAND_MODAL_GRADIENT_TOGGLE: { + expand_cache->falloff_gradient = !expand_cache->falloff_gradient; + break; + } + case SCULPT_EXPAND_MODAL_BRUSH_GRADIENT_TOGGLE: { + expand_cache->brush_gradient = !expand_cache->brush_gradient; + if (expand_cache->brush_gradient) { + expand_cache->falloff_gradient = true; + } + break; + } + case SCULPT_EXPAND_MODAL_SNAP_TOGGLE: { + if (expand_cache->snap) { + expand_cache->snap = false; + if (expand_cache->snap_enabled_face_sets) { + BLI_gset_free(expand_cache->snap_enabled_face_sets, NULL); + expand_cache->snap_enabled_face_sets = NULL; + } + } + else { + expand_cache->snap = true; + if (!expand_cache->snap_enabled_face_sets) { + expand_cache->snap_enabled_face_sets = BLI_gset_int_new("snap face sets"); + } + sculpt_expand_snap_initialize_from_enabled(ss, expand_cache); + } + } break; + case SCULPT_EXPAND_MODAL_MOVE_TOGGLE: { + if (expand_cache->move) { + expand_cache->move = false; + sculpt_expand_falloff_factors_from_vertex_and_symm_create( + expand_cache, + sd, + ob, + expand_cache->initial_active_vertex, + expand_cache->move_original_falloff_type); + break; + } + else { + expand_cache->move = true; + expand_cache->move_original_falloff_type = expand_cache->falloff_type; + copy_v2_v2(expand_cache->initial_mouse_move, mouse); + copy_v2_v2(expand_cache->original_mouse_move, expand_cache->initial_mouse); + if (expand_cache->falloff_type == SCULPT_EXPAND_FALLOFF_GEODESIC && + SCULPT_vertex_count_get(ss) > expand_cache->max_geodesic_move_preview) { + /* Set to spherical falloff for preview in high poly meshes as it is the fastest one. + * In most cases it should match closely the preview from geodesic. */ + expand_cache->move_preview_falloff_type = SCULPT_EXPAND_FALLOFF_SPHERICAL; + } + else { + expand_cache->move_preview_falloff_type = expand_cache->falloff_type; + } + } + break; + } + case SCULPT_EXPAND_MODAL_RECURSION_STEP_GEODESIC: { + sculpt_expand_resursion_step_add(ob, expand_cache, SCULPT_EXPAND_RECURSION_GEODESICS); + break; + } + case SCULPT_EXPAND_MODAL_RECURSION_STEP_TOPOLOGY: { + sculpt_expand_resursion_step_add(ob, expand_cache, SCULPT_EXPAND_RECURSION_TOPOLOGY); + break; + } + case SCULPT_EXPAND_MODAL_CONFIRM: { + sculpt_expand_update_for_vertex(C, ob, target_expand_vertex); + + if (expand_cache->reposition_pivot) { + sculpt_expand_reposition_pivot(C, ob, expand_cache); + } + + sculpt_expand_finish(C); + return OPERATOR_FINISHED; + } + case SCULPT_EXPAND_MODAL_FALLOFF_GEODESIC: { + sculpt_expand_falloff_factors_from_vertex_and_symm_create( + expand_cache, + sd, + ob, + expand_cache->initial_active_vertex, + SCULPT_EXPAND_FALLOFF_GEODESIC); + break; + } + case SCULPT_EXPAND_MODAL_FALLOFF_TOPOLOGY: { + sculpt_expand_falloff_factors_from_vertex_and_symm_create( + expand_cache, + sd, + ob, + expand_cache->initial_active_vertex, + SCULPT_EXPAND_FALLOFF_TOPOLOGY); + break; + } + case SCULPT_EXPAND_MODAL_FALLOFF_TOPOLOGY_DIAGONALS: { + sculpt_expand_falloff_factors_from_vertex_and_symm_create( + expand_cache, + sd, + ob, + expand_cache->initial_active_vertex, + SCULPT_EXPAND_FALLOFF_TOPOLOGY_DIAGONALS); + break; + } + case SCULPT_EXPAND_MODAL_FALLOFF_SPHERICAL: { + sculpt_expand_falloff_factors_from_vertex_and_symm_create( + expand_cache, + sd, + ob, + expand_cache->initial_active_vertex, + SCULPT_EXPAND_FALLOFF_SPHERICAL); + break; + } + case SCULPT_EXPAND_MODAL_LOOP_COUNT_INCREASE: { + expand_cache->loop_count += 1; + break; + } + case SCULPT_EXPAND_MODAL_LOOP_COUNT_DECREASE: { + expand_cache->loop_count -= 1; + expand_cache->loop_count = max_ii(expand_cache->loop_count, 1); + break; + } + case SCULPT_EXPAND_MODAL_TEXTURE_DISTORTION_INCREASE: { + if (expand_cache->texture_distortion_strength == 0.0f) { + if (expand_cache->brush->mtex.tex == NULL) { + BKE_report(op->reports, + RPT_WARNING, + "Active brush does not contain any texture to distort the expand boundary"); + break; + } + if (expand_cache->brush->mtex.brush_map_mode != MTEX_MAP_MODE_3D) { + BKE_report(op->reports, + RPT_WARNING, + "Texture mapping not set to 3D, results may be unpredictable"); + } + } + expand_cache->texture_distortion_strength += SCULPT_EXPAND_TEXTURE_DISTORTION_STEP; + break; + } + case SCULPT_EXPAND_MODAL_TEXTURE_DISTORTION_DECREASE: { + expand_cache->texture_distortion_strength -= SCULPT_EXPAND_TEXTURE_DISTORTION_STEP; + expand_cache->texture_distortion_strength = max_ff( + expand_cache->texture_distortion_strength, 0.0f); + break; + } + } + } + + /* Handle expand origin movement if enabled. */ + if (expand_cache->move) { + sculpt_expand_move_propagation_origin(C, ob, event, expand_cache); + } + + /* Add new Face Sets IDs to the snapping gset if enabled. */ + if (expand_cache->snap) { + const int active_face_set_id = sculpt_expand_active_face_set_id_get(ss, expand_cache); + if (!BLI_gset_haskey(expand_cache->snap_enabled_face_sets, + POINTER_FROM_INT(active_face_set_id))) { + BLI_gset_add(expand_cache->snap_enabled_face_sets, POINTER_FROM_INT(active_face_set_id)); + } + } + + /* Update the sculpt data with the current state of the ExpandCache. */ + sculpt_expand_update_for_vertex(C, ob, target_expand_vertex); + + return OPERATOR_RUNNING_MODAL; +} + +/* Deletes the delete_id Face Set ID from the mesh Face Sets and stores the result in r_face_set. + * The faces that were using the delete_id Face Set are filled using the content from their + * neighbors. */ +static void sculpt_expand_delete_face_set_id( + int *r_face_sets, Mesh *mesh, MeshElemMap *pmap, const int totface, const int delete_id) +{ + /* Check that all the face sets IDs in the mesh are not equal to delete_id befor attempting to + * delete it. */ + bool all_same_id = true; + for (int i = 0; i < totface; i++) { + if (r_face_sets[i] != delete_id) { + all_same_id = false; + break; + } + } + if (all_same_id) { + return; + } + + BLI_LINKSTACK_DECLARE(queue, void *); + BLI_LINKSTACK_DECLARE(queue_next, void *); + + BLI_LINKSTACK_INIT(queue); + BLI_LINKSTACK_INIT(queue_next); + + for (int i = 0; i < totface; i++) { + if (r_face_sets[i] == delete_id) { + BLI_LINKSTACK_PUSH(queue, POINTER_FROM_INT(i)); + } + } + + while (BLI_LINKSTACK_SIZE(queue)) { + while (BLI_LINKSTACK_SIZE(queue)) { + const int f_index = POINTER_AS_INT(BLI_LINKSTACK_POP(queue)); + int other_id = delete_id; + const MPoly *c_poly = &mesh->mpoly[f_index]; + for (int l = 0; l < c_poly->totloop; l++) { + const MLoop *c_loop = &mesh->mloop[c_poly->loopstart + l]; + const MeshElemMap *vert_map = &pmap[c_loop->v]; + for (int i = 0; i < vert_map->count; i++) { + + const int neighbor_face_index = vert_map->indices[i]; + if (r_face_sets[neighbor_face_index] != delete_id) { + other_id = r_face_sets[neighbor_face_index]; + } + } + } + + if (other_id != delete_id) { + r_face_sets[f_index] = other_id; + } + else { + BLI_LINKSTACK_PUSH(queue_next, POINTER_FROM_INT(f_index)); + } + } + + BLI_LINKSTACK_SWAP(queue, queue_next); + } + + BLI_LINKSTACK_FREE(queue); + BLI_LINKSTACK_FREE(queue_next); +} + +static void sculpt_expand_cache_initial_config_set(bContext *C, + wmOperator *op, + ExpandCache *expand_cache) +{ + /* RNA properties. */ + expand_cache->invert = RNA_boolean_get(op->ptr, "invert"); + expand_cache->preserve = RNA_boolean_get(op->ptr, "use_mask_preserve"); + expand_cache->falloff_gradient = RNA_boolean_get(op->ptr, "use_falloff_gradient"); + expand_cache->target = RNA_enum_get(op->ptr, "target"); + expand_cache->modify_active_face_set = RNA_boolean_get(op->ptr, "use_modify_active"); + expand_cache->reposition_pivot = RNA_boolean_get(op->ptr, "use_reposition_pivot"); + expand_cache->max_geodesic_move_preview = RNA_int_get(op->ptr, "max_geodesic_move_preview"); + + /* These can be exposed in RNA if needed. */ + expand_cache->loop_count = 1; + expand_cache->brush_gradient = false; + + /* Texture and color data from the active Brush. */ + Object *ob = CTX_data_active_object(C); + Sculpt *sd = CTX_data_tool_settings(C)->sculpt; + SculptSession *ss = ob->sculpt; + expand_cache->brush = BKE_paint_brush(&sd->paint); + BKE_curvemapping_init(expand_cache->brush->curve); + copy_v4_fl(expand_cache->fill_color, 1.0f); + copy_v3_v3(expand_cache->fill_color, BKE_brush_color_get(ss->scene, expand_cache->brush)); + IMB_colormanagement_srgb_to_scene_linear_v3(expand_cache->fill_color); + + expand_cache->scene = CTX_data_scene(C); + expand_cache->mtex = &expand_cache->brush->mtex; + expand_cache->texture_distortion_strength = 0.0f; + expand_cache->blend_mode = expand_cache->brush->blend; +} + +/* Does the undo sculpt push for the affected target data of the ExpandCache. */ +static void sculpt_expand_undo_push(Object *ob, ExpandCache *expand_cache) +{ + SculptSession *ss = ob->sculpt; + PBVHNode **nodes; + int totnode; + BKE_pbvh_search_gather(ss->pbvh, NULL, NULL, &nodes, &totnode); + + switch (expand_cache->target) { + case SCULPT_EXPAND_TARGET_MASK: + for (int i = 0; i < totnode; i++) { + SCULPT_undo_push_node(ob, nodes[i], SCULPT_UNDO_MASK); + } + break; + case SCULPT_EXPAND_TARGET_FACE_SETS: + SCULPT_undo_push_node(ob, nodes[0], SCULPT_UNDO_FACE_SETS); + break; + case SCULPT_EXPAND_TARGET_COLORS: + for (int i = 0; i < totnode; i++) { + SCULPT_undo_push_node(ob, nodes[i], SCULPT_UNDO_COLOR); + } + break; + } + + MEM_freeN(nodes); +} + +static int sculpt_expand_invoke(bContext *C, wmOperator *op, const wmEvent *event) +{ + Depsgraph *depsgraph = CTX_data_ensure_evaluated_depsgraph(C); + Object *ob = CTX_data_active_object(C); + SculptSession *ss = ob->sculpt; + Sculpt *sd = CTX_data_tool_settings(C)->sculpt; + + /* Create and configure the Expand Cache. */ + ss->expand_cache = MEM_callocN(sizeof(ExpandCache), "expand cache"); + sculpt_expand_cache_initial_config_set(C, op, ss->expand_cache); + + /* Update object. */ + const bool needs_colors = ss->expand_cache->target == SCULPT_EXPAND_TARGET_COLORS; + + if (needs_colors) { + /* CTX_data_ensure_evaluated_depsgraph should be used at the end to include the updates of + * earlier steps modifying the data. */ + BKE_sculpt_color_layer_create_if_needed(ob); + depsgraph = CTX_data_ensure_evaluated_depsgraph(C); + } + + BKE_sculpt_update_object_for_edit(depsgraph, ob, true, true, needs_colors); + + /* Do nothing when the mesh has 0 vertices. */ + const int totvert = SCULPT_vertex_count_get(ss); + if (totvert == 0) { + sculpt_expand_cache_free(ss); + return OPERATOR_CANCELLED; + } + + /* Face Set operations are not supported in dyntopo. */ + if (ss->expand_cache->target == SCULPT_EXPAND_TARGET_FACE_SETS && + BKE_pbvh_type(ss->pbvh) == PBVH_BMESH) { + sculpt_expand_cache_free(ss); + return OPERATOR_CANCELLED; + } + + sculpt_expand_ensure_sculptsession_data(ob); + + /* Initialize undo. */ + SCULPT_undo_push_begin(ob, "expand"); + sculpt_expand_undo_push(ob, ss->expand_cache); + + /* Set the initial element for expand from the event position. */ + const float mouse[2] = {event->mval[0], event->mval[1]}; + sculpt_expand_set_initial_components_for_mouse(C, ob, ss->expand_cache, mouse); + + /* Cache PBVH nodes. */ + BKE_pbvh_search_gather( + ss->pbvh, NULL, NULL, &ss->expand_cache->nodes, &ss->expand_cache->totnode); + + /* Store initial state. */ + sculpt_expand_original_state_store(ob, ss->expand_cache); + + if (ss->expand_cache->modify_active_face_set) { + sculpt_expand_delete_face_set_id(ss->expand_cache->initial_face_sets, + ob->data, + ss->pmap, + ss->totfaces, + ss->expand_cache->next_face_set); + } + + /* Initialize the falloff. */ + eSculptExpandFalloffType falloff_type = RNA_enum_get(op->ptr, "falloff_type"); + + /* When starting from a boundary vertex, set the initial falloff to boundary. */ + if (SCULPT_vertex_is_boundary(ss, ss->expand_cache->initial_active_vertex)) { + falloff_type = SCULPT_EXPAND_FALLOFF_BOUNDARY_TOPOLOGY; + } + + sculpt_expand_falloff_factors_from_vertex_and_symm_create( + ss->expand_cache, sd, ob, ss->expand_cache->initial_active_vertex, falloff_type); + + /* Initial mesh data update, resets all target data in the sculpt mesh. */ + sculpt_expand_update_for_vertex(C, ob, ss->expand_cache->initial_active_vertex); + + WM_event_add_modal_handler(C, op); + return OPERATOR_RUNNING_MODAL; +} + +void sculpt_expand_modal_keymap(wmKeyConfig *keyconf) +{ + static const EnumPropertyItem modal_items[] = { + {SCULPT_EXPAND_MODAL_CONFIRM, "CONFIRM", 0, "Confirm", ""}, + {SCULPT_EXPAND_MODAL_CANCEL, "CANCEL", 0, "Cancel", ""}, + {SCULPT_EXPAND_MODAL_INVERT, "INVERT", 0, "Invert", ""}, + {SCULPT_EXPAND_MODAL_PRESERVE_TOGGLE, "PRESERVE", 0, "Toggle Preserve State", ""}, + {SCULPT_EXPAND_MODAL_GRADIENT_TOGGLE, "GRADIENT", 0, "Toggle Gradient", ""}, + {SCULPT_EXPAND_MODAL_RECURSION_STEP_GEODESIC, + "RECURSION_STEP_GEODESIC", + 0, + "Geodesic recursion step", + ""}, + {SCULPT_EXPAND_MODAL_RECURSION_STEP_TOPOLOGY, + "RECURSION_STEP_TOPOLOGY", + 0, + "Topology recursion Step", + ""}, + {SCULPT_EXPAND_MODAL_MOVE_TOGGLE, "MOVE_TOGGLE", 0, "Move Origin", ""}, + {SCULPT_EXPAND_MODAL_FALLOFF_GEODESIC, "FALLOFF_GEODESICS", 0, "Geodesic Falloff", ""}, + {SCULPT_EXPAND_MODAL_FALLOFF_TOPOLOGY, "FALLOFF_TOPOLOGY", 0, "Topology Falloff", ""}, + {SCULPT_EXPAND_MODAL_FALLOFF_TOPOLOGY_DIAGONALS, + "FALLOFF_TOPOLOGY_DIAGONALS", + 0, + "Diagonals Falloff", + ""}, + {SCULPT_EXPAND_MODAL_FALLOFF_SPHERICAL, "FALLOFF_SPHERICAL", 0, "Spherical Falloff", ""}, + {SCULPT_EXPAND_MODAL_SNAP_TOGGLE, "SNAP_TOGGLE", 0, "Snap expand to Face Sets", ""}, + {SCULPT_EXPAND_MODAL_LOOP_COUNT_INCREASE, + "LOOP_COUNT_INCREASE", + 0, + "Loop Count Increase", + ""}, + {SCULPT_EXPAND_MODAL_LOOP_COUNT_DECREASE, + "LOOP_COUNT_DECREASE", + 0, + "Loop Count Decrease", + ""}, + {SCULPT_EXPAND_MODAL_BRUSH_GRADIENT_TOGGLE, + "BRUSH_GRADIENT_TOGGLE", + 0, + "Toggle Brush Gradient", + ""}, + {SCULPT_EXPAND_MODAL_TEXTURE_DISTORTION_INCREASE, + "TEXTURE_DISTORTION_INCREASE", + 0, + "Texture Distortion Increase", + ""}, + {SCULPT_EXPAND_MODAL_TEXTURE_DISTORTION_DECREASE, + "TEXTURE_DISTORTION_DECREASE", + 0, + "Texture Distortion Decrease", + ""}, + {0, NULL, 0, NULL, NULL}, + }; + + static const char *name = "Sculpt Expand Modal"; + wmKeyMap *keymap = WM_modalkeymap_find(keyconf, name); + + /* This function is called for each spacetype, only needs to add map once. */ + if (keymap && keymap->modal_items) { + return; + } + + keymap = WM_modalkeymap_ensure(keyconf, name, modal_items); + WM_modalkeymap_assign(keymap, "SCULPT_OT_expand"); +} + +void SCULPT_OT_expand(wmOperatorType *ot) +{ + /* Identifiers. */ + ot->name = "Expand"; + ot->idname = "SCULPT_OT_expand"; + ot->description = "Generic sculpt expand operator"; + + /* API callbacks. */ + ot->invoke = sculpt_expand_invoke; + ot->modal = sculpt_expand_modal; + ot->cancel = sculpt_expand_cancel; + ot->poll = SCULPT_mode_poll; + + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + + static EnumPropertyItem prop_sculpt_expand_falloff_type_items[] = { + {SCULPT_EXPAND_FALLOFF_GEODESIC, "GEODESIC", 0, "Geodesic", ""}, + {SCULPT_EXPAND_FALLOFF_TOPOLOGY, "TOPOLOGY", 0, "Topology", ""}, + {SCULPT_EXPAND_FALLOFF_TOPOLOGY_DIAGONALS, + "TOPOLOGY_DIAGONALS", + 0, + "Topology Diagonals", + ""}, + {SCULPT_EXPAND_FALLOFF_NORMALS, "NORMALS", 0, "Normals", ""}, + {SCULPT_EXPAND_FALLOFF_SPHERICAL, "SPHERICAL", 0, "Spherical", ""}, + {SCULPT_EXPAND_FALLOFF_BOUNDARY_TOPOLOGY, "BOUNDARY_TOPOLOGY", 0, "Boundary Topology", ""}, + {SCULPT_EXPAND_FALLOFF_BOUNDARY_FACE_SET, "BOUNDARY_FACE_SET", 0, "Boundary Face Set", ""}, + {SCULPT_EXPAND_FALLOFF_ACTIVE_FACE_SET, "ACTIVE_FACE_SET", 0, "Active Face Set", ""}, + {0, NULL, 0, NULL, NULL}, + }; + + static EnumPropertyItem prop_sculpt_expand_target_type_items[] = { + {SCULPT_EXPAND_TARGET_MASK, "MASK", 0, "Mask", ""}, + {SCULPT_EXPAND_TARGET_FACE_SETS, "FACE_SETS", 0, "Face Sets", ""}, + {SCULPT_EXPAND_TARGET_COLORS, "COLOR", 0, "Color", ""}, + {0, NULL, 0, NULL, NULL}, + }; + + RNA_def_enum(ot->srna, + "target", + prop_sculpt_expand_target_type_items, + SCULPT_EXPAND_TARGET_MASK, + "Data Target", + "Data that is going to be modified in the expand operation"); + + RNA_def_enum(ot->srna, + "falloff_type", + prop_sculpt_expand_falloff_type_items, + SCULPT_EXPAND_FALLOFF_GEODESIC, + "Falloff Type", + "Initial falloff of the expand operation"); + + ot->prop = RNA_def_boolean( + ot->srna, "invert", false, "Invert", "Invert the expand active elements"); + ot->prop = RNA_def_boolean(ot->srna, + "use_mask_preserve", + false, + "Preserve Previous", + "Preserve the previous state of the target data"); + ot->prop = RNA_def_boolean(ot->srna, + "use_falloff_gradient", + false, + "Falloff Gradient", + "Expand Using a linear falloff"); + + ot->prop = RNA_def_boolean(ot->srna, + "use_modify_active", + false, + "Modify Active", + "Modify the active Face Set instead of creating a new one"); + + ot->prop = RNA_def_boolean( + ot->srna, + "use_reposition_pivot", + true, + "Reposition Pivot", + "Reposition the sculpt transform pivot to the boundary of the expand active area"); + + ot->prop = RNA_def_int(ot->srna, + "max_geodesic_move_preview", + 10000, + 0, + INT_MAX, + "Max Vertex Count for Geodesic Move Preview", + "Maximum number of vertices in the mesh for using geodesic falloff when " + "moving the origin of expand. If the total number of vertices is greater " + "than this value, the falloff will be set to spherical when moving", + 0, + 1000000); +} diff --git a/source/blender/editors/sculpt_paint/sculpt_geodesic.c b/source/blender/editors/sculpt_paint/sculpt_geodesic.c new file mode 100644 index 00000000000..d86d0938300 --- /dev/null +++ b/source/blender/editors/sculpt_paint/sculpt_geodesic.c @@ -0,0 +1,360 @@ +/* + * 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 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * 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) 2020 Blender Foundation. + * All rights reserved. + */ + +/** \file + * \ingroup edsculpt + */ + +#include "MEM_guardedalloc.h" + +#include "BLI_blenlib.h" +#include "BLI_linklist_stack.h" +#include "BLI_math.h" +#include "BLI_task.h" + +#include "BLT_translation.h" + +#include "DNA_brush_types.h" +#include "DNA_mesh_types.h" +#include "DNA_meshdata_types.h" +#include "DNA_object_types.h" + +#include "BKE_brush.h" +#include "BKE_ccg.h" +#include "BKE_colortools.h" +#include "BKE_context.h" +#include "BKE_image.h" +#include "BKE_mesh.h" +#include "BKE_mesh_mapping.h" +#include "BKE_multires.h" +#include "BKE_node.h" +#include "BKE_object.h" +#include "BKE_paint.h" +#include "BKE_pbvh.h" +#include "BKE_scene.h" +#include "BKE_subdiv_ccg.h" + +#include "DEG_depsgraph.h" + +#include "WM_api.h" +#include "WM_message.h" +#include "WM_toolsystem.h" +#include "WM_types.h" + +#include "RNA_access.h" +#include "RNA_define.h" + +#include "ED_object.h" +#include "ED_screen.h" +#include "ED_sculpt.h" +#include "ED_view3d.h" +#include "paint_intern.h" +#include "sculpt_intern.h" + +#include "IMB_colormanagement.h" +#include "IMB_imbuf.h" + +#include "bmesh.h" + +#include <math.h> +#include <stdlib.h> +#define SCULPT_GEODESIC_VERTEX_NONE -1 + +/* Propagate distance from v1 and v2 to v0. */ +static bool sculpt_geodesic_mesh_test_dist_add( + MVert *mvert, const int v0, const int v1, const int v2, float *dists, GSet *initial_vertices) +{ + if (BLI_gset_haskey(initial_vertices, POINTER_FROM_INT(v0))) { + return false; + } + + BLI_assert(dists[v1] != FLT_MAX); + if (dists[v0] <= dists[v1]) { + return false; + } + + float dist0; + if (v2 != SCULPT_GEODESIC_VERTEX_NONE) { + BLI_assert(dists[v2] != FLT_MAX); + if (dists[v0] <= dists[v2]) { + return false; + } + dist0 = geodesic_distance_propagate_across_triangle( + mvert[v0].co, mvert[v1].co, mvert[v2].co, dists[v1], dists[v2]); + } + else { + float vec[3]; + sub_v3_v3v3(vec, mvert[v1].co, mvert[v0].co); + dist0 = dists[v1] + len_v3(vec); + } + + if (dist0 < dists[v0]) { + dists[v0] = dist0; + return true; + } + + return false; +} + +static float *SCULPT_geodesic_mesh_create(Object *ob, + GSet *initial_vertices, + const float limit_radius) +{ + SculptSession *ss = ob->sculpt; + Mesh *mesh = BKE_object_get_original_mesh(ob); + + const int totvert = mesh->totvert; + const int totedge = mesh->totedge; + + const float limit_radius_sq = limit_radius * limit_radius; + + MEdge *edges = mesh->medge; + MVert *verts = SCULPT_mesh_deformed_mverts_get(ss); + + float *dists = MEM_malloc_arrayN(totvert, sizeof(float), "distances"); + BLI_bitmap *edge_tag = BLI_BITMAP_NEW(totedge, "edge tag"); + + if (!ss->epmap) { + BKE_mesh_edge_poly_map_create(&ss->epmap, + &ss->epmap_mem, + mesh->medge, + mesh->totedge, + mesh->mpoly, + mesh->totpoly, + mesh->mloop, + mesh->totloop); + } + if (!ss->vemap) { + BKE_mesh_vert_edge_map_create( + &ss->vemap, &ss->vemap_mem, mesh->medge, mesh->totvert, mesh->totedge); + } + + /* Both contain edge indices encoded as *void. */ + BLI_LINKSTACK_DECLARE(queue, void *); + BLI_LINKSTACK_DECLARE(queue_next, void *); + + BLI_LINKSTACK_INIT(queue); + BLI_LINKSTACK_INIT(queue_next); + + for (int i = 0; i < totvert; i++) { + if (BLI_gset_haskey(initial_vertices, POINTER_FROM_INT(i))) { + dists[i] = 0.0f; + } + else { + dists[i] = FLT_MAX; + } + } + + /* Masks vertices that are further than limit radius from an initial vertex. As there is no need + * to define a distance to them the algorithm can stop earlier by skipping them. */ + BLI_bitmap *affected_vertex = BLI_BITMAP_NEW(totvert, "affected vertex"); + GSetIterator gs_iter; + + if (limit_radius == FLT_MAX) { + /* In this case, no need to loop through all initial vertices to check distances as they are + * all going to be affected. */ + BLI_bitmap_set_all(affected_vertex, true, totvert); + } + else { + /* This is an O(n^2) loop used to limit the geodesic distance calculation to a radius. When + * this optimization is needed, it is expected for the tool to request the distance to a low + * number of vertices (usually just 1 or 2). */ + GSET_ITER (gs_iter, initial_vertices) { + const int v = POINTER_AS_INT(BLI_gsetIterator_getKey(&gs_iter)); + float *v_co = verts[v].co; + for (int i = 0; i < totvert; i++) { + if (len_squared_v3v3(v_co, verts[i].co) <= limit_radius_sq) { + BLI_BITMAP_ENABLE(affected_vertex, i); + } + } + } + } + + /* Add edges adjacent to an initial vertex to the queue. */ + for (int i = 0; i < totedge; i++) { + const int v1 = edges[i].v1; + const int v2 = edges[i].v2; + if (!BLI_BITMAP_TEST(affected_vertex, v1) && !BLI_BITMAP_TEST(affected_vertex, v2)) { + continue; + } + if (dists[v1] != FLT_MAX || dists[v2] != FLT_MAX) { + BLI_LINKSTACK_PUSH(queue, POINTER_FROM_INT(i)); + } + } + + do { + while (BLI_LINKSTACK_SIZE(queue)) { + const int e = POINTER_AS_INT(BLI_LINKSTACK_POP(queue)); + int v1 = edges[e].v1; + int v2 = edges[e].v2; + + if (dists[v1] == FLT_MAX || dists[v2] == FLT_MAX) { + if (dists[v1] > dists[v2]) { + SWAP(int, v1, v2); + } + sculpt_geodesic_mesh_test_dist_add( + verts, v2, v1, SCULPT_GEODESIC_VERTEX_NONE, dists, initial_vertices); + } + + if (ss->epmap[e].count != 0) { + for (int poly_map_index = 0; poly_map_index < ss->epmap[e].count; poly_map_index++) { + const int poly = ss->epmap[e].indices[poly_map_index]; + if (ss->face_sets[poly] <= 0) { + continue; + } + const MPoly *mpoly = &mesh->mpoly[poly]; + + for (int loop_index = 0; loop_index < mpoly->totloop; loop_index++) { + const MLoop *mloop = &mesh->mloop[loop_index + mpoly->loopstart]; + const int v_other = mloop->v; + if (ELEM(v_other, v1, v2)) { + continue; + } + if (sculpt_geodesic_mesh_test_dist_add( + verts, v_other, v1, v2, dists, initial_vertices)) { + for (int edge_map_index = 0; edge_map_index < ss->vemap[v_other].count; + edge_map_index++) { + const int e_other = ss->vemap[v_other].indices[edge_map_index]; + int ev_other; + if (edges[e_other].v1 == (uint)v_other) { + ev_other = edges[e_other].v2; + } + else { + ev_other = edges[e_other].v1; + } + + if (e_other != e && !BLI_BITMAP_TEST(edge_tag, e_other) && + (ss->epmap[e_other].count == 0 || dists[ev_other] != FLT_MAX)) { + if (BLI_BITMAP_TEST(affected_vertex, v_other) || + BLI_BITMAP_TEST(affected_vertex, ev_other)) { + BLI_BITMAP_ENABLE(edge_tag, e_other); + BLI_LINKSTACK_PUSH(queue_next, POINTER_FROM_INT(e_other)); + } + } + } + } + } + } + } + } + + for (LinkNode *lnk = queue_next; lnk; lnk = lnk->next) { + const int e = POINTER_AS_INT(lnk->link); + BLI_BITMAP_DISABLE(edge_tag, e); + } + + BLI_LINKSTACK_SWAP(queue, queue_next); + + } while (BLI_LINKSTACK_SIZE(queue)); + + BLI_LINKSTACK_FREE(queue); + BLI_LINKSTACK_FREE(queue_next); + MEM_SAFE_FREE(edge_tag); + MEM_SAFE_FREE(affected_vertex); + + return dists; +} + +/* For sculpt mesh data that does not support a geodesic distances algorithm, fallback to the + * distance to each vertex. In this case, only one of the initial vertices will be used to + * calculate the distance. */ +static float *SCULPT_geodesic_fallback_create(Object *ob, GSet *initial_vertices) +{ + + SculptSession *ss = ob->sculpt; + Mesh *mesh = BKE_object_get_original_mesh(ob); + const int totvert = mesh->totvert; + float *dists = MEM_malloc_arrayN(totvert, sizeof(float), "distances"); + int first_affected = SCULPT_GEODESIC_VERTEX_NONE; + GSetIterator gs_iter; + GSET_ITER (gs_iter, initial_vertices) { + first_affected = POINTER_AS_INT(BLI_gsetIterator_getKey(&gs_iter)); + break; + } + + if (first_affected == SCULPT_GEODESIC_VERTEX_NONE) { + for (int i = 0; i < totvert; i++) { + dists[i] = FLT_MAX; + } + return dists; + } + + const float *first_affected_co = SCULPT_vertex_co_get(ss, first_affected); + for (int i = 0; i < totvert; i++) { + dists[i] = len_v3v3(first_affected_co, SCULPT_vertex_co_get(ss, i)); + } + + return dists; +} + +float *SCULPT_geodesic_distances_create(Object *ob, + GSet *initial_vertices, + const float limit_radius) +{ + SculptSession *ss = ob->sculpt; + switch (BKE_pbvh_type(ss->pbvh)) { + case PBVH_FACES: + return SCULPT_geodesic_mesh_create(ob, initial_vertices, limit_radius); + case PBVH_BMESH: + case PBVH_GRIDS: + return SCULPT_geodesic_fallback_create(ob, initial_vertices); + } + BLI_assert(false); + return NULL; +} + +float *SCULPT_geodesic_from_vertex_and_symm(Sculpt *sd, + Object *ob, + const int vertex, + const float limit_radius) +{ + SculptSession *ss = ob->sculpt; + GSet *initial_vertices = BLI_gset_int_new("initial_vertices"); + + const char symm = SCULPT_mesh_symmetry_xyz_get(ob); + for (char i = 0; i <= symm; ++i) { + if (SCULPT_is_symmetry_iteration_valid(i, symm)) { + int v = -1; + if (i == 0) { + v = vertex; + } + else { + float location[3]; + flip_v3_v3(location, SCULPT_vertex_co_get(ss, vertex), i); + v = SCULPT_nearest_vertex_get(sd, ob, location, FLT_MAX, false); + } + if (v != -1) { + BLI_gset_add(initial_vertices, POINTER_FROM_INT(v)); + } + } + } + + float *dists = SCULPT_geodesic_distances_create(ob, initial_vertices, limit_radius); + BLI_gset_free(initial_vertices, NULL); + return dists; +} + +float *SCULPT_geodesic_from_vertex(Object *ob, const int vertex, const float limit_radius) +{ + GSet *initial_vertices = BLI_gset_int_new("initial_vertices"); + BLI_gset_add(initial_vertices, POINTER_FROM_INT(vertex)); + float *dists = SCULPT_geodesic_distances_create(ob, initial_vertices, limit_radius); + BLI_gset_free(initial_vertices, NULL); + return dists; +} diff --git a/source/blender/editors/sculpt_paint/sculpt_intern.h b/source/blender/editors/sculpt_paint/sculpt_intern.h index f90cf366ed9..19c4eda7593 100644 --- a/source/blender/editors/sculpt_paint/sculpt_intern.h +++ b/source/blender/editors/sculpt_paint/sculpt_intern.h @@ -187,6 +187,8 @@ void SCULPT_boundary_info_ensure(Object *object); /* Boundary Info needs to be initialized in order to use this function. */ bool SCULPT_vertex_is_boundary(const SculptSession *ss, const int index); +void SCULPT_connected_components_ensure(Object *ob); + /* Sculpt Visibility API */ void SCULPT_vertex_visible_set(SculptSession *ss, int index, bool visible); @@ -300,6 +302,7 @@ void SCULPT_floodfill_add_initial_with_symmetry(struct Sculpt *sd, int index, float radius); void SCULPT_floodfill_add_initial(SculptFloodFill *flood, int index); +void SCULPT_floodfill_add_and_skip_initial(SculptFloodFill *flood, int index); void SCULPT_floodfill_execute( struct SculptSession *ss, SculptFloodFill *flood, @@ -361,6 +364,21 @@ float *SCULPT_boundary_automasking_init(Object *ob, int propagation_steps, float *automask_factor); +/* Geodesic distances. */ + +/* Returns an array indexed by vertex index containing the geodesic distance to the closest vertex +in the initial vertex set. The caller is responsible for freeing the array. +Geodesic distances will only work when used with PBVH_FACES, for other types of PBVH it will +fallback to euclidean distances to one of the initial vertices in the set. */ +float *SCULPT_geodesic_distances_create(struct Object *ob, + struct GSet *initial_vertices, + const float limit_radius); +float *SCULPT_geodesic_from_vertex_and_symm(struct Sculpt *sd, + struct Object *ob, + const int vertex, + const float limit_radius); +float *SCULPT_geodesic_from_vertex(Object *ob, const int vertex, const float limit_radius); + /* Filters. */ void SCULPT_filter_cache_init(struct bContext *C, Object *ob, Sculpt *sd, const int undo_type); void SCULPT_filter_cache_free(SculptSession *ss); @@ -1066,6 +1084,155 @@ void SCULPT_filter_to_orientation_space(float r_v[3], struct FilterCache *filter void SCULPT_filter_to_object_space(float r_v[3], struct FilterCache *filter_cache); void SCULPT_filter_zero_disabled_axis_components(float r_v[3], struct FilterCache *filter_cache); +/* Sculpt Expand. */ +typedef enum eSculptExpandFalloffType { + SCULPT_EXPAND_FALLOFF_GEODESIC, + SCULPT_EXPAND_FALLOFF_TOPOLOGY, + SCULPT_EXPAND_FALLOFF_TOPOLOGY_DIAGONALS, + SCULPT_EXPAND_FALLOFF_NORMALS, + SCULPT_EXPAND_FALLOFF_SPHERICAL, + SCULPT_EXPAND_FALLOFF_BOUNDARY_TOPOLOGY, + SCULPT_EXPAND_FALLOFF_BOUNDARY_FACE_SET, + SCULPT_EXPAND_FALLOFF_ACTIVE_FACE_SET, +} eSculptExpandFalloffType; + +typedef enum eSculptExpandTargetType { + SCULPT_EXPAND_TARGET_MASK, + SCULPT_EXPAND_TARGET_FACE_SETS, + SCULPT_EXPAND_TARGET_COLORS, +} eSculptExpandTargetType; + +typedef enum eSculptExpandRecursionType { + SCULPT_EXPAND_RECURSION_TOPOLOGY, + SCULPT_EXPAND_RECURSION_GEODESICS, +} eSculptExpandRecursionType; + +#define EXPAND_SYMM_AREAS 8 + +typedef struct ExpandCache { + /* Target data elements that the expand operation will affect. */ + eSculptExpandTargetType target; + + /* Falloff data. */ + eSculptExpandFalloffType falloff_type; + + /* Indexed by vertex index, precalculated falloff value of that vertex (without any falloff + * editing modification applied). */ + float *vert_falloff; + /* Max falloff value in *vert_falloff. */ + float max_vert_falloff; + + /* Indexed by base mesh poly index, precalculated falloff value of that face. These values are + * calculated from the per vertex falloff (*vert_falloff) when needed. */ + float *face_falloff; + float max_face_falloff; + + /* Falloff value of the active element (vertex or base mesh face) that Expand will expand to. */ + float active_falloff; + + /* When set to true, expand skips all falloff computations and considers all elements as enabled. + */ + bool all_enabled; + + /* Initial mouse and cursor data from where the current falloff started. This data can be changed + * during the execution of Expand by moving the origin. */ + float initial_mouse_move[2]; + float initial_mouse[2]; + int initial_active_vertex; + int initial_active_face_set; + + /* Maximum number of vertices allowed in the SculptSession for previewing the falloff using + * geodesic distances. */ + int max_geodesic_move_preview; + + /* Original falloff type before starting the move operation. */ + eSculptExpandFalloffType move_original_falloff_type; + /* Falloff type using when moving the origin for preview. */ + eSculptExpandFalloffType move_preview_falloff_type; + + /* Face set ID that is going to be used when creating a new Face Set. */ + int next_face_set; + + /* Face Set ID of the Face set selected for editing. */ + int update_face_set; + + /* Mouse position since the last time the origin was moved. Used for reference when moving the + * initial position of Expand. */ + float original_mouse_move[2]; + + /* Active components checks. */ + /* Indexed by symmetry pass index, contains the connected component ID found in + * SculptSession->vertex_info.connected_component. Other connected components not found in this + * array will be ignored by Expand. */ + int active_connected_components[EXPAND_SYMM_AREAS]; + + /* Snapping. */ + /* GSet containing all Face Sets IDs that Expand will use to snap the new data. */ + GSet *snap_enabled_face_sets; + + /* Texture distortion data. */ + Brush *brush; + struct Scene *scene; + struct MTex *mtex; + + /* Controls how much texture distortion will be applied to the current falloff */ + float texture_distortion_strength; + + /* Cached PBVH nodes. This allows to skip gathering all nodes from the PBVH each time expand + * needs to update the state of the elements. */ + PBVHNode **nodes; + int totnode; + + /* Expand state options. */ + + /* Number of loops (times that the falloff is going to be repeated). */ + int loop_count; + + /* Invert the falloff result. */ + bool invert; + + /* When set to true, preserves the previous state of the data and adds the new one on top. */ + bool preserve; + + /* When set to true, the mask or colors will be applied as a gradient. */ + bool falloff_gradient; + + /* When set to true, Expand will use the Brush falloff curve data to shape the gradient. */ + bool brush_gradient; + + /* When set to true, Expand will move the origin (initial active vertex and cursor position) + * instead of updating the active vertex and active falloff. */ + bool move; + + /* When set to true, Expand will snap the new data to the Face Sets IDs found in + * *original_face_sets. */ + bool snap; + + /* When set to true, Expand will use the current Face Set ID to modify an existing Face Set + * instead of creating a new one. */ + bool modify_active_face_set; + + /* When set to true, Expand will reposition the sculpt pivot to the boundary of the expand result + * after finishing the operation. */ + bool reposition_pivot; + + /* Color target data type related data. */ + float fill_color[4]; + short blend_mode; + + /* Face Sets at the first step of the expand operation, before starting modifying the active + * vertex and active falloff. These are not the original Face Sets of the sculpt before starting + * the operator as they could have been modified by Expand when initializing the operator and + * before starting changing the active vertex. These Face Sets are used for restoring and + * checking the Face Sets state while the Expand operation modal runs. */ + int *initial_face_sets; + + /* Original data of the sculpt as it was before running the Expand operator. */ + float *original_mask; + int *original_face_sets; + float (*original_colors)[4]; +} ExpandCache; + typedef struct FilterCache { bool enabled_axis[3]; bool enabled_force_axis[3]; @@ -1150,6 +1317,10 @@ bool SCULPT_get_redraw_rect(struct ARegion *region, /* Operators. */ +/* Expand. */ +void SCULPT_OT_expand(struct wmOperatorType *ot); +void sculpt_expand_modal_keymap(struct wmKeyConfig *keyconf); + /* Gestures. */ void SCULPT_OT_face_set_lasso_gesture(struct wmOperatorType *ot); void SCULPT_OT_face_set_box_gesture(struct wmOperatorType *ot); diff --git a/source/blender/editors/space_api/spacetypes.c b/source/blender/editors/space_api/spacetypes.c index c112c678a09..1bd8d13b25b 100644 --- a/source/blender/editors/space_api/spacetypes.c +++ b/source/blender/editors/space_api/spacetypes.c @@ -274,9 +274,7 @@ void ED_region_draw_cb_draw(const bContext *C, ARegion *region, int type) void ED_region_draw_cb_remove_by_type(ARegionType *art, void *draw_fn, void (*free)(void *)) { - RegionDrawCB *rdc = art->drawcalls.first; - while (rdc) { - RegionDrawCB *rdc_next = rdc->next; + LISTBASE_FOREACH_MUTABLE (RegionDrawCB *, rdc, &art->drawcalls) { if (rdc->draw == draw_fn) { if (free) { free(rdc->customdata); @@ -284,7 +282,6 @@ void ED_region_draw_cb_remove_by_type(ARegionType *art, void *draw_fn, void (*fr BLI_remlink(&art->drawcalls, rdc); MEM_freeN(rdc); } - rdc = rdc_next; } } diff --git a/source/blender/editors/space_buttons/buttons_texture.c b/source/blender/editors/space_buttons/buttons_texture.c index 4847e8738df..43128ed00fa 100644 --- a/source/blender/editors/space_buttons/buttons_texture.c +++ b/source/blender/editors/space_buttons/buttons_texture.c @@ -64,13 +64,42 @@ #include "ED_screen.h" #include "WM_api.h" +#include "WM_types.h" #include "../interface/interface_intern.h" #include "buttons_intern.h" /* own include */ +static ScrArea *find_area_properties(const bContext *C); +static SpaceProperties *find_space_properties(const bContext *C); + /************************* Texture User **************************/ +static void buttons_texture_user_node_property_add(ListBase *users, + ID *id, + PointerRNA ptr, + PropertyRNA *prop, + bNodeTree *ntree, + bNode *node, + const char *category, + int icon, + const char *name) +{ + ButsTextureUser *user = MEM_callocN(sizeof(ButsTextureUser), "ButsTextureUser"); + + user->id = id; + user->ptr = ptr; + user->prop = prop; + user->ntree = ntree; + user->node = node; + user->category = category; + user->icon = icon; + user->name = name; + user->index = BLI_listbase_count(users); + + BLI_addtail(users, user); +} + static void buttons_texture_user_property_add(ListBase *users, ID *id, PointerRNA ptr, @@ -139,20 +168,66 @@ static void buttons_texture_users_find_nodetree(ListBase *users, } } +static void buttons_texture_modifier_geonodes_users_add(Object *ob, + NodesModifierData *nmd, + bNodeTree *node_tree, + ListBase *users) +{ + PointerRNA ptr; + PropertyRNA *prop; + + LISTBASE_FOREACH (bNode *, node, &node_tree->nodes) { + if (node->type == NODE_GROUP && node->id) { + /* Recurse into the node group */ + buttons_texture_modifier_geonodes_users_add(ob, nmd, (bNodeTree *)node->id, users); + } + else if (node->type == GEO_NODE_ATTRIBUTE_SAMPLE_TEXTURE) { + RNA_pointer_create(&node_tree->id, &RNA_Node, node, &ptr); + prop = RNA_struct_find_property(&ptr, "texture"); + if (prop == NULL) { + continue; + } + + PointerRNA texptr = RNA_property_pointer_get(&ptr, prop); + Tex *tex = (RNA_struct_is_a(texptr.type, &RNA_Texture)) ? (Tex *)texptr.data : NULL; + if (tex != NULL) { + buttons_texture_user_node_property_add(users, + &ob->id, + ptr, + prop, + node_tree, + node, + N_("Geometry Nodes"), + RNA_struct_ui_icon(ptr.type), + nmd->modifier.name); + } + } + } +} + static void buttons_texture_modifier_foreach(void *userData, Object *ob, ModifierData *md, const char *propname) { - PointerRNA ptr; - PropertyRNA *prop; ListBase *users = userData; - RNA_pointer_create(&ob->id, &RNA_Modifier, md, &ptr); - prop = RNA_struct_find_property(&ptr, propname); + if (md->type == eModifierType_Nodes) { + NodesModifierData *nmd = (NodesModifierData *)md; + if (nmd->node_group != NULL) { + buttons_texture_modifier_geonodes_users_add(ob, nmd, nmd->node_group, users); + } + } + else { + PointerRNA ptr; + PropertyRNA *prop; - buttons_texture_user_property_add( - users, &ob->id, ptr, prop, N_("Modifiers"), RNA_struct_ui_icon(ptr.type), md->name); + RNA_pointer_create(&ob->id, &RNA_Modifier, md, &ptr); + prop = RNA_struct_find_property(&ptr, propname); + + buttons_texture_user_property_add( + users, &ob->id, ptr, prop, N_("Modifiers"), RNA_struct_ui_icon(ptr.type), md->name); + } } static void buttons_texture_modifier_gpencil_foreach(void *userData, @@ -325,31 +400,32 @@ void buttons_texture_context_compute(const bContext *C, SpaceProperties *sbuts) ct->texture = NULL; if (ct->user) { + if (ct->user->node != NULL) { + /* Detect change of active texture node in same node tree, in that + * case we also automatically switch to the other node. */ + if ((ct->user->node->flag & NODE_ACTIVE_TEXTURE) == 0) { + ButsTextureUser *user; + for (user = ct->users.first; user; user = user->next) { + if (user->ntree == ct->user->ntree && user->node != ct->user->node) { + if (user->node->flag & NODE_ACTIVE_TEXTURE) { + ct->user = user; + ct->index = BLI_findindex(&ct->users, user); + break; + } + } + } + } + } if (ct->user->ptr.data) { PointerRNA texptr; Tex *tex; - /* get texture datablock pointer if it's a property */ + /* Get texture datablock pointer if it's a property. */ texptr = RNA_property_pointer_get(&ct->user->ptr, ct->user->prop); tex = (RNA_struct_is_a(texptr.type, &RNA_Texture)) ? texptr.data : NULL; ct->texture = tex; } - else if (ct->user->node && !(ct->user->node->flag & NODE_ACTIVE_TEXTURE)) { - ButsTextureUser *user; - - /* detect change of active texture node in same node tree, in that - * case we also automatically switch to the other node */ - for (user = ct->users.first; user; user = user->next) { - if (user->ntree == ct->user->ntree && user->node != ct->user->node) { - if (user->node->flag & NODE_ACTIVE_TEXTURE) { - ct->user = user; - ct->index = BLI_findindex(&ct->users, user); - break; - } - } - } - } } } } @@ -357,7 +433,7 @@ void buttons_texture_context_compute(const bContext *C, SpaceProperties *sbuts) static void template_texture_select(bContext *C, void *user_p, void *UNUSED(arg)) { /* callback when selecting a texture user in the menu */ - SpaceProperties *sbuts = CTX_wm_space_properties(C); + SpaceProperties *sbuts = find_space_properties(C); ButsContextTexture *ct = (sbuts) ? sbuts->texuser : NULL; ButsTextureUser *user = (ButsTextureUser *)user_p; PointerRNA texptr; @@ -371,8 +447,15 @@ static void template_texture_select(bContext *C, void *user_p, void *UNUSED(arg) if (user->node) { ED_node_set_active(CTX_data_main(C), user->ntree, user->node, NULL); ct->texture = NULL; + + /* Not totally sure if we should also change selection? */ + LISTBASE_FOREACH (bNode *, node, &user->ntree->nodes) { + nodeSetSelected(node, false); + } + nodeSetSelected(user->node, true); + WM_event_add_notifier(C, NC_NODE | NA_SELECTED, NULL); } - else { + if (user->ptr.data) { texptr = RNA_property_pointer_get(&user->ptr, user->prop); tex = (RNA_struct_is_a(texptr.type, &RNA_Texture)) ? texptr.data : NULL; @@ -511,16 +594,53 @@ void uiTemplateTextureUser(uiLayout *layout, bContext *C) /************************* Texture Show **************************/ +static ScrArea *find_area_properties(const bContext *C) +{ + bScreen *screen = CTX_wm_screen(C); + Object *ob = CTX_data_active_object(C); + + LISTBASE_FOREACH (ScrArea *, area, &screen->areabase) { + if (area->spacetype == SPACE_PROPERTIES) { + /* Only if unpinned, or if pinned object matches. */ + SpaceProperties *sbuts = area->spacedata.first; + ID *pinid = sbuts->pinid; + if (pinid == NULL || ((GS(pinid->name) == ID_OB) && (Object *)pinid == ob)) { + return area; + } + } + } + + return NULL; +} + +static SpaceProperties *find_space_properties(const bContext *C) +{ + ScrArea *area = find_area_properties(C); + if (area != NULL) { + return area->spacedata.first; + } + + return NULL; +} + static void template_texture_show(bContext *C, void *data_p, void *prop_p) { - SpaceProperties *sbuts = CTX_wm_space_properties(C); - ButsContextTexture *ct = (sbuts) ? sbuts->texuser : NULL; - ButsTextureUser *user; + if (data_p == NULL || prop_p == NULL) { + return; + } + + ScrArea *area = find_area_properties(C); + if (area == NULL) { + return; + } + SpaceProperties *sbuts = (SpaceProperties *)area->spacedata.first; + ButsContextTexture *ct = (sbuts) ? sbuts->texuser : NULL; if (!ct) { return; } + ButsTextureUser *user; for (user = ct->users.first; user; user = user->next) { if (user->ptr.data == data_p && user->prop == prop_p) { break; @@ -537,48 +657,65 @@ static void template_texture_show(bContext *C, void *data_p, void *prop_p) sbuts->preview = 1; /* redraw editor */ - ED_area_tag_redraw(CTX_wm_area(C)); + ED_area_tag_redraw(area); } } +/* Button to quickly show texture in Properties Editor texture tab. */ void uiTemplateTextureShow(uiLayout *layout, const bContext *C, PointerRNA *ptr, PropertyRNA *prop) { - /* button to quickly show texture in texture tab */ - SpaceProperties *sbuts = CTX_wm_space_properties(C); - ButsContextTexture *ct = (sbuts) ? sbuts->texuser : NULL; - ButsTextureUser *user; + /* Only show the button if there is actually a texture assigned. */ + Tex *texture = RNA_property_pointer_get(ptr, prop).data; + if (texture == NULL) { + return; + } - /* only show button in other tabs in properties editor */ - if (!ct || sbuts->mainb == BCONTEXT_TEXTURE) { + /* Only show the button if we are not in the Properties Editor's texture tab. */ + SpaceProperties *sbuts_context = CTX_wm_space_properties(C); + if (sbuts_context != NULL && sbuts_context->mainb == BCONTEXT_TEXTURE) { return; } + SpaceProperties *sbuts = find_space_properties(C); + ButsContextTexture *ct = (sbuts) ? sbuts->texuser : NULL; + /* find corresponding texture user */ - for (user = ct->users.first; user; user = user->next) { - if (user->ptr.data == ptr->data && user->prop == prop) { - break; + ButsTextureUser *user; + bool user_found = false; + if (ct != NULL) { + for (user = ct->users.first; user; user = user->next) { + if (user->ptr.data == ptr->data && user->prop == prop) { + user_found = true; + break; + } } } - /* draw button */ - if (user) { - uiBlock *block = uiLayoutGetBlock(layout); - uiBut *but; - - but = uiDefIconBut(block, - UI_BTYPE_BUT, - 0, - ICON_PROPERTIES, - 0, - 0, - UI_UNIT_X, - UI_UNIT_Y, - NULL, - 0.0, - 0.0, - 0.0, - 0.0, - TIP_("Show texture in texture tab")); - UI_but_func_set(but, template_texture_show, user->ptr.data, user->prop); + /* Draw button (disabled if we cannot find a Properties Editor to display this in). */ + uiBlock *block = uiLayoutGetBlock(layout); + uiBut *but; + but = uiDefIconBut(block, + UI_BTYPE_BUT, + 0, + ICON_PROPERTIES, + 0, + 0, + UI_UNIT_X, + UI_UNIT_Y, + NULL, + 0.0, + 0.0, + 0.0, + 0.0, + TIP_("Show texture in texture tab")); + UI_but_func_set(but, + template_texture_show, + user_found ? user->ptr.data : NULL, + user_found ? user->prop : NULL); + if (ct == NULL) { + UI_but_disable(but, TIP_("No (unpinned) Properties Editor found to display texture in")); + } + else if (!user_found) { + UI_but_disable(but, TIP_("No texture user found")); } } diff --git a/source/blender/editors/space_clip/clip_draw.c b/source/blender/editors/space_clip/clip_draw.c index cbe8ec4ba00..471b4a4bf5b 100644 --- a/source/blender/editors/space_clip/clip_draw.c +++ b/source/blender/editors/space_clip/clip_draw.c @@ -46,6 +46,7 @@ #include "ED_gpencil.h" #include "ED_mask.h" #include "ED_screen.h" +#include "ED_util.h" #include "BIF_glutil.h" diff --git a/source/blender/editors/space_image/image_draw.c b/source/blender/editors/space_image/image_draw.c index 67d5055ec65..2be6d31369c 100644 --- a/source/blender/editors/space_image/image_draw.c +++ b/source/blender/editors/space_image/image_draw.c @@ -68,6 +68,7 @@ #include "ED_mask.h" #include "ED_render.h" #include "ED_screen.h" +#include "ED_util.h" #include "UI_interface.h" #include "UI_resources.h" diff --git a/source/blender/editors/space_image/space_image.c b/source/blender/editors/space_image/space_image.c index 95ca8aba399..c51d2f25efd 100644 --- a/source/blender/editors/space_image/space_image.c +++ b/source/blender/editors/space_image/space_image.c @@ -54,6 +54,7 @@ #include "ED_screen.h" #include "ED_space_api.h" #include "ED_transform.h" +#include "ED_util.h" #include "ED_uvedit.h" #include "WM_api.h" diff --git a/source/blender/editors/space_node/CMakeLists.txt b/source/blender/editors/space_node/CMakeLists.txt index c640b076ba4..bc043a4e665 100644 --- a/source/blender/editors/space_node/CMakeLists.txt +++ b/source/blender/editors/space_node/CMakeLists.txt @@ -42,6 +42,7 @@ set(SRC node_buttons.c node_draw.cc node_edit.c + node_geometry_attribute_search.cc node_gizmo.c node_group.c node_ops.c diff --git a/source/blender/editors/space_node/drawnode.c b/source/blender/editors/space_node/drawnode.c index 82a1cd818c9..977c2053187 100644 --- a/source/blender/editors/space_node/drawnode.c +++ b/source/blender/editors/space_node/drawnode.c @@ -3389,7 +3389,15 @@ static void std_node_socket_draw( case SOCK_STRING: { uiLayout *row = uiLayoutSplit(layout, 0.5f, false); uiItemL(row, text, 0); - uiItemR(row, ptr, "default_value", DEFAULT_FLAGS, "", 0); + + const bNodeTree *node_tree = (const bNodeTree *)node_ptr->owner_id; + if (node_tree->type == NTREE_GEOMETRY) { + node_geometry_add_attribute_search_button(node_tree, node, ptr, row); + } + else { + uiItemR(row, ptr, "default_value", DEFAULT_FLAGS, "", 0); + } + break; } case SOCK_OBJECT: { diff --git a/source/blender/editors/space_node/node_geometry_attribute_search.cc b/source/blender/editors/space_node/node_geometry_attribute_search.cc new file mode 100644 index 00000000000..41f04dad221 --- /dev/null +++ b/source/blender/editors/space_node/node_geometry_attribute_search.cc @@ -0,0 +1,151 @@ +/* + * 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 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +#include "BLI_index_range.hh" +#include "BLI_listbase.h" +#include "BLI_map.hh" +#include "BLI_set.hh" +#include "BLI_string_ref.hh" +#include "BLI_string_search.h" + +#include "DNA_modifier_types.h" +#include "DNA_node_types.h" +#include "DNA_object_types.h" +#include "DNA_space_types.h" + +#include "BKE_context.h" +#include "BKE_node_ui_storage.hh" +#include "BKE_object.h" + +#include "UI_interface.h" +#include "UI_resources.h" + +#include "node_intern.h" + +using blender::IndexRange; +using blender::Map; +using blender::Set; +using blender::StringRef; + +struct AttributeSearchData { + const bNodeTree &node_tree; + const bNode &node; + + uiBut *search_button; + + /* Used to keep track of a button pointer over multiple redraws. Since the UI code + * may reallocate the button, without this we might end up with a dangling pointer. */ + uiButStore *button_store; + uiBlock *button_store_block; +}; + +static void attribute_search_update_fn( + const bContext *C, void *arg, const char *str, uiSearchItems *items, const bool is_first) +{ + AttributeSearchData *data = static_cast<AttributeSearchData *>(arg); + const NodeUIStorage *ui_storage = BKE_node_tree_ui_storage_get_from_context( + C, data->node_tree, data->node); + if (ui_storage == nullptr) { + return; + } + + const Set<std::string> &attribute_name_hints = ui_storage->attribute_name_hints; + + if (str[0] != '\0' && !attribute_name_hints.contains_as(StringRef(str))) { + /* Any string may be valid, so add the current search string with the hints. */ + UI_search_item_add(items, str, (void *)str, ICON_ADD, 0, 0); + } + + /* Skip the filter when the menu is first opened, so all of the items are visible. */ + if (is_first) { + for (const std::string &attribute_name : attribute_name_hints) { + /* Just use the pointer to the name string as the search data, + * since it's not used anyway but we need a pointer. */ + UI_search_item_add(items, attribute_name.c_str(), (void *)&attribute_name, ICON_NONE, 0, 0); + } + return; + } + + StringSearch *search = BLI_string_search_new(); + for (const std::string &attribute_name : attribute_name_hints) { + BLI_string_search_add(search, attribute_name.c_str(), (void *)&attribute_name); + } + + std::string **filtered_items; + const int filtered_amount = BLI_string_search_query(search, str, (void ***)&filtered_items); + + for (const int i : IndexRange(filtered_amount)) { + std::string *item = filtered_items[i]; + if (!UI_search_item_add(items, item->c_str(), item, ICON_NONE, 0, 0)) { + break; + } + } + + MEM_freeN(filtered_items); + BLI_string_search_free(search); +} + +static void attribute_search_free_fn(void *arg) +{ + AttributeSearchData *data = static_cast<AttributeSearchData *>(arg); + + UI_butstore_free(data->button_store_block, data->button_store); + delete data; +} + +void node_geometry_add_attribute_search_button(const bNodeTree *node_tree, + const bNode *node, + PointerRNA *socket_ptr, + uiLayout *layout) +{ + uiBlock *block = uiLayoutGetBlock(layout); + uiBut *but = uiDefIconTextButR(block, + UI_BTYPE_SEARCH_MENU, + 0, + ICON_NONE, + "", + 0, + 0, + 10 * UI_UNIT_X, /* Dummy value, replaced by layout system. */ + UI_UNIT_Y, + socket_ptr, + "default_value", + 0, + 0.0f, + 0.0f, + 0.0f, + 0.0f, + ""); + + AttributeSearchData *data = new AttributeSearchData{ + *node_tree, + *node, + but, + UI_butstore_create(block), + block, + }; + + UI_butstore_register(data->button_store, &data->search_button); + + UI_but_func_search_set_results_are_suggestions(but, true); + UI_but_func_search_set(but, + nullptr, + attribute_search_update_fn, + static_cast<void *>(data), + attribute_search_free_fn, + nullptr, + nullptr); +} diff --git a/source/blender/editors/space_node/node_intern.h b/source/blender/editors/space_node/node_intern.h index 5973d59e68f..972e6cab123 100644 --- a/source/blender/editors/space_node/node_intern.h +++ b/source/blender/editors/space_node/node_intern.h @@ -38,9 +38,11 @@ struct bContext; struct bNode; struct bNodeLink; struct bNodeSocket; +struct uiBut; struct wmGizmoGroupType; struct wmKeyConfig; struct wmWindow; +struct uiBlock; #ifdef __cplusplus extern "C" { @@ -289,6 +291,12 @@ void NODE_GGT_backdrop_corner_pin(struct wmGizmoGroupType *gzgt); void NODE_OT_cryptomatte_layer_add(struct wmOperatorType *ot); void NODE_OT_cryptomatte_layer_remove(struct wmOperatorType *ot); +/* node_geometry_attribute_search.cc */ +void node_geometry_add_attribute_search_button(const struct bNodeTree *node_tree, + const struct bNode *node, + struct PointerRNA *socket_ptr, + struct uiLayout *layout); + extern const char *node_context_dir[]; /* XXXXXX */ diff --git a/source/blender/editors/space_node/node_select.c b/source/blender/editors/space_node/node_select.c index 58d22c2864f..704b7350bb9 100644 --- a/source/blender/editors/space_node/node_select.c +++ b/source/blender/editors/space_node/node_select.c @@ -1178,7 +1178,8 @@ static void node_find_create_label(const bNode *node, char *str, int maxlen) static void node_find_update_fn(const struct bContext *C, void *UNUSED(arg), const char *str, - uiSearchItems *items) + uiSearchItems *items, + const bool UNUSED(is_first)) { SpaceNode *snode = CTX_wm_space_node(C); diff --git a/source/blender/editors/space_outliner/outliner_collections.c b/source/blender/editors/space_outliner/outliner_collections.c index 0afc26e0d8a..ef5733fe375 100644 --- a/source/blender/editors/space_outliner/outliner_collections.c +++ b/source/blender/editors/space_outliner/outliner_collections.c @@ -1367,7 +1367,7 @@ void OUTLINER_OT_collection_enable(wmOperatorType *ot) /* identifiers */ ot->name = "Enable Collection"; ot->idname = "OUTLINER_OT_collection_enable"; - ot->description = "Enable viewport drawing in the view layers"; + ot->description = "Enable viewport display in the view layers"; /* api callbacks */ ot->exec = collection_flag_exec; @@ -1382,7 +1382,7 @@ void OUTLINER_OT_collection_disable(wmOperatorType *ot) /* identifiers */ ot->name = "Disable Collection"; ot->idname = "OUTLINER_OT_collection_disable"; - ot->description = "Disable viewport drawing in the view layers"; + ot->description = "Disable viewport display in the view layers"; /* api callbacks */ ot->exec = collection_flag_exec; diff --git a/source/blender/editors/space_outliner/outliner_tools.c b/source/blender/editors/space_outliner/outliner_tools.c index 8726fd768d4..b735064cfef 100644 --- a/source/blender/editors/space_outliner/outliner_tools.c +++ b/source/blender/editors/space_outliner/outliner_tools.c @@ -554,7 +554,8 @@ static void merged_element_search_fn_recursive( static void merged_element_search_update_fn(const bContext *UNUSED(C), void *data, const char *str, - uiSearchItems *items) + uiSearchItems *items, + const bool UNUSED(is_first)) { MergedSearchData *search_data = (MergedSearchData *)data; TreeElement *parent = search_data->parent_element; diff --git a/source/blender/editors/space_sequencer/sequencer_add.c b/source/blender/editors/space_sequencer/sequencer_add.c index a9033b98708..037ce78b9a2 100644 --- a/source/blender/editors/space_sequencer/sequencer_add.c +++ b/source/blender/editors/space_sequencer/sequencer_add.c @@ -36,6 +36,7 @@ #include "DNA_mask_types.h" #include "DNA_scene_types.h" +#include "DNA_sound_types.h" #include "BKE_context.h" #include "BKE_lib_id.h" @@ -44,6 +45,8 @@ #include "BKE_movieclip.h" #include "BKE_report.h" +#include "IMB_imbuf.h" + #include "WM_api.h" #include "WM_types.h" @@ -89,8 +92,6 @@ typedef struct SequencerAddData { #define SEQPROP_NOCHAN (1 << 3) #define SEQPROP_FIT_METHOD (1 << 4) -#define SELECT 1 - static const EnumPropertyItem scale_fit_methods[] = { {SEQ_SCALE_TO_FIT, "FIT", 0, "Scale to Fit", "Scale image to fit within the canvas"}, {SEQ_SCALE_TO_FILL, "FILL", 0, "Scale to Fill", "Scale image to completely fill the canvas"}, @@ -216,7 +217,7 @@ static void sequencer_generic_invoke_xy__internal(bContext *C, wmOperator *op, i } } -static void seq_load_operator_info(SeqLoadInfo *seq_load, bContext *C, wmOperator *op) +static void load_data_init_from_operator(SeqLoadData *load_data, bContext *C, wmOperator *op) { Main *bmain = CTX_data_main(C); @@ -224,69 +225,56 @@ static void seq_load_operator_info(SeqLoadInfo *seq_load, bContext *C, wmOperato const bool relative = (prop = RNA_struct_find_property(op->ptr, "relative_path")) && RNA_property_boolean_get(op->ptr, prop); int is_file = -1; - memset(seq_load, 0, sizeof(SeqLoadInfo)); + memset(load_data, 0, sizeof(SeqLoadData)); - seq_load->start_frame = RNA_int_get(op->ptr, "frame_start"); - seq_load->end_frame = seq_load->start_frame; - seq_load->channel = RNA_int_get(op->ptr, "channel"); - seq_load->len = 1; - seq_load->fit_method = RNA_enum_get(op->ptr, "fit_method"); - SEQ_tool_settings_fit_method_set(CTX_data_scene(C), seq_load->fit_method); + load_data->start_frame = RNA_int_get(op->ptr, "frame_start"); + load_data->channel = RNA_int_get(op->ptr, "channel"); + load_data->image.end_frame = load_data->start_frame; + load_data->image.len = 1; + load_data->fit_method = RNA_enum_get(op->ptr, "fit_method"); + SEQ_tool_settings_fit_method_set(CTX_data_scene(C), load_data->fit_method); if ((prop = RNA_struct_find_property(op->ptr, "filepath"))) { /* Full path, file is set by the caller. */ - RNA_property_string_get(op->ptr, prop, seq_load->path); + RNA_property_string_get(op->ptr, prop, load_data->path); is_file = 1; } else if ((prop = RNA_struct_find_property(op->ptr, "directory"))) { /* Full path, file is set by the caller. */ - RNA_property_string_get(op->ptr, prop, seq_load->path); + RNA_property_string_get(op->ptr, prop, load_data->path); is_file = 0; } if ((is_file != -1) && relative) { - BLI_path_rel(seq_load->path, BKE_main_blendfile_path(bmain)); + BLI_path_rel(load_data->path, BKE_main_blendfile_path(bmain)); } if ((prop = RNA_struct_find_property(op->ptr, "frame_end"))) { - seq_load->end_frame = RNA_property_int_get(op->ptr, prop); - } - - if ((prop = RNA_struct_find_property(op->ptr, "replace_sel")) && - RNA_property_boolean_get(op->ptr, prop)) { - seq_load->flag |= SEQ_LOAD_REPLACE_SEL; + load_data->image.end_frame = RNA_property_int_get(op->ptr, prop); } if ((prop = RNA_struct_find_property(op->ptr, "cache")) && RNA_property_boolean_get(op->ptr, prop)) { - seq_load->flag |= SEQ_LOAD_SOUND_CACHE; + load_data->flags |= SEQ_LOAD_SOUND_CACHE; } if ((prop = RNA_struct_find_property(op->ptr, "mono")) && RNA_property_boolean_get(op->ptr, prop)) { - seq_load->flag |= SEQ_LOAD_SOUND_MONO; - } - - if ((prop = RNA_struct_find_property(op->ptr, "sound")) && - RNA_property_boolean_get(op->ptr, prop)) { - seq_load->flag |= SEQ_LOAD_MOVIE_SOUND; + load_data->flags |= SEQ_LOAD_SOUND_MONO; } if ((prop = RNA_struct_find_property(op->ptr, "use_framerate")) && RNA_property_boolean_get(op->ptr, prop)) { - seq_load->flag |= SEQ_LOAD_SYNC_FPS; + load_data->flags |= SEQ_LOAD_MOVIE_SYNC_FPS; } - /* Create consecutive array of strips. */ - seq_load->flag |= SEQ_LOAD_FRAME_ADVANCE; - if (is_file == 1) { - BLI_strncpy(seq_load->name, BLI_path_basename(seq_load->path), sizeof(seq_load->name)); + BLI_strncpy(load_data->name, BLI_path_basename(load_data->path), sizeof(load_data->name)); } else if ((prop = RNA_struct_find_property(op->ptr, "files"))) { RNA_PROP_BEGIN (op->ptr, itemptr, prop) { char *name = RNA_string_get_alloc(&itemptr, "name", NULL, 0); - BLI_strncpy(seq_load->name, name, sizeof(seq_load->name)); + BLI_strncpy(load_data->name, name, sizeof(load_data->name)); MEM_freeN(name); break; } @@ -299,36 +287,31 @@ static void seq_load_operator_info(SeqLoadInfo *seq_load, bContext *C, wmOperato SequencerAddData *sad = op->customdata; ImageFormatData *imf = &sad->im_format; - seq_load->views_format = imf->views_format; - seq_load->flag |= SEQ_USE_VIEWS; - seq_load->stereo3d_format = &imf->stereo3d_format; + load_data->use_multiview = true; + load_data->views_format = imf->views_format; + load_data->stereo3d_format = &imf->stereo3d_format; } } } -/** - * Apply generic operator options. - */ -static void sequencer_add_apply_overlap(bContext *C, wmOperator *op, Sequence *seq) +static void seq_load_apply_generic_options(bContext *C, wmOperator *op, Sequence *seq) { Scene *scene = CTX_data_scene(C); Editing *ed = SEQ_editing_get(scene, false); - if (RNA_boolean_get(op->ptr, "overlap") == false) { - if (SEQ_transform_test_overlap(ed->seqbasep, seq)) { - SEQ_transform_seqbase_shuffle(ed->seqbasep, seq, scene); - } + if (seq == NULL) { + return; } -} - -static void sequencer_add_apply_replace_sel(bContext *C, wmOperator *op, Sequence *seq) -{ - Scene *scene = CTX_data_scene(C); if (RNA_boolean_get(op->ptr, "replace_sel")) { - ED_sequencer_deselect_all(scene); - SEQ_select_active_set(scene, seq); seq->flag |= SELECT; + SEQ_select_active_set(scene, seq); + } + + if (RNA_boolean_get(op->ptr, "overlap") == false) { + if (SEQ_transform_test_overlap(ed->seqbasep, seq)) { + SEQ_transform_seqbase_shuffle(ed->seqbasep, seq, scene); + } } } @@ -356,34 +339,24 @@ static int sequencer_add_scene_strip_exec(bContext *C, wmOperator *op) { Main *bmain = CTX_data_main(C); Scene *scene = CTX_data_scene(C); - Editing *ed = SEQ_editing_get(scene, true); - Scene *sce_seq; - Sequence *seq; - - int start_frame, channel; - start_frame = RNA_int_get(op->ptr, "frame_start"); - channel = RNA_int_get(op->ptr, "channel"); - sce_seq = BLI_findlink(&bmain->scenes, RNA_enum_get(op->ptr, "scene")); + const Editing *ed = SEQ_editing_get(scene, true); + Scene *sce_seq = BLI_findlink(&bmain->scenes, RNA_enum_get(op->ptr, "scene")); if (sce_seq == NULL) { BKE_report(op->reports, RPT_ERROR, "Scene not found"); return OPERATOR_CANCELLED; } - seq = SEQ_sequence_alloc(ed->seqbasep, start_frame, channel, SEQ_TYPE_SCENE); - seq->blend_mode = SEQ_TYPE_CROSS; - seq->scene = sce_seq; - seq->len = sce_seq->r.efra - sce_seq->r.sfra + 1; - - BLI_strncpy(seq->name + 2, sce_seq->id.name + 2, sizeof(seq->name) - 2); - SEQ_sequence_base_unique_name_recursive(&ed->seqbase, seq); + if (RNA_boolean_get(op->ptr, "replace_sel")) { + ED_sequencer_deselect_all(scene); + } - SEQ_time_update_sequence_bounds(scene, seq); - SEQ_sort(scene); + SeqLoadData load_data; + load_data_init_from_operator(&load_data, C, op); + load_data.scene = sce_seq; - sequencer_add_apply_replace_sel(C, op, seq); - sequencer_add_apply_overlap(C, op, seq); - SEQ_relations_invalidate_cache_composite(scene, seq); + Sequence *seq = SEQ_add_scene_strip(scene, ed->seqbasep, &load_data); + seq_load_apply_generic_options(C, op, seq); DEG_id_tag_update(&scene->id, ID_RECALC_SEQUENCER_STRIPS); DEG_relations_tag_update(bmain); @@ -430,36 +403,24 @@ static int sequencer_add_movieclip_strip_exec(bContext *C, wmOperator *op) { Main *bmain = CTX_data_main(C); Scene *scene = CTX_data_scene(C); - Editing *ed = SEQ_editing_get(scene, true); - MovieClip *clip; - Sequence *seq; - - int start_frame, channel; - start_frame = RNA_int_get(op->ptr, "frame_start"); - channel = RNA_int_get(op->ptr, "channel"); - clip = BLI_findlink(&bmain->movieclips, RNA_enum_get(op->ptr, "clip")); + const Editing *ed = SEQ_editing_get(scene, true); + MovieClip *clip = BLI_findlink(&bmain->movieclips, RNA_enum_get(op->ptr, "clip")); if (clip == NULL) { BKE_report(op->reports, RPT_ERROR, "Movie clip not found"); return OPERATOR_CANCELLED; } - seq = SEQ_sequence_alloc(ed->seqbasep, start_frame, channel, SEQ_TYPE_MOVIECLIP); - seq->blend_mode = SEQ_TYPE_CROSS; - seq->clip = clip; - seq->len = BKE_movieclip_get_duration(clip); - - id_us_ensure_real(&seq->clip->id); - - BLI_strncpy(seq->name + 2, clip->id.name + 2, sizeof(seq->name) - 2); - SEQ_sequence_base_unique_name_recursive(&ed->seqbase, seq); + if (RNA_boolean_get(op->ptr, "replace_sel")) { + ED_sequencer_deselect_all(scene); + } - SEQ_time_update_sequence_bounds(scene, seq); - SEQ_sort(scene); + SeqLoadData load_data; + load_data_init_from_operator(&load_data, C, op); + load_data.clip = clip; - sequencer_add_apply_replace_sel(C, op, seq); - sequencer_add_apply_overlap(C, op, seq); - SEQ_relations_invalidate_cache_composite(scene, seq); + Sequence *seq = SEQ_add_movieclip_strip(scene, ed->seqbasep, &load_data); + seq_load_apply_generic_options(C, op, seq); DEG_id_tag_update(&scene->id, ID_RECALC_SEQUENCER_STRIPS); WM_event_add_notifier(C, NC_SCENE | ND_SEQUENCER, scene); @@ -506,36 +467,24 @@ static int sequencer_add_mask_strip_exec(bContext *C, wmOperator *op) { Main *bmain = CTX_data_main(C); Scene *scene = CTX_data_scene(C); - Editing *ed = SEQ_editing_get(scene, true); - Mask *mask; - Sequence *seq; - - int start_frame, channel; - start_frame = RNA_int_get(op->ptr, "frame_start"); - channel = RNA_int_get(op->ptr, "channel"); - mask = BLI_findlink(&bmain->masks, RNA_enum_get(op->ptr, "mask")); + const Editing *ed = SEQ_editing_get(scene, true); + Mask *mask = BLI_findlink(&bmain->masks, RNA_enum_get(op->ptr, "mask")); if (mask == NULL) { BKE_report(op->reports, RPT_ERROR, "Mask not found"); return OPERATOR_CANCELLED; } - seq = SEQ_sequence_alloc(ed->seqbasep, start_frame, channel, SEQ_TYPE_MASK); - seq->blend_mode = SEQ_TYPE_CROSS; - seq->mask = mask; - seq->len = BKE_mask_get_duration(mask); - - id_us_ensure_real(&seq->mask->id); - - BLI_strncpy(seq->name + 2, mask->id.name + 2, sizeof(seq->name) - 2); - SEQ_sequence_base_unique_name_recursive(&ed->seqbase, seq); + if (RNA_boolean_get(op->ptr, "replace_sel")) { + ED_sequencer_deselect_all(scene); + } - SEQ_time_update_sequence_bounds(scene, seq); - SEQ_sort(scene); + SeqLoadData load_data; + load_data_init_from_operator(&load_data, C, op); + load_data.mask = mask; - sequencer_add_apply_replace_sel(C, op, seq); - sequencer_add_apply_overlap(C, op, seq); - SEQ_relations_invalidate_cache_composite(scene, seq); + Sequence *seq = SEQ_add_mask_strip(scene, ed->seqbasep, &load_data); + seq_load_apply_generic_options(C, op, seq); DEG_id_tag_update(&scene->id, ID_RECALC_SEQUENCER_STRIPS); WM_event_add_notifier(C, NC_SCENE | ND_SEQUENCER, scene); @@ -577,100 +526,120 @@ void SEQUENCER_OT_mask_strip_add(struct wmOperatorType *ot) ot->prop = prop; } -static int sequencer_add_generic_strip_exec(bContext *C, wmOperator *op, SeqLoadFn seq_load_fn) +static void sequencer_add_init(bContext *UNUSED(C), wmOperator *op) { - Scene *scene = CTX_data_scene(C); - Editing *ed = SEQ_editing_get(scene, true); - SeqLoadInfo seq_load; - int tot_files; - - seq_load_operator_info(&seq_load, C, op); + op->customdata = MEM_callocN(sizeof(SequencerAddData), __func__); +} - if (seq_load.flag & SEQ_LOAD_REPLACE_SEL) { - ED_sequencer_deselect_all(scene); +static void sequencer_add_cancel(bContext *UNUSED(C), wmOperator *op) +{ + if (op->customdata) { + MEM_freeN(op->customdata); } + op->customdata = NULL; +} - tot_files = RNA_property_collection_length(op->ptr, RNA_struct_find_property(op->ptr, "files")); - - if (tot_files > 1) { - char dir_only[FILE_MAX]; - char file_only[FILE_MAX]; - - RNA_BEGIN (op->ptr, itemptr, "files") { - Sequence *seq; +static bool sequencer_add_draw_check_fn(PointerRNA *UNUSED(ptr), + PropertyRNA *prop, + void *UNUSED(user_data)) +{ + const char *prop_id = RNA_property_identifier(prop); - RNA_string_get(op->ptr, "directory", dir_only); - RNA_string_get(&itemptr, "name", file_only); - BLI_join_dirfile(seq_load.path, sizeof(seq_load.path), dir_only, file_only); + return !(STR_ELEM(prop_id, "filepath", "directory", "filename")); +} - /* Set seq_load.name, otherwise all video/audio files get the same name. */ - BLI_strncpy(seq_load.name, file_only, sizeof(seq_load.name)); +static void sequencer_add_movie_multiple_strips(bContext *C, + wmOperator *op, + SeqLoadData *load_data) +{ + Main *bmain = CTX_data_main(C); + Scene *scene = CTX_data_scene(C); + const Editing *ed = SEQ_editing_get(scene, true); - seq = seq_load_fn(C, ed->seqbasep, &seq_load); - if (seq) { - if (seq_load.seq_sound) { - sequencer_add_apply_overlap(C, op, seq_load.seq_sound); - } - sequencer_add_apply_overlap(C, op, seq); - } + RNA_BEGIN (op->ptr, itemptr, "files") { + char dir_only[FILE_MAX]; + char file_only[FILE_MAX]; + RNA_string_get(op->ptr, "directory", dir_only); + RNA_string_get(&itemptr, "name", file_only); + BLI_join_dirfile(load_data->path, sizeof(load_data->path), dir_only, file_only); + BLI_strncpy(load_data->name, file_only, sizeof(load_data->name)); + Sequence *seq_movie = NULL; + Sequence *seq_sound = NULL; + load_data->channel++; + seq_movie = SEQ_add_movie_strip(bmain, scene, ed->seqbasep, load_data); + load_data->channel--; + if (seq_movie == NULL) { + BKE_reportf(op->reports, RPT_ERROR, "File '%s' could not be loaded", load_data->path); } - RNA_END; - } - else { /* Single file./ */ - Sequence *seq; - seq = seq_load_fn(C, ed->seqbasep, &seq_load); - - if (seq) { - if (seq_load.seq_sound) { - sequencer_add_apply_overlap(C, op, seq_load.seq_sound); + else { + if (RNA_boolean_get(op->ptr, "sound")) { + seq_sound = SEQ_add_sound_strip(bmain, scene, ed->seqbasep, load_data); } - sequencer_add_apply_overlap(C, op, seq); + load_data->start_frame += seq_movie->enddisp - seq_movie->startdisp; + seq_load_apply_generic_options(C, op, seq_sound); + seq_load_apply_generic_options(C, op, seq_movie); } } + RNA_END; +} - if (op->customdata) { - MEM_freeN(op->customdata); - } +static bool sequencer_add_movie_single_strip(bContext *C, wmOperator *op, SeqLoadData *load_data) +{ + Main *bmain = CTX_data_main(C); + Scene *scene = CTX_data_scene(C); + const Editing *ed = SEQ_editing_get(scene, true); - if (seq_load.tot_success == 0) { - BKE_reportf(op->reports, RPT_ERROR, "File '%s' could not be loaded", seq_load.path); + Sequence *seq_movie = NULL; + Sequence *seq_sound = NULL; + load_data->channel++; + seq_movie = SEQ_add_movie_strip(bmain, scene, ed->seqbasep, load_data); + load_data->channel--; - return OPERATOR_CANCELLED; + if (seq_movie == NULL) { + BKE_reportf(op->reports, RPT_ERROR, "File '%s' could not be loaded", load_data->path); + return false; } + if (RNA_boolean_get(op->ptr, "sound")) { + seq_sound = SEQ_add_sound_strip(bmain, scene, ed->seqbasep, load_data); + } + seq_load_apply_generic_options(C, op, seq_sound); + seq_load_apply_generic_options(C, op, seq_movie); - SEQ_sort(scene); - - DEG_id_tag_update(&scene->id, ID_RECALC_SEQUENCER_STRIPS); - WM_event_add_notifier(C, NC_SCENE | ND_SEQUENCER, scene); - - return OPERATOR_FINISHED; + return true; } -static void sequencer_add_init(bContext *UNUSED(C), wmOperator *op) +static int sequencer_add_movie_strip_exec(bContext *C, wmOperator *op) { - op->customdata = MEM_callocN(sizeof(SequencerAddData), __func__); -} + Main *bmain = CTX_data_main(C); + Scene *scene = CTX_data_scene(C); + SeqLoadData load_data; + + load_data_init_from_operator(&load_data, C, op); + + if (RNA_boolean_get(op->ptr, "replace_sel")) { + ED_sequencer_deselect_all(scene); + } + + const int tot_files = RNA_property_collection_length(op->ptr, + RNA_struct_find_property(op->ptr, "files")); + if (tot_files > 1) { + sequencer_add_movie_multiple_strips(C, op, &load_data); + } + else { + if (!sequencer_add_movie_single_strip(C, op, &load_data)) { + return OPERATOR_CANCELLED; + } + } -static void sequencer_add_cancel(bContext *UNUSED(C), wmOperator *op) -{ if (op->customdata) { MEM_freeN(op->customdata); } - op->customdata = NULL; -} -static bool sequencer_add_draw_check_fn(PointerRNA *UNUSED(ptr), - PropertyRNA *prop, - void *UNUSED(user_data)) -{ - const char *prop_id = RNA_property_identifier(prop); - - return !(STR_ELEM(prop_id, "filepath", "directory", "filename")); -} + DEG_relations_tag_update(bmain); + DEG_id_tag_update(&scene->id, ID_RECALC_SEQUENCER_STRIPS); + WM_event_add_notifier(C, NC_SCENE | ND_SEQUENCER, scene); -static int sequencer_add_movie_strip_exec(bContext *C, wmOperator *op) -{ - return sequencer_add_generic_strip_exec(C, op, SEQ_add_movie_strip); + return OPERATOR_FINISHED; } static int sequencer_add_movie_strip_invoke(bContext *C, @@ -681,7 +650,8 @@ static int sequencer_add_movie_strip_invoke(bContext *C, Scene *scene = CTX_data_scene(C); Editing *ed = SEQ_editing_get(scene, false); - /* Only enable "use_framerate" if there aren't any existing strips, unless overridden by user. */ + /* Only enable "use_framerate" if there aren't any existing strips, unless overridden by user. + */ if (ed && ed->seqbasep && ed->seqbasep->first) { RNA_boolean_set(op->ptr, "use_framerate", false); } @@ -761,9 +731,80 @@ void SEQUENCER_OT_movie_strip_add(struct wmOperatorType *ot) "Use framerate from the movie to keep sound and video in sync"); } +static void sequencer_add_sound_multiple_strips(bContext *C, + wmOperator *op, + SeqLoadData *load_data) +{ + Main *bmain = CTX_data_main(C); + Scene *scene = CTX_data_scene(C); + Editing *ed = SEQ_editing_get(scene, true); + + RNA_BEGIN (op->ptr, itemptr, "files") { + char dir_only[FILE_MAX]; + char file_only[FILE_MAX]; + RNA_string_get(op->ptr, "directory", dir_only); + RNA_string_get(&itemptr, "name", file_only); + BLI_join_dirfile(load_data->path, sizeof(load_data->path), dir_only, file_only); + BLI_strncpy(load_data->name, file_only, sizeof(load_data->name)); + Sequence *seq = SEQ_add_sound_strip(bmain, scene, ed->seqbasep, load_data); + if (seq == NULL) { + BKE_reportf(op->reports, RPT_ERROR, "File '%s' could not be loaded", load_data->path); + } + else { + seq_load_apply_generic_options(C, op, seq); + load_data->start_frame += seq->enddisp - seq->startdisp; + } + } + RNA_END; +} + +static bool sequencer_add_sound_single_strip(bContext *C, wmOperator *op, SeqLoadData *load_data) +{ + Main *bmain = CTX_data_main(C); + Scene *scene = CTX_data_scene(C); + Editing *ed = SEQ_editing_get(scene, true); + + Sequence *seq = SEQ_add_sound_strip(bmain, scene, ed->seqbasep, load_data); + if (seq == NULL) { + BKE_reportf(op->reports, RPT_ERROR, "File '%s' could not be loaded", load_data->path); + return false; + } + seq_load_apply_generic_options(C, op, seq); + + return true; +} + static int sequencer_add_sound_strip_exec(bContext *C, wmOperator *op) { - return sequencer_add_generic_strip_exec(C, op, SEQ_add_sound_strip); + Main *bmain = CTX_data_main(C); + Scene *scene = CTX_data_scene(C); + SeqLoadData load_data; + load_data_init_from_operator(&load_data, C, op); + + if (RNA_boolean_get(op->ptr, "replace_sel")) { + ED_sequencer_deselect_all(scene); + } + + const int tot_files = RNA_property_collection_length(op->ptr, + RNA_struct_find_property(op->ptr, "files")); + if (tot_files > 1) { + sequencer_add_sound_multiple_strips(C, op, &load_data); + } + else { + if (!sequencer_add_sound_single_strip(C, op, &load_data)) { + return OPERATOR_CANCELLED; + } + } + + if (op->customdata) { + MEM_freeN(op->customdata); + } + + DEG_relations_tag_update(bmain); + DEG_id_tag_update(&scene->id, ID_RECALC_SEQUENCER_STRIPS); + WM_event_add_notifier(C, NC_SCENE | ND_SEQUENCER, scene); + + return OPERATOR_FINISHED; } static int sequencer_add_sound_strip_invoke(bContext *C, @@ -873,78 +914,82 @@ void sequencer_image_seq_reserve_frames( } } -static int sequencer_add_image_strip_exec(bContext *C, wmOperator *op) +static int sequencer_add_image_strip_calculate_length(wmOperator *op, + const int start_frame, + int *minframe, + int *numdigits) { - int minframe, numdigits; - Scene *scene = CTX_data_scene(C); - Editing *ed = SEQ_editing_get(scene, true); - SeqLoadInfo seq_load; - Sequence *seq; - Strip *strip; - StripElem *se; const bool use_placeholders = RNA_boolean_get(op->ptr, "use_placeholders"); - seq_load_operator_info(&seq_load, C, op); - - /* Images are unique in how they handle this - 1 per strip elem. */ if (use_placeholders) { - seq_load.len = sequencer_image_seq_get_minmax_frame( - op, seq_load.start_frame, &minframe, &numdigits); + return sequencer_image_seq_get_minmax_frame(op, start_frame, minframe, numdigits); } else { - seq_load.len = RNA_property_collection_length(op->ptr, - RNA_struct_find_property(op->ptr, "files")); - } - - if (seq_load.len == 0) { - return OPERATOR_CANCELLED; + return RNA_property_collection_length(op->ptr, RNA_struct_find_property(op->ptr, "files")); } +} - if (seq_load.flag & SEQ_LOAD_REPLACE_SEL) { - ED_sequencer_deselect_all(scene); - } +static void sequencer_add_image_strip_load_files( + wmOperator *op, Sequence *seq, SeqLoadData *load_data, const int minframe, const int numdigits) +{ + const bool use_placeholders = RNA_boolean_get(op->ptr, "use_placeholders"); - /* Main adding function. */ - seq = SEQ_add_image_strip(C, ed->seqbasep, &seq_load); - strip = seq->strip; - se = strip->stripdata; - seq->blend_mode = SEQ_TYPE_ALPHAOVER; + SEQ_add_image_set_directory(seq, load_data->path); if (use_placeholders) { - sequencer_image_seq_reserve_frames(op, se, seq_load.len, minframe, numdigits); + sequencer_image_seq_reserve_frames( + op, seq->strip->stripdata, load_data->image.len, minframe, numdigits); } else { + size_t strip_frame = 0; RNA_BEGIN (op->ptr, itemptr, "files") { char *filename = RNA_string_get_alloc(&itemptr, "name", NULL, 0); - BLI_strncpy(se->name, filename, sizeof(se->name)); + SEQ_add_image_load_file(seq, strip_frame, filename); MEM_freeN(filename); - se++; + strip_frame++; } RNA_END; } +} - if (seq_load.len == 1) { - if (seq_load.start_frame < seq_load.end_frame) { - seq->endstill = seq_load.end_frame - seq_load.start_frame; - } +static int sequencer_add_image_strip_exec(bContext *C, wmOperator *op) +{ + Scene *scene = CTX_data_scene(C); + Editing *ed = SEQ_editing_get(scene, true); + + SeqLoadData load_data; + load_data_init_from_operator(&load_data, C, op); + + int minframe, numdigits; + load_data.image.len = sequencer_add_image_strip_calculate_length( + op, load_data.start_frame, &minframe, &numdigits); + if (load_data.image.len == 0) { + return OPERATOR_CANCELLED; } - SEQ_render_init_colorspace(seq); - SEQ_time_update_sequence_bounds(scene, seq); - SEQ_sort(scene); + if (RNA_boolean_get(op->ptr, "replace_sel")) { + ED_sequencer_deselect_all(scene); + } - /* Last active name. */ - BLI_strncpy(ed->act_imagedir, strip->dir, sizeof(ed->act_imagedir)); - sequencer_add_apply_overlap(C, op, seq); + Sequence *seq = SEQ_add_image_strip(CTX_data_main(C), scene, ed->seqbasep, &load_data); + sequencer_add_image_strip_load_files(op, seq, &load_data, minframe, numdigits); + SEQ_add_image_init_alpha_mode(seq); - if (op->customdata) { - MEM_freeN(op->customdata); + /* Adjust length. */ + if (load_data.image.len == 1) { + SEQ_transform_set_right_handle_frame(seq, load_data.image.end_frame); + SEQ_time_update_sequence(scene, seq); } - SEQ_relations_invalidate_cache_composite(scene, seq); + seq_load_apply_generic_options(C, op, seq); + DEG_id_tag_update(&scene->id, ID_RECALC_SEQUENCER_STRIPS); WM_event_add_notifier(C, NC_SCENE | ND_SEQUENCER, scene); + if (op->customdata) { + MEM_freeN(op->customdata); + } + return OPERATOR_FINISHED; } @@ -1016,80 +1061,46 @@ static int sequencer_add_effect_strip_exec(bContext *C, wmOperator *op) { Scene *scene = CTX_data_scene(C); Editing *ed = SEQ_editing_get(scene, true); - Sequence *seq; - struct SeqEffectHandle sh; - Sequence *seq1, *seq2, *seq3; const char *error_msg; - int start_frame, end_frame, channel, type; - start_frame = RNA_int_get(op->ptr, "frame_start"); - end_frame = RNA_int_get(op->ptr, "frame_end"); - channel = RNA_int_get(op->ptr, "channel"); - type = RNA_enum_get(op->ptr, "type"); + SeqLoadData load_data; + load_data_init_from_operator(&load_data, C, op); + load_data.effect.type = RNA_enum_get(op->ptr, "type"); - if (!seq_effect_find_selected(scene, NULL, type, &seq1, &seq2, &seq3, &error_msg)) { + Sequence *seq1, *seq2, *seq3; + if (!seq_effect_find_selected( + scene, NULL, load_data.effect.type, &seq1, &seq2, &seq3, &error_msg)) { BKE_report(op->reports, RPT_ERROR, error_msg); return OPERATOR_CANCELLED; } - /* Check its start and end frames are valid. */ - if (seq1 == NULL && end_frame <= start_frame) { - end_frame = start_frame + 1; - RNA_int_set(op->ptr, "frame_end", end_frame); - } - - seq = SEQ_sequence_alloc(ed->seqbasep, start_frame, channel, type); - BLI_strncpy(seq->name + 2, SEQ_sequence_give_name(seq), sizeof(seq->name) - 2); - SEQ_sequence_base_unique_name_recursive(&ed->seqbase, seq); - - sh = SEQ_effect_handle_get(seq); - sh.init(seq); - seq->seq1 = seq1; - seq->seq2 = seq2; - seq->seq3 = seq3; - - if (!seq1) { - seq->len = 1; /* Effect is generator, set non zero length. */ - SEQ_transform_set_right_handle_frame(seq, end_frame); + if (RNA_boolean_get(op->ptr, "replace_sel")) { + ED_sequencer_deselect_all(scene); } - seq->flag |= SEQ_USE_EFFECT_DEFAULT_FADE; - SEQ_time_update_sequence(scene, seq); - - if (seq->type == SEQ_TYPE_COLOR) { - SolidColorVars *colvars = (SolidColorVars *)seq->effectdata; - RNA_float_get_array(op->ptr, "color", colvars->col); - seq->blend_mode = SEQ_TYPE_CROSS; - } - else if (seq->type == SEQ_TYPE_ADJUSTMENT) { - seq->blend_mode = SEQ_TYPE_CROSS; - } - else if (seq->type == SEQ_TYPE_TEXT) { - seq->blend_mode = SEQ_TYPE_ALPHAOVER; - } - else if (SEQ_effect_get_num_inputs(seq->type) == 1) { - seq->blend_mode = seq1->blend_mode; - } + load_data.effect.seq1 = seq1; + load_data.effect.seq2 = seq2; + load_data.effect.seq3 = seq3; /* Set channel. If unset, use lowest free one above strips. */ if (!RNA_struct_property_is_set(op->ptr, "channel")) { - if (seq->seq1) { - int chan = max_iii(seq->seq1 ? seq->seq1->machine : 0, - seq->seq2 ? seq->seq2->machine : 0, - seq->seq3 ? seq->seq3->machine : 0); + if (seq1 != NULL) { + int chan = max_iii( + seq1 ? seq1->machine : 0, seq2 ? seq2->machine : 0, seq3 ? seq3->machine : 0); if (chan < MAXSEQ) { - seq->machine = chan; + load_data.channel = chan; } } } - sequencer_add_apply_replace_sel(C, op, seq); - sequencer_add_apply_overlap(C, op, seq); + Sequence *seq = SEQ_add_effect_strip(scene, ed->seqbasep, &load_data); + seq_load_apply_generic_options(C, op, seq); - SEQ_relations_update_changed_seq_and_deps(scene, seq, 1, 1); /* Runs SEQ_time_update_sequence. */ - SEQ_sort(scene); + if (seq->type == SEQ_TYPE_COLOR) { + SolidColorVars *colvars = (SolidColorVars *)seq->effectdata; + RNA_float_get_array(op->ptr, "color", colvars->col); + } - SEQ_relations_invalidate_cache_composite(scene, seq); DEG_id_tag_update(&scene->id, ID_RECALC_SEQUENCER_STRIPS); WM_event_add_notifier(C, NC_SCENE | ND_SEQUENCER, scene); diff --git a/source/blender/editors/space_sequencer/sequencer_draw.c b/source/blender/editors/space_sequencer/sequencer_draw.c index b9fb577eb43..9828368ccf7 100644 --- a/source/blender/editors/space_sequencer/sequencer_draw.c +++ b/source/blender/editors/space_sequencer/sequencer_draw.c @@ -66,6 +66,7 @@ #include "ED_sequencer.h" #include "ED_space_api.h" #include "ED_time_scrub_ui.h" +#include "ED_util.h" #include "BIF_glutil.h" diff --git a/source/blender/editors/space_sequencer/sequencer_edit.c b/source/blender/editors/space_sequencer/sequencer_edit.c index 608e220c582..78d263dffad 100644 --- a/source/blender/editors/space_sequencer/sequencer_edit.c +++ b/source/blender/editors/space_sequencer/sequencer_edit.c @@ -1870,93 +1870,28 @@ void SEQUENCER_OT_images_separate(wmOperatorType *ot) /** \name Toggle Meta Strip Operator * \{ */ -void recurs_sel_seq(Sequence *seqm) -{ - Sequence *seq; - - seq = seqm->seqbase.first; - while (seq) { - - if (seqm->flag & (SEQ_LEFTSEL + SEQ_RIGHTSEL)) { - seq->flag &= ~SEQ_ALLSEL; - } - else if (seqm->flag & SELECT) { - seq->flag |= SELECT; - } - else { - seq->flag &= ~SEQ_ALLSEL; - } - - if (seq->seqbase.first) { - recurs_sel_seq(seq); - } - - seq = seq->next; - } -} - static int sequencer_meta_toggle_exec(bContext *C, wmOperator *UNUSED(op)) { Scene *scene = CTX_data_scene(C); Editing *ed = SEQ_editing_get(scene, false); - Sequence *last_seq = SEQ_select_active_get(scene); - MetaStack *ms; + Sequence *active_seq = SEQ_select_active_get(scene); - if (last_seq && last_seq->type == SEQ_TYPE_META && last_seq->flag & SELECT) { + if (active_seq && active_seq->type == SEQ_TYPE_META && active_seq->flag & SELECT) { /* Enter metastrip. */ - ms = MEM_mallocN(sizeof(MetaStack), "metastack"); - BLI_addtail(&ed->metastack, ms); - ms->parseq = last_seq; - ms->oldbasep = ed->seqbasep; - copy_v2_v2_int(ms->disp_range, &ms->parseq->startdisp); - - ed->seqbasep = &last_seq->seqbase; - + SEQ_meta_stack_alloc(ed, active_seq); + SEQ_seqbase_active_set(ed, &active_seq->seqbase); SEQ_select_active_set(scene, NULL); } else { /* Exit metastrip if possible. */ - - Sequence *seq; - if (BLI_listbase_is_empty(&ed->metastack)) { return OPERATOR_CANCELLED; } - ms = ed->metastack.last; - BLI_remlink(&ed->metastack, ms); - - ed->seqbasep = ms->oldbasep; - - /* For old files, update from meta. */ - if (ms->disp_range[0] == ms->disp_range[1]) { - copy_v2_v2_int(ms->disp_range, &ms->parseq->startdisp); - } - - /* Recalc all: the meta can have effects connected to it. */ - for (seq = ed->seqbasep->first; seq; seq = seq->next) { - SEQ_time_update_sequence(scene, seq); - } - - /* 2.73+, keeping endpoints is important! - * Moving them around means you can't usefully use metas in a complex edit. */ -#if 1 - SEQ_transform_set_left_handle_frame(ms->parseq, ms->disp_range[0]); - SEQ_transform_set_right_handle_frame(ms->parseq, ms->disp_range[1]); - SEQ_transform_fix_single_image_seq_offsets(ms->parseq); - SEQ_time_update_sequence(scene, ms->parseq); -#else - if (SEQ_transform_test_overlap(ed->seqbasep, ms->parseq)) { - SEQ_transform_seqbase_shuffle(ed->seqbasep, ms->parseq, scene); - } -#endif - + MetaStack *ms = SEQ_meta_stack_active_get(ed); + SEQ_seqbase_active_set(ed, ms->oldbasep); SEQ_select_active_set(scene, ms->parseq); - - ms->parseq->flag |= SELECT; - recurs_sel_seq(ms->parseq); - - MEM_freeN(ms); + SEQ_meta_stack_free(ed, ms); } DEG_id_tag_update(&scene->id, ID_RECALC_SEQUENCER_STRIPS); @@ -1990,48 +1925,44 @@ static int sequencer_meta_make_exec(bContext *C, wmOperator *op) { Scene *scene = CTX_data_scene(C); Editing *ed = SEQ_editing_get(scene, false); + Sequence *active_seq = SEQ_select_active_get(scene); + ListBase *active_seqbase = SEQ_active_seqbase_get(ed); - Sequence *seq, *seqm, *next, *last_seq = SEQ_select_active_get(scene); - int channel_max = 1; - - if (SEQ_transform_seqbase_isolated_sel_check(ed->seqbasep) == false) { + if (SEQ_transform_seqbase_isolated_sel_check(active_seqbase) == false) { BKE_report(op->reports, RPT_ERROR, "Please select all related strips"); return OPERATOR_CANCELLED; } SEQ_prefetch_stop(scene); - /* Remove all selected from main list, and put in meta. */ - - seqm = SEQ_sequence_alloc(ed->seqbasep, 1, 1, SEQ_TYPE_META); /* Channel number set later. */ - strcpy(seqm->name + 2, "MetaStrip"); - seqm->flag = SELECT; + int channel_max = 1, meta_start_frame = MAXFRAME, meta_end_frame = MINFRAME; + Sequence *seqm = SEQ_sequence_alloc(active_seqbase, 1, 1, SEQ_TYPE_META); - seq = ed->seqbasep->first; - while (seq) { - next = seq->next; - if (seq != seqm && (seq->flag & SELECT)) { - SEQ_relations_invalidate_cache_composite(scene, seq); - channel_max = max_ii(seq->machine, channel_max); - /* Sequence is moved within the same edit, no need to re-generate the UUID. */ - BLI_remlink(ed->seqbasep, seq); + /* Remove all selected from main list, and put in meta. + * Sequence is moved within the same edit, no need to re-generate the UUID. */ + LISTBASE_FOREACH_MUTABLE (Sequence *, seq, active_seqbase) { + if (seq != seqm && seq->flag & SELECT) { + BLI_remlink(active_seqbase, seq); BLI_addtail(&seqm->seqbase, seq); + SEQ_relations_invalidate_cache_preprocessed(scene, seq); + channel_max = max_ii(seq->machine, channel_max); + meta_start_frame = min_ii(seq->startdisp, meta_start_frame); + meta_end_frame = max_ii(seq->enddisp, meta_end_frame); } - seq = next; } - seqm->machine = last_seq ? last_seq->machine : channel_max; - SEQ_time_update_sequence(scene, seqm); + seqm->machine = active_seq ? active_seq->machine : channel_max; + strcpy(seqm->name + 2, "MetaStrip"); + SEQ_sequence_base_unique_name_recursive(&ed->seqbase, seqm); + seqm->start = meta_start_frame; + seqm->len = meta_end_frame - meta_start_frame; + SEQ_time_update_sequence(scene, seqm); SEQ_select_active_set(scene, seqm); - - if (SEQ_transform_test_overlap(ed->seqbasep, seqm)) { - SEQ_transform_seqbase_shuffle(ed->seqbasep, seqm, scene); + if (SEQ_transform_test_overlap(active_seqbase, seqm)) { + SEQ_transform_seqbase_shuffle(active_seqbase, seqm, scene); } DEG_id_tag_update(&scene->id, ID_RECALC_SEQUENCER_STRIPS); - - SEQ_sequence_base_unique_name_recursive(&scene->ed->seqbase, seqm); - SEQ_relations_invalidate_cache_composite(scene, seqm); WM_event_add_notifier(C, NC_SCENE | ND_SEQUENCER, scene); return OPERATOR_FINISHED; @@ -2058,95 +1989,43 @@ void SEQUENCER_OT_meta_make(wmOperatorType *ot) /** \name UnMeta Strip Operator * \{ */ -static int seq_depends_on_meta(Sequence *seq, Sequence *seqm) -{ - if (seq == seqm) { - return 1; - } - if (seq->seq1 && seq_depends_on_meta(seq->seq1, seqm)) { - return 1; - } - if (seq->seq2 && seq_depends_on_meta(seq->seq2, seqm)) { - return 1; - } - if (seq->seq3 && seq_depends_on_meta(seq->seq3, seqm)) { - return 1; - } - return 0; -} - -static void recurs_del_seq_flag(Scene *scene, ListBase *lb, short flag, short deleteall) -{ - Sequence *seq, *seqn; - Sequence *last_seq = SEQ_select_active_get(scene); - - seq = lb->first; - while (seq) { - seqn = seq->next; - if ((seq->flag & flag) || deleteall) { - BLI_remlink(lb, seq); - if (seq == last_seq) { - SEQ_select_active_set(scene, NULL); - } - if (seq->type == SEQ_TYPE_META) { - recurs_del_seq_flag(scene, &seq->seqbase, flag, 1); - } - SEQ_sequence_free(scene, seq, true); - } - seq = seqn; - } -} - static int sequencer_meta_separate_exec(bContext *C, wmOperator *UNUSED(op)) { Scene *scene = CTX_data_scene(C); Editing *ed = SEQ_editing_get(scene, false); + Sequence *active_seq = SEQ_select_active_get(scene); - Sequence *seq, *last_seq = SEQ_select_active_get(scene); /* last_seq checks (ed == NULL) */ - - if (last_seq == NULL || last_seq->type != SEQ_TYPE_META) { + if (active_seq == NULL || active_seq->type != SEQ_TYPE_META) { return OPERATOR_CANCELLED; } SEQ_prefetch_stop(scene); - for (seq = last_seq->seqbase.first; seq != NULL; seq = seq->next) { - SEQ_relations_invalidate_cache_composite(scene, seq); + LISTBASE_FOREACH (Sequence *, seq, &active_seq->seqbase) { + SEQ_relations_invalidate_cache_preprocessed(scene, seq); } - /* This moves strips from meta to parent, sating within same edit and no new strips are - * allocated. If the UUID was unique already (as it should) it will stay unique. - * No need to re-generate the UUIDs. */ - BLI_movelisttolist(ed->seqbasep, &last_seq->seqbase); + /* Remove all selected from meta, and put in main list. + * Sequence is moved within the same edit, no need to re-generate the UUID. */ + BLI_movelisttolist(ed->seqbasep, &active_seq->seqbase); + BLI_listbase_clear(&active_seq->seqbase); - BLI_listbase_clear(&last_seq->seqbase); + ListBase *active_seqbase = SEQ_active_seqbase_get(ed); + SEQ_edit_flag_for_removal(scene, active_seqbase, active_seq); + SEQ_edit_remove_flagged_sequences(scene, active_seqbase); - BLI_remlink(ed->seqbasep, last_seq); - SEQ_sequence_free(scene, last_seq, true); - - /* Empty meta strip, delete all effects depending on it. */ - for (seq = ed->seqbasep->first; seq; seq = seq->next) { - if ((seq->type & SEQ_TYPE_EFFECT) && seq_depends_on_meta(seq, last_seq)) { - seq->flag |= SEQ_FLAG_DELETE; - } - } - - recurs_del_seq_flag(scene, ed->seqbasep, SEQ_FLAG_DELETE, 0); - - /* Test for effects and overlap - * don't use SEQ_CURRENT_BEGIN since that would be recursive. */ - for (seq = ed->seqbasep->first; seq; seq = seq->next) { + /* Test for effects and overlap. */ + LISTBASE_FOREACH (Sequence *, seq, active_seqbase) { if (seq->flag & SELECT) { seq->flag &= ~SEQ_OVERLAP; - if (SEQ_transform_test_overlap(ed->seqbasep, seq)) { - SEQ_transform_seqbase_shuffle(ed->seqbasep, seq, scene); + if (SEQ_transform_test_overlap(active_seqbase, seq)) { + SEQ_transform_seqbase_shuffle(active_seqbase, seq, scene); } } } SEQ_sort(scene); DEG_id_tag_update(&scene->id, ID_RECALC_SEQUENCER_STRIPS); - WM_event_add_notifier(C, NC_SCENE | ND_SEQUENCER, scene); return OPERATOR_FINISHED; diff --git a/source/blender/editors/space_sequencer/sequencer_select.c b/source/blender/editors/space_sequencer/sequencer_select.c index ffcb3d35d5a..5f0a18fbd0b 100644 --- a/source/blender/editors/space_sequencer/sequencer_select.c +++ b/source/blender/editors/space_sequencer/sequencer_select.c @@ -360,6 +360,31 @@ static void select_neighbor_from_last(Scene *scene, int lr) } #endif +void recurs_sel_seq(Sequence *seq_meta) +{ + Sequence *seq; + + seq = seq_meta->seqbase.first; + while (seq) { + + if (seq_meta->flag & (SEQ_LEFTSEL + SEQ_RIGHTSEL)) { + seq->flag &= ~SEQ_ALLSEL; + } + else if (seq_meta->flag & SELECT) { + seq->flag |= SELECT; + } + else { + seq->flag &= ~SEQ_ALLSEL; + } + + if (seq->seqbase.first) { + recurs_sel_seq(seq); + } + + seq = seq->next; + } +} + /** \} */ /* -------------------------------------------------------------------- */ diff --git a/source/blender/editors/transform/transform_constraints.c b/source/blender/editors/transform/transform_constraints.c index 1f589a830fc..93d5d41e121 100644 --- a/source/blender/editors/transform/transform_constraints.c +++ b/source/blender/editors/transform/transform_constraints.c @@ -572,7 +572,7 @@ static void constraints_rotation_impl(TransInfo *t, break; } /* don't flip axis if asked to or if num input */ - if (r_angle && (mode & CON_NOFLIP) == 0 && hasNumInput(&t->num) == 0) { + if (r_angle && !((mode & CON_NOFLIP) || hasNumInput(&t->num) || (t->flag & T_INPUT_IS_VALUES_FINAL))) { float view_vector[3]; view_vector_calc(t, t->center_global, view_vector); if (dot_v3v3(r_vec, view_vector) > 0.0f) { diff --git a/source/blender/editors/transform/transform_convert_sequencer.c b/source/blender/editors/transform/transform_convert_sequencer.c index 4ab52b78002..30418471d6d 100644 --- a/source/blender/editors/transform/transform_convert_sequencer.c +++ b/source/blender/editors/transform/transform_convert_sequencer.c @@ -90,35 +90,17 @@ static void SeqTransInfo(TransInfo *t, Sequence *seq, int *r_recursive, int *r_c Scene *scene = t->scene; int cfra = CFRA; - int left = SEQ_transform_get_left_handle_frame(seq, true); - int right = SEQ_transform_get_right_handle_frame(seq, true); + int left = SEQ_transform_get_left_handle_frame(seq, false); + int right = SEQ_transform_get_right_handle_frame(seq, false); if (seq->depth == 0 && ((seq->flag & SELECT) == 0 || (seq->flag & SEQ_LOCK))) { *r_recursive = false; *r_count = 0; *r_flag = 0; } - else if (seq->type == SEQ_TYPE_META) { - - /* for meta's we only ever need to extend their children, no matter what depth - * just check the meta's are in the bounds */ - if (t->frame_side == 'R' && right <= cfra) { - *r_recursive = false; - } - else if (t->frame_side == 'L' && left >= cfra) { - *r_recursive = false; - } - else { - *r_recursive = true; - } - - *r_count = 1; - *r_flag = (seq->flag | SELECT) & ~(SEQ_LEFTSEL | SEQ_RIGHTSEL); - } else { - - *r_recursive = false; /* not a meta, so no thinking here */ - *r_count = 1; /* unless its set to 0, extend will never set 2 handles at once */ + *r_recursive = false; + *r_count = 1; /* unless its set to 0, extend will never set 2 handles at once */ *r_flag = (seq->flag | SELECT) & ~(SEQ_LEFTSEL | SEQ_RIGHTSEL); if (t->frame_side == 'R') { @@ -183,26 +165,9 @@ static void SeqTransInfo(TransInfo *t, Sequence *seq, int *r_recursive, int *r_c else { /* Nested, different rules apply */ -#ifdef SEQ_TX_NESTED_METAS *r_flag = (seq->flag | SELECT) & ~(SEQ_LEFTSEL | SEQ_RIGHTSEL); *r_count = 1; /* ignore the selection for nested */ *r_recursive = (seq->type == SEQ_TYPE_META); -#else - if (seq->type == SEQ_TYPE_META) { - /* Meta's can only directly be moved between channels since they - * don't have their start and length set directly (children affect that) - * since this Meta is nested we don't need any of its data in fact. - * SEQ_time_update_sequence() will update its settings when run on the top-level meta. */ - *r_flag = 0; - *r_count = 0; - *r_recursive = true; - } - else { - *r_flag = (seq->flag | SELECT) & ~(SEQ_LEFTSEL | SEQ_RIGHTSEL); - *r_count = 1; /* ignore the selection for nested */ - *r_recursive = false; - } -#endif } } } @@ -645,8 +610,6 @@ void createTransSeqData(TransInfo *t) /* commented _only_ because the meta may have animation data which * needs moving too T28158. */ -#define SEQ_TX_NESTED_METAS - BLI_INLINE void trans_update_seq(Scene *sce, Sequence *seq, int old_start, int sel_flag) { if (seq->depth == 0) { @@ -693,17 +656,10 @@ static void flushTransSeq(TransInfo *t) switch (tdsq->sel_flag) { case SELECT: -#ifdef SEQ_TX_NESTED_METAS if ((seq->depth != 0 || SEQ_transform_sequence_can_be_translated(seq))) { /* for meta's, their children move */ seq->start = new_frame - tdsq->start_offset; } -#else - if (seq->type != SEQ_TYPE_META && (seq->depth != 0 || seq_tx_test(seq))) { - /* for meta's, their children move */ - seq->start = new_frame - tdsq->start_offset; - } -#endif if (seq->depth == 0) { seq->machine = round_fl_to_int(td2d->loc[1]); CLAMP(seq->machine, 1, MAXSEQ); diff --git a/source/blender/editors/transform/transform_generics.c b/source/blender/editors/transform/transform_generics.c index 6fca49495e9..e43a3ff3635 100644 --- a/source/blender/editors/transform/transform_generics.c +++ b/source/blender/editors/transform/transform_generics.c @@ -381,12 +381,10 @@ void initTransInfo(bContext *C, TransInfo *t, wmOperator *op, const wmEvent *eve if (op && (prop = RNA_struct_find_property(op->ptr, "constraint_axis"))) { bool constraint_axis[3] = {false, false, false}; - if (t->flag & T_INPUT_IS_VALUES_FINAL) { - if (t_values_set_is_array) { - /* For operators whose `t->values` is array, set constraint so that the - * orientation is more intuitive in the Redo Panel. */ - constraint_axis[0] = constraint_axis[1] = constraint_axis[2] = true; - } + if (t_values_set_is_array && t->flag & T_INPUT_IS_VALUES_FINAL) { + /* For operators whose `t->values` is array (as Move and Scale), set constraint so that the + * orientation is more intuitive in the Redo Panel. */ + constraint_axis[0] = constraint_axis[1] = constraint_axis[2] = true; } else if (RNA_property_is_set(op->ptr, prop)) { RNA_property_boolean_get_array(op->ptr, prop, constraint_axis); diff --git a/source/blender/editors/transform/transform_mode.c b/source/blender/editors/transform/transform_mode.c index 9e6e4d8807e..d14f693da9c 100644 --- a/source/blender/editors/transform/transform_mode.c +++ b/source/blender/editors/transform/transform_mode.c @@ -554,15 +554,6 @@ void headerRotation(TransInfo *t, char str[UI_MAX_DRAW_STR], float final) } } -void postInputRotation(TransInfo *t, float values[3]) -{ - float axis_final[3]; - copy_v3_v3(axis_final, t->spacemtx[t->orient_axis]); - if ((t->con.mode & CON_APPLY) && t->con.applyRot) { - t->con.applyRot(t, NULL, NULL, axis_final, values); - } -} - /** * Applies values of rotation to `td->loc` and `td->ext->quat` * based on a rotation matrix (mat) and a pivot (center). diff --git a/source/blender/editors/transform/transform_mode.h b/source/blender/editors/transform/transform_mode.h index 7a05506e12c..6d7a0b528ae 100644 --- a/source/blender/editors/transform/transform_mode.h +++ b/source/blender/editors/transform/transform_mode.h @@ -47,7 +47,6 @@ void protectedTransBits(short protectflag, float vec[3]); void protectedSizeBits(short protectflag, float size[3]); void constraintTransLim(TransInfo *t, TransData *td); void constraintSizeLim(TransInfo *t, TransData *td); -void postInputRotation(TransInfo *t, float values[3]); void headerRotation(TransInfo *t, char *str, float final); void ElementRotation_ex(TransInfo *t, TransDataContainer *tc, diff --git a/source/blender/editors/transform/transform_mode_bend.c b/source/blender/editors/transform/transform_mode_bend.c index adf3a0346a0..038f7d48c66 100644 --- a/source/blender/editors/transform/transform_mode_bend.c +++ b/source/blender/editors/transform/transform_mode_bend.c @@ -254,7 +254,6 @@ void initBend(TransInfo *t) t->transform = Bend; t->handleEvent = handleEventBend; - setInputPostFct(&t->mouse, postInputRotation); initMouseInputMode(t, &t->mouse, INPUT_ANGLE_SPRING); t->idx_max = 1; diff --git a/source/blender/editors/transform/transform_mode_edge_rotate_normal.c b/source/blender/editors/transform/transform_mode_edge_rotate_normal.c index 32f0d4bd365..c78115561b2 100644 --- a/source/blender/editors/transform/transform_mode_edge_rotate_normal.c +++ b/source/blender/editors/transform/transform_mode_edge_rotate_normal.c @@ -127,7 +127,6 @@ void initNormalRotation(TransInfo *t) t->mode = TFM_NORMAL_ROTATION; t->transform = applyNormalRotation; - setInputPostFct(&t->mouse, postInputRotation); initMouseInputMode(t, &t->mouse, INPUT_ANGLE); t->idx_max = 0; diff --git a/source/blender/editors/transform/transform_mode_rotate.c b/source/blender/editors/transform/transform_mode_rotate.c index fa02e5382a7..8d8594d5775 100644 --- a/source/blender/editors/transform/transform_mode_rotate.c +++ b/source/blender/editors/transform/transform_mode_rotate.c @@ -197,7 +197,7 @@ static void applyRotation(TransInfo *t, const int UNUSED(mval[2])) float final = t->values[0]; if ((t->con.mode & CON_APPLY) && t->con.applyRot) { - t->con.applyRot(t, NULL, NULL, axis_final, NULL); + t->con.applyRot(t, NULL, NULL, axis_final, &final); } else { negate_v3_v3(axis_final, t->spacemtx[t->orient_axis]); @@ -234,7 +234,6 @@ void initRotation(TransInfo *t) t->tsnap.applySnap = ApplySnapRotation; t->tsnap.distance = RotationBetween; - setInputPostFct(&t->mouse, postInputRotation); initMouseInputMode(t, &t->mouse, INPUT_ANGLE); t->idx_max = 0; diff --git a/source/blender/editors/undo/memfile_undo.c b/source/blender/editors/undo/memfile_undo.c index 4fd8c180a4b..9189adaf4d1 100644 --- a/source/blender/editors/undo/memfile_undo.c +++ b/source/blender/editors/undo/memfile_undo.c @@ -152,7 +152,7 @@ static void memfile_undosys_step_decode(struct bContext *C, bool use_old_bmain_data = true; - if (USER_EXPERIMENTAL_TEST(&U, use_undo_legacy)) { + if (USER_EXPERIMENTAL_TEST(&U, use_undo_legacy) || !(U.uiflag & USER_GLOBALUNDO)) { use_old_bmain_data = false; } else if (undo_direction == STEP_REDO) { diff --git a/source/blender/editors/util/CMakeLists.txt b/source/blender/editors/util/CMakeLists.txt index 38655b8490e..7d7d10004a3 100644 --- a/source/blender/editors/util/CMakeLists.txt +++ b/source/blender/editors/util/CMakeLists.txt @@ -21,6 +21,7 @@ set(INC ../../blenkernel ../../blenlib ../../blentranslation + ../../blenfont ../../bmesh ../../depsgraph ../../gpu @@ -36,6 +37,7 @@ set(INC set(SRC + ed_draw.c ed_transverts.c ed_util.c ed_util_imbuf.c diff --git a/source/blender/editors/util/ed_draw.c b/source/blender/editors/util/ed_draw.c new file mode 100644 index 00000000000..94adba36664 --- /dev/null +++ b/source/blender/editors/util/ed_draw.c @@ -0,0 +1,385 @@ +/* + * 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 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * 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) 2008 Blender Foundation. + * All rights reserved. + */ + +/** \file + * \ingroup edutil + */ + +#include <math.h> +#include <stdlib.h> +#include <string.h> + +#include "MEM_guardedalloc.h" + +#include "BLI_listbase.h" +#include "BLI_path_util.h" +#include "BLI_rect.h" +#include "BLI_string.h" +#include "BLI_utildefines.h" + +#include "BKE_context.h" +#include "BKE_image.h" + +#include "BLF_api.h" + +#include "IMB_imbuf_types.h" +#include "IMB_metadata.h" + +#include "ED_screen.h" +#include "ED_space_api.h" +#include "ED_util.h" + +#include "GPU_immediate.h" +#include "GPU_matrix.h" +#include "GPU_state.h" + +#include "UI_interface.h" +#include "UI_resources.h" + +#include "RNA_access.h" +#include "WM_api.h" +#include "WM_types.h" + +/** + * Callback that draws a line between the mouse and a position given as the initial argument. + */ +void ED_region_draw_mouse_line_cb(const bContext *C, ARegion *region, void *arg_info) +{ + wmWindow *win = CTX_wm_window(C); + const float *mval_src = (float *)arg_info; + const float mval_dst[2] = { + win->eventstate->x - region->winrct.xmin, + win->eventstate->y - region->winrct.ymin, + }; + + const uint shdr_pos = GPU_vertformat_attr_add( + immVertexFormat(), "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT); + + GPU_line_width(1.0f); + + immBindBuiltinProgram(GPU_SHADER_2D_LINE_DASHED_UNIFORM_COLOR); + + float viewport_size[4]; + GPU_viewport_size_get_f(viewport_size); + immUniform2f("viewport_size", viewport_size[2] / UI_DPI_FAC, viewport_size[3] / UI_DPI_FAC); + + immUniform1i("colors_len", 0); /* "simple" mode */ + immUniformThemeColor3(TH_VIEW_OVERLAY); + immUniform1f("dash_width", 6.0f); + immUniform1f("dash_factor", 0.5f); + + immBegin(GPU_PRIM_LINES, 2); + immVertex2fv(shdr_pos, mval_src); + immVertex2fv(shdr_pos, mval_dst); + immEnd(); + + immUnbindProgram(); +} + +#define MAX_METADATA_STR 1024 + +static const char *meta_data_list[] = { + "File", + "Strip", + "Date", + "RenderTime", + "Note", + "Marker", + "Time", + "Frame", + "Camera", + "Scene", +}; + +BLI_INLINE bool metadata_is_valid(ImBuf *ibuf, char *r_str, short index, int offset) +{ + return (IMB_metadata_get_field( + ibuf->metadata, meta_data_list[index], r_str + offset, MAX_METADATA_STR - offset) && + r_str[0]); +} + +BLI_INLINE bool metadata_is_custom_drawable(const char *field) +{ + /* Metadata field stored by Blender for multilayer EXR images. Is rather + * useless to be viewed all the time. Can still be seen in the Metadata + * panel. */ + if (STREQ(field, "BlenderMultiChannel")) { + return false; + } + /* Is almost always has value "scanlineimage", also useless to be seen + * all the time. */ + if (STREQ(field, "type")) { + return false; + } + return !BKE_stamp_is_known_field(field); +} + +typedef struct MetadataCustomDrawContext { + int fontid; + int xmin, ymin; + int vertical_offset; + int current_y; +} MetadataCustomDrawContext; + +static void metadata_custom_draw_fields(const char *field, const char *value, void *ctx_v) +{ + if (!metadata_is_custom_drawable(field)) { + return; + } + MetadataCustomDrawContext *ctx = (MetadataCustomDrawContext *)ctx_v; + char temp_str[MAX_METADATA_STR]; + BLI_snprintf(temp_str, MAX_METADATA_STR, "%s: %s", field, value); + BLF_position(ctx->fontid, ctx->xmin, ctx->ymin + ctx->current_y, 0.0f); + BLF_draw(ctx->fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX); + ctx->current_y += ctx->vertical_offset; +} + +static void metadata_draw_imbuf(ImBuf *ibuf, const rctf *rect, int fontid, const bool is_top) +{ + char temp_str[MAX_METADATA_STR]; + int ofs_y = 0; + const float height = BLF_height_max(fontid); + const float margin = height / 8; + const float vertical_offset = (height + margin); + + /* values taking margins into account */ + const float descender = BLF_descender(fontid); + const float xmin = (rect->xmin + margin); + const float xmax = (rect->xmax - margin); + const float ymin = (rect->ymin + margin) - descender; + const float ymax = (rect->ymax - margin) - descender; + + if (is_top) { + for (int i = 0; i < 4; i++) { + /* first line */ + if (i == 0) { + bool do_newline = false; + int len = BLI_snprintf_rlen(temp_str, MAX_METADATA_STR, "%s: ", meta_data_list[0]); + if (metadata_is_valid(ibuf, temp_str, 0, len)) { + BLF_position(fontid, xmin, ymax - vertical_offset, 0.0f); + BLF_draw(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX); + do_newline = true; + } + + len = BLI_snprintf_rlen(temp_str, MAX_METADATA_STR, "%s: ", meta_data_list[1]); + if (metadata_is_valid(ibuf, temp_str, 1, len)) { + int line_width = BLF_width(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX); + BLF_position(fontid, xmax - line_width, ymax - vertical_offset, 0.0f); + BLF_draw(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX); + do_newline = true; + } + + if (do_newline) { + ofs_y += vertical_offset; + } + } /* Strip */ + else if (i == 1 || i == 2) { + int len = BLI_snprintf_rlen(temp_str, MAX_METADATA_STR, "%s: ", meta_data_list[i + 1]); + if (metadata_is_valid(ibuf, temp_str, i + 1, len)) { + BLF_position(fontid, xmin, ymax - vertical_offset - ofs_y, 0.0f); + BLF_draw(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX); + ofs_y += vertical_offset; + } + } /* Note (wrapped) */ + else if (i == 3) { + int len = BLI_snprintf_rlen(temp_str, MAX_METADATA_STR, "%s: ", meta_data_list[i + 1]); + if (metadata_is_valid(ibuf, temp_str, i + 1, len)) { + struct ResultBLF info; + BLF_enable(fontid, BLF_WORD_WRAP); + BLF_wordwrap(fontid, ibuf->x - (margin * 2)); + BLF_position(fontid, xmin, ymax - vertical_offset - ofs_y, 0.0f); + BLF_draw_ex(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX, &info); + BLF_wordwrap(fontid, 0); + BLF_disable(fontid, BLF_WORD_WRAP); + ofs_y += vertical_offset * info.lines; + } + } + else { + int len = BLI_snprintf_rlen(temp_str, MAX_METADATA_STR, "%s: ", meta_data_list[i + 1]); + if (metadata_is_valid(ibuf, temp_str, i + 1, len)) { + int line_width = BLF_width(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX); + BLF_position(fontid, xmax - line_width, ymax - vertical_offset - ofs_y, 0.0f); + BLF_draw(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX); + ofs_y += vertical_offset; + } + } + } + } + else { + MetadataCustomDrawContext ctx; + ctx.fontid = fontid; + ctx.xmin = xmin; + ctx.ymin = ymin; + ctx.current_y = ofs_y; + ctx.vertical_offset = vertical_offset; + IMB_metadata_foreach(ibuf, metadata_custom_draw_fields, &ctx); + int ofs_x = 0; + ofs_y = ctx.current_y; + for (int i = 5; i < 10; i++) { + int len = BLI_snprintf_rlen(temp_str, MAX_METADATA_STR, "%s: ", meta_data_list[i]); + if (metadata_is_valid(ibuf, temp_str, i, len)) { + BLF_position(fontid, xmin + ofs_x, ymin + ofs_y, 0.0f); + BLF_draw(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX); + + ofs_x += BLF_width(fontid, temp_str, BLF_DRAW_STR_DUMMY_MAX) + UI_UNIT_X; + } + } + } +} + +typedef struct MetadataCustomCountContext { + int count; +} MetadataCustomCountContext; + +static void metadata_custom_count_fields(const char *field, const char *UNUSED(value), void *ctx_v) +{ + if (!metadata_is_custom_drawable(field)) { + return; + } + MetadataCustomCountContext *ctx = (MetadataCustomCountContext *)ctx_v; + ctx->count++; +} + +static float metadata_box_height_get(ImBuf *ibuf, int fontid, const bool is_top) +{ + const float height = BLF_height_max(fontid); + const float margin = (height / 8); + char str[MAX_METADATA_STR] = ""; + short count = 0; + + if (is_top) { + if (metadata_is_valid(ibuf, str, 0, 0) || metadata_is_valid(ibuf, str, 1, 0)) { + count++; + } + for (int i = 2; i < 5; i++) { + if (metadata_is_valid(ibuf, str, i, 0)) { + if (i == 4) { + struct { + struct ResultBLF info; + rctf rect; + } wrap; + + BLF_enable(fontid, BLF_WORD_WRAP); + BLF_wordwrap(fontid, ibuf->x - (margin * 2)); + BLF_boundbox_ex(fontid, str, sizeof(str), &wrap.rect, &wrap.info); + BLF_wordwrap(fontid, 0); + BLF_disable(fontid, BLF_WORD_WRAP); + + count += wrap.info.lines; + } + else { + count++; + } + } + } + } + else { + for (int i = 5; i < 10; i++) { + if (metadata_is_valid(ibuf, str, i, 0)) { + count = 1; + break; + } + } + MetadataCustomCountContext ctx; + ctx.count = 0; + IMB_metadata_foreach(ibuf, metadata_custom_count_fields, &ctx); + count += ctx.count; + } + + if (count) { + return (height + margin) * count; + } + + return 0; +} + +/* Should be kept in sync with BKE_image_stamp_buf */ +void ED_region_image_metadata_draw( + int x, int y, ImBuf *ibuf, const rctf *frame, float zoomx, float zoomy) +{ + const uiStyle *style = UI_style_get_dpi(); + + if (!ibuf->metadata) { + return; + } + + /* find window pixel coordinates of origin */ + GPU_matrix_push(); + + /* offset and zoom using ogl */ + GPU_matrix_translate_2f(x, y); + GPU_matrix_scale_2f(zoomx, zoomy); + + BLF_size(blf_mono_font, style->widgetlabel.points * 1.5f * U.pixelsize, U.dpi); + + /* *** upper box*** */ + + /* get needed box height */ + float box_y = metadata_box_height_get(ibuf, blf_mono_font, true); + + if (box_y) { + /* set up rect */ + rctf rect; + BLI_rctf_init(&rect, frame->xmin, frame->xmax, frame->ymax, frame->ymax + box_y); + /* draw top box */ + GPUVertFormat *format = immVertexFormat(); + uint pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT); + immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR); + immUniformThemeColor(TH_METADATA_BG); + immRectf(pos, rect.xmin, rect.ymin, rect.xmax, rect.ymax); + immUnbindProgram(); + + BLF_clipping(blf_mono_font, rect.xmin, rect.ymin, rect.xmax, rect.ymax); + BLF_enable(blf_mono_font, BLF_CLIPPING); + + UI_FontThemeColor(blf_mono_font, TH_METADATA_TEXT); + metadata_draw_imbuf(ibuf, &rect, blf_mono_font, true); + + BLF_disable(blf_mono_font, BLF_CLIPPING); + } + + /* *** lower box*** */ + + box_y = metadata_box_height_get(ibuf, blf_mono_font, false); + + if (box_y) { + /* set up box rect */ + rctf rect; + BLI_rctf_init(&rect, frame->xmin, frame->xmax, frame->ymin - box_y, frame->ymin); + /* draw top box */ + GPUVertFormat *format = immVertexFormat(); + uint pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT); + immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR); + immUniformThemeColor(TH_METADATA_BG); + immRectf(pos, rect.xmin, rect.ymin, rect.xmax, rect.ymax); + immUnbindProgram(); + + BLF_clipping(blf_mono_font, rect.xmin, rect.ymin, rect.xmax, rect.ymax); + BLF_enable(blf_mono_font, BLF_CLIPPING); + + UI_FontThemeColor(blf_mono_font, TH_METADATA_TEXT); + metadata_draw_imbuf(ibuf, &rect, blf_mono_font, false); + + BLF_disable(blf_mono_font, BLF_CLIPPING); + } + + GPU_matrix_pop(); +} + +#undef MAX_METADATA_STR diff --git a/source/blender/editors/util/ed_util.c b/source/blender/editors/util/ed_util.c index 695db9ba246..9903711834a 100644 --- a/source/blender/editors/util/ed_util.c +++ b/source/blender/editors/util/ed_util.c @@ -434,44 +434,6 @@ void unpack_menu(bContext *C, UI_popup_menu_end(C, pup); } -/* ********************* generic callbacks for drawcall api *********************** */ - -/** - * Callback that draws a line between the mouse and a position given as the initial argument. - */ -void ED_region_draw_mouse_line_cb(const bContext *C, ARegion *region, void *arg_info) -{ - wmWindow *win = CTX_wm_window(C); - const float *mval_src = (float *)arg_info; - const float mval_dst[2] = { - win->eventstate->x - region->winrct.xmin, - win->eventstate->y - region->winrct.ymin, - }; - - const uint shdr_pos = GPU_vertformat_attr_add( - immVertexFormat(), "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT); - - GPU_line_width(1.0f); - - immBindBuiltinProgram(GPU_SHADER_2D_LINE_DASHED_UNIFORM_COLOR); - - float viewport_size[4]; - GPU_viewport_size_get_f(viewport_size); - immUniform2f("viewport_size", viewport_size[2] / UI_DPI_FAC, viewport_size[3] / UI_DPI_FAC); - - immUniform1i("colors_len", 0); /* "simple" mode */ - immUniformThemeColor3(TH_VIEW_OVERLAY); - immUniform1f("dash_width", 6.0f); - immUniform1f("dash_factor", 0.5f); - - immBegin(GPU_PRIM_LINES, 2); - immVertex2fv(shdr_pos, mval_src); - immVertex2fv(shdr_pos, mval_dst); - immEnd(); - - immUnbindProgram(); -} - /** * Use to free ID references within runtime data (stored outside of DNA) * |