From e12c08e8d170b7ca40f204a5b0423c23a9fbc2c1 Mon Sep 17 00:00:00 2001 From: Campbell Barton Date: Wed, 17 Apr 2019 06:17:24 +0200 Subject: ClangFormat: apply to source, most of intern Apply clang format as proposed in T53211. For details on usage and instructions for migrating branches without conflicts, see: https://wiki.blender.org/wiki/Tools/ClangFormat --- source/blender/editors/physics/CMakeLists.txt | 84 +- source/blender/editors/physics/dynamicpaint_ops.c | 746 +- source/blender/editors/physics/particle_boids.c | 422 +- source/blender/editors/physics/particle_edit.c | 8199 ++++++++++---------- .../blender/editors/physics/particle_edit_undo.c | 364 +- .../editors/physics/particle_edit_utildefines.h | 48 +- source/blender/editors/physics/particle_object.c | 1916 ++--- source/blender/editors/physics/physics_fluid.c | 1832 ++--- source/blender/editors/physics/physics_intern.h | 13 +- source/blender/editors/physics/physics_ops.c | 186 +- .../blender/editors/physics/physics_pointcache.c | 487 +- .../blender/editors/physics/rigidbody_constraint.c | 220 +- source/blender/editors/physics/rigidbody_object.c | 818 +- source/blender/editors/physics/rigidbody_world.c | 182 +- 14 files changed, 7952 insertions(+), 7565 deletions(-) (limited to 'source/blender/editors/physics') diff --git a/source/blender/editors/physics/CMakeLists.txt b/source/blender/editors/physics/CMakeLists.txt index 39a34ed7a47..3eb443320c3 100644 --- a/source/blender/editors/physics/CMakeLists.txt +++ b/source/blender/editors/physics/CMakeLists.txt @@ -16,70 +16,70 @@ # ***** END GPL LICENSE BLOCK ***** set(INC - ../include - ../../blenkernel - ../../blenlib - ../../blentranslation - ../../depsgraph - ../../gpu - ../../makesdna - ../../makesrna - ../../windowmanager - ../../../../intern/guardedalloc - ../../../../intern/glew-mx + ../include + ../../blenkernel + ../../blenlib + ../../blentranslation + ../../depsgraph + ../../gpu + ../../makesdna + ../../makesrna + ../../windowmanager + ../../../../intern/guardedalloc + ../../../../intern/glew-mx ) set(INC_SYS - ${GLEW_INCLUDE_PATH} + ${GLEW_INCLUDE_PATH} ) set(SRC - dynamicpaint_ops.c - particle_boids.c - particle_edit.c - particle_edit_undo.c - particle_object.c - physics_fluid.c - physics_ops.c - physics_pointcache.c - rigidbody_constraint.c - rigidbody_object.c - rigidbody_world.c + dynamicpaint_ops.c + particle_boids.c + particle_edit.c + particle_edit_undo.c + particle_object.c + physics_fluid.c + physics_ops.c + physics_pointcache.c + rigidbody_constraint.c + rigidbody_object.c + rigidbody_world.c - particle_edit_utildefines.h - physics_intern.h + particle_edit_utildefines.h + physics_intern.h ) set(LIB - bf_blenkernel - bf_blenlib + bf_blenkernel + bf_blenlib ) if(WITH_MOD_FLUID) - list(APPEND INC - ../../../../intern/elbeem/extern - ) - list(APPEND LIB - bf_intern_elbeem - ) - add_definitions(-DWITH_MOD_FLUID) + list(APPEND INC + ../../../../intern/elbeem/extern + ) + list(APPEND LIB + bf_intern_elbeem + ) + add_definitions(-DWITH_MOD_FLUID) endif() if(WITH_MOD_SMOKE) - list(APPEND LIB - bf_intern_smoke - ) + list(APPEND LIB + bf_intern_smoke + ) endif() if(WITH_INTERNATIONAL) - add_definitions(-DWITH_INTERNATIONAL) + add_definitions(-DWITH_INTERNATIONAL) endif() if(WITH_BULLET) - list(APPEND INC - ../../../../intern/rigidbody - ) - add_definitions(-DWITH_BULLET) + list(APPEND INC + ../../../../intern/rigidbody + ) + add_definitions(-DWITH_BULLET) endif() add_definitions(${GL_DEFINITIONS}) diff --git a/source/blender/editors/physics/dynamicpaint_ops.c b/source/blender/editors/physics/dynamicpaint_ops.c index a88d2089ea1..e0ea53b06ec 100644 --- a/source/blender/editors/physics/dynamicpaint_ops.c +++ b/source/blender/editors/physics/dynamicpaint_ops.c @@ -65,269 +65,280 @@ static int surface_slot_add_exec(bContext *C, wmOperator *UNUSED(op)) { - DynamicPaintModifierData *pmd = NULL; - Object *cObject = ED_object_context(C); - DynamicPaintCanvasSettings *canvas; - DynamicPaintSurface *surface; - - /* Make sure we're dealing with a canvas */ - pmd = (DynamicPaintModifierData *)modifiers_findByType(cObject, eModifierType_DynamicPaint); - if (!pmd || !pmd->canvas) - return OPERATOR_CANCELLED; - - canvas = pmd->canvas; - surface = dynamicPaint_createNewSurface(canvas, CTX_data_scene(C)); - - if (!surface) - return OPERATOR_CANCELLED; - - /* set preview for this surface only and set active */ - canvas->active_sur = 0; - for (surface = surface->prev; surface; surface = surface->prev) { - surface->flags &= ~MOD_DPAINT_PREVIEW; - canvas->active_sur++; - } - - return OPERATOR_FINISHED; + DynamicPaintModifierData *pmd = NULL; + Object *cObject = ED_object_context(C); + DynamicPaintCanvasSettings *canvas; + DynamicPaintSurface *surface; + + /* Make sure we're dealing with a canvas */ + pmd = (DynamicPaintModifierData *)modifiers_findByType(cObject, eModifierType_DynamicPaint); + if (!pmd || !pmd->canvas) + return OPERATOR_CANCELLED; + + canvas = pmd->canvas; + surface = dynamicPaint_createNewSurface(canvas, CTX_data_scene(C)); + + if (!surface) + return OPERATOR_CANCELLED; + + /* set preview for this surface only and set active */ + canvas->active_sur = 0; + for (surface = surface->prev; surface; surface = surface->prev) { + surface->flags &= ~MOD_DPAINT_PREVIEW; + canvas->active_sur++; + } + + return OPERATOR_FINISHED; } /* add surface slot */ void DPAINT_OT_surface_slot_add(wmOperatorType *ot) { - /* identifiers */ - ot->name = "Add Surface Slot"; - ot->idname = "DPAINT_OT_surface_slot_add"; - ot->description = "Add a new Dynamic Paint surface slot"; + /* identifiers */ + ot->name = "Add Surface Slot"; + ot->idname = "DPAINT_OT_surface_slot_add"; + ot->description = "Add a new Dynamic Paint surface slot"; - /* api callbacks */ - ot->exec = surface_slot_add_exec; - ot->poll = ED_operator_object_active_editable; + /* api callbacks */ + ot->exec = surface_slot_add_exec; + ot->poll = ED_operator_object_active_editable; - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } static int surface_slot_remove_exec(bContext *C, wmOperator *UNUSED(op)) { - DynamicPaintModifierData *pmd = NULL; - Object *obj_ctx = ED_object_context(C); - DynamicPaintCanvasSettings *canvas; - DynamicPaintSurface *surface; - int id = 0; - - /* Make sure we're dealing with a canvas */ - pmd = (DynamicPaintModifierData *)modifiers_findByType(obj_ctx, eModifierType_DynamicPaint); - if (!pmd || !pmd->canvas) return OPERATOR_CANCELLED; - - canvas = pmd->canvas; - surface = canvas->surfaces.first; - - /* find active surface and remove it */ - for (; surface; surface = surface->next) { - if (id == canvas->active_sur) { - canvas->active_sur -= 1; - dynamicPaint_freeSurface(pmd, surface); - break; - } - id++; - } - - dynamicPaint_resetPreview(canvas); - DEG_id_tag_update(&obj_ctx->id, ID_RECALC_GEOMETRY); - WM_event_add_notifier(C, NC_OBJECT | ND_MODIFIER, obj_ctx); - - return OPERATOR_FINISHED; + DynamicPaintModifierData *pmd = NULL; + Object *obj_ctx = ED_object_context(C); + DynamicPaintCanvasSettings *canvas; + DynamicPaintSurface *surface; + int id = 0; + + /* Make sure we're dealing with a canvas */ + pmd = (DynamicPaintModifierData *)modifiers_findByType(obj_ctx, eModifierType_DynamicPaint); + if (!pmd || !pmd->canvas) + return OPERATOR_CANCELLED; + + canvas = pmd->canvas; + surface = canvas->surfaces.first; + + /* find active surface and remove it */ + for (; surface; surface = surface->next) { + if (id == canvas->active_sur) { + canvas->active_sur -= 1; + dynamicPaint_freeSurface(pmd, surface); + break; + } + id++; + } + + dynamicPaint_resetPreview(canvas); + DEG_id_tag_update(&obj_ctx->id, ID_RECALC_GEOMETRY); + WM_event_add_notifier(C, NC_OBJECT | ND_MODIFIER, obj_ctx); + + return OPERATOR_FINISHED; } /* remove surface slot */ void DPAINT_OT_surface_slot_remove(wmOperatorType *ot) { - /* identifiers */ - ot->name = "Remove Surface Slot"; - ot->idname = "DPAINT_OT_surface_slot_remove"; - ot->description = "Remove the selected surface slot"; + /* identifiers */ + ot->name = "Remove Surface Slot"; + ot->idname = "DPAINT_OT_surface_slot_remove"; + ot->description = "Remove the selected surface slot"; - /* api callbacks */ - ot->exec = surface_slot_remove_exec; - ot->poll = ED_operator_object_active_editable; + /* api callbacks */ + ot->exec = surface_slot_remove_exec; + ot->poll = ED_operator_object_active_editable; - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } static int type_toggle_exec(bContext *C, wmOperator *op) { - Object *cObject = ED_object_context(C); - Scene *scene = CTX_data_scene(C); - DynamicPaintModifierData *pmd = (DynamicPaintModifierData *)modifiers_findByType(cObject, eModifierType_DynamicPaint); - int type = RNA_enum_get(op->ptr, "type"); - - if (!pmd) return OPERATOR_CANCELLED; - - /* if type is already enabled, toggle it off */ - if (type == MOD_DYNAMICPAINT_TYPE_CANVAS && pmd->canvas) { - dynamicPaint_freeCanvas(pmd); - } - else if (type == MOD_DYNAMICPAINT_TYPE_BRUSH && pmd->brush) { - dynamicPaint_freeBrush(pmd); - } - /* else create a new type */ - else { - if (!dynamicPaint_createType(pmd, type, scene)) - return OPERATOR_CANCELLED; - } - - /* update dependency */ - DEG_id_tag_update(&cObject->id, ID_RECALC_GEOMETRY); - DEG_relations_tag_update(CTX_data_main(C)); - WM_event_add_notifier(C, NC_OBJECT | ND_MODIFIER, cObject); - - return OPERATOR_FINISHED; + Object *cObject = ED_object_context(C); + Scene *scene = CTX_data_scene(C); + DynamicPaintModifierData *pmd = (DynamicPaintModifierData *)modifiers_findByType( + cObject, eModifierType_DynamicPaint); + int type = RNA_enum_get(op->ptr, "type"); + + if (!pmd) + return OPERATOR_CANCELLED; + + /* if type is already enabled, toggle it off */ + if (type == MOD_DYNAMICPAINT_TYPE_CANVAS && pmd->canvas) { + dynamicPaint_freeCanvas(pmd); + } + else if (type == MOD_DYNAMICPAINT_TYPE_BRUSH && pmd->brush) { + dynamicPaint_freeBrush(pmd); + } + /* else create a new type */ + else { + if (!dynamicPaint_createType(pmd, type, scene)) + return OPERATOR_CANCELLED; + } + + /* update dependency */ + DEG_id_tag_update(&cObject->id, ID_RECALC_GEOMETRY); + DEG_relations_tag_update(CTX_data_main(C)); + WM_event_add_notifier(C, NC_OBJECT | ND_MODIFIER, cObject); + + return OPERATOR_FINISHED; } void DPAINT_OT_type_toggle(wmOperatorType *ot) { - PropertyRNA *prop; - - /* identifiers */ - ot->name = "Toggle Type Active"; - ot->idname = "DPAINT_OT_type_toggle"; - ot->description = "Toggle whether given type is active or not"; - - /* api callbacks */ - ot->exec = type_toggle_exec; - ot->poll = ED_operator_object_active_editable; - - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; - - /* properties */ - prop = RNA_def_enum(ot->srna, "type", rna_enum_prop_dynamicpaint_type_items, MOD_DYNAMICPAINT_TYPE_CANVAS, "Type", ""); - ot->prop = prop; + PropertyRNA *prop; + + /* identifiers */ + ot->name = "Toggle Type Active"; + ot->idname = "DPAINT_OT_type_toggle"; + ot->description = "Toggle whether given type is active or not"; + + /* api callbacks */ + ot->exec = type_toggle_exec; + ot->poll = ED_operator_object_active_editable; + + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + + /* properties */ + prop = RNA_def_enum(ot->srna, + "type", + rna_enum_prop_dynamicpaint_type_items, + MOD_DYNAMICPAINT_TYPE_CANVAS, + "Type", + ""); + ot->prop = prop; } static int output_toggle_exec(bContext *C, wmOperator *op) { - Object *ob = ED_object_context(C); - DynamicPaintSurface *surface; - DynamicPaintModifierData *pmd = (DynamicPaintModifierData *)modifiers_findByType(ob, eModifierType_DynamicPaint); - int output = RNA_enum_get(op->ptr, "output"); /* currently only 1/0 */ - - if (!pmd || !pmd->canvas) return OPERATOR_CANCELLED; - surface = get_activeSurface(pmd->canvas); - - /* if type is already enabled, toggle it off */ - if (surface->format == MOD_DPAINT_SURFACE_F_VERTEX) { - int exists = dynamicPaint_outputLayerExists(surface, ob, output); - const char *name; - - if (output == 0) - name = surface->output_name; - else - name = surface->output_name2; - - /* Vertex Color Layer */ - if (surface->type == MOD_DPAINT_SURFACE_T_PAINT) { - if (!exists) - ED_mesh_color_add(ob->data, name, true, true); - else - ED_mesh_color_remove_named(ob->data, name); - } - /* Vertex Weight Layer */ - else if (surface->type == MOD_DPAINT_SURFACE_T_WEIGHT) { - if (!exists) { - BKE_object_defgroup_add_name(ob, name); - } - else { - bDeformGroup *defgroup = defgroup_find_name(ob, name); - if (defgroup) BKE_object_defgroup_remove(ob, defgroup); - } - } - } - - return OPERATOR_FINISHED; + Object *ob = ED_object_context(C); + DynamicPaintSurface *surface; + DynamicPaintModifierData *pmd = (DynamicPaintModifierData *)modifiers_findByType( + ob, eModifierType_DynamicPaint); + int output = RNA_enum_get(op->ptr, "output"); /* currently only 1/0 */ + + if (!pmd || !pmd->canvas) + return OPERATOR_CANCELLED; + surface = get_activeSurface(pmd->canvas); + + /* if type is already enabled, toggle it off */ + if (surface->format == MOD_DPAINT_SURFACE_F_VERTEX) { + int exists = dynamicPaint_outputLayerExists(surface, ob, output); + const char *name; + + if (output == 0) + name = surface->output_name; + else + name = surface->output_name2; + + /* Vertex Color Layer */ + if (surface->type == MOD_DPAINT_SURFACE_T_PAINT) { + if (!exists) + ED_mesh_color_add(ob->data, name, true, true); + else + ED_mesh_color_remove_named(ob->data, name); + } + /* Vertex Weight Layer */ + else if (surface->type == MOD_DPAINT_SURFACE_T_WEIGHT) { + if (!exists) { + BKE_object_defgroup_add_name(ob, name); + } + else { + bDeformGroup *defgroup = defgroup_find_name(ob, name); + if (defgroup) + BKE_object_defgroup_remove(ob, defgroup); + } + } + } + + return OPERATOR_FINISHED; } void DPAINT_OT_output_toggle(wmOperatorType *ot) { - static const EnumPropertyItem prop_output_toggle_types[] = { - {0, "A", 0, "Output A", ""}, - {1, "B", 0, "Output B", ""}, - {0, NULL, 0, NULL, NULL}, - }; - - /* identifiers */ - ot->name = "Toggle Output Layer"; - ot->idname = "DPAINT_OT_output_toggle"; - ot->description = "Add or remove Dynamic Paint output data layer"; - - /* api callbacks */ - ot->exec = output_toggle_exec; - ot->poll = ED_operator_object_active_editable; - - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; - - /* properties */ - ot->prop = RNA_def_enum(ot->srna, "output", prop_output_toggle_types, 0, "Output Toggle", ""); + static const EnumPropertyItem prop_output_toggle_types[] = { + {0, "A", 0, "Output A", ""}, + {1, "B", 0, "Output B", ""}, + {0, NULL, 0, NULL, NULL}, + }; + + /* identifiers */ + ot->name = "Toggle Output Layer"; + ot->idname = "DPAINT_OT_output_toggle"; + ot->description = "Add or remove Dynamic Paint output data layer"; + + /* api callbacks */ + ot->exec = output_toggle_exec; + ot->poll = ED_operator_object_active_editable; + + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + + /* properties */ + ot->prop = RNA_def_enum(ot->srna, "output", prop_output_toggle_types, 0, "Output Toggle", ""); } - /***************************** Image Sequence Baking ******************************/ typedef struct DynamicPaintBakeJob { - /* from wmJob */ - void *owner; - short *stop, *do_update; - float *progress; + /* from wmJob */ + void *owner; + short *stop, *do_update; + float *progress; - struct Main *bmain; - Scene *scene; - Depsgraph *depsgraph; - Object *ob; + struct Main *bmain; + Scene *scene; + Depsgraph *depsgraph; + Object *ob; - DynamicPaintSurface *surface; - DynamicPaintCanvasSettings *canvas; + DynamicPaintSurface *surface; + DynamicPaintCanvasSettings *canvas; - int success; - double start; + int success; + double start; } DynamicPaintBakeJob; static void dpaint_bake_free(void *customdata) { - DynamicPaintBakeJob *job = customdata; - MEM_freeN(job); + DynamicPaintBakeJob *job = customdata; + MEM_freeN(job); } static void dpaint_bake_endjob(void *customdata) { - DynamicPaintBakeJob *job = customdata; - DynamicPaintCanvasSettings *canvas = job->canvas; - - canvas->flags &= ~MOD_DPAINT_BAKING; - - dynamicPaint_freeSurfaceData(job->surface); - - G.is_rendering = false; - BKE_spacedata_draw_locks(false); - - WM_set_locked_interface(G_MAIN->wm.first, false); - - /* Bake was successful: - * Report for ended bake and how long it took */ - if (job->success) { - /* Show bake info */ - WM_reportf(RPT_INFO, "DynamicPaint: Bake complete! (%.2f)", PIL_check_seconds_timer() - job->start); - } - else { - if (strlen(canvas->error)) { /* If an error occurred */ - WM_reportf(RPT_ERROR, "DynamicPaint: Bake failed: %s", canvas->error); - } - else { /* User canceled the bake */ - WM_report(RPT_WARNING, "Baking canceled!"); - } - } + DynamicPaintBakeJob *job = customdata; + DynamicPaintCanvasSettings *canvas = job->canvas; + + canvas->flags &= ~MOD_DPAINT_BAKING; + + dynamicPaint_freeSurfaceData(job->surface); + + G.is_rendering = false; + BKE_spacedata_draw_locks(false); + + WM_set_locked_interface(G_MAIN->wm.first, false); + + /* Bake was successful: + * Report for ended bake and how long it took */ + if (job->success) { + /* Show bake info */ + WM_reportf( + RPT_INFO, "DynamicPaint: Bake complete! (%.2f)", PIL_check_seconds_timer() - job->start); + } + else { + if (strlen(canvas->error)) { /* If an error occurred */ + WM_reportf(RPT_ERROR, "DynamicPaint: Bake failed: %s", canvas->error); + } + else { /* User canceled the bake */ + WM_report(RPT_WARNING, "Baking canceled!"); + } + } } /* @@ -336,110 +347,112 @@ static void dpaint_bake_endjob(void *customdata) */ static void dynamicPaint_bakeImageSequence(DynamicPaintBakeJob *job) { - DynamicPaintSurface *surface = job->surface; - Object *cObject = job->ob; - DynamicPaintCanvasSettings *canvas = surface->canvas; - Scene *scene = job->scene; - int frame = 1, orig_frame; - int frames; - - frames = surface->end_frame - surface->start_frame + 1; - if (frames <= 0) { - BLI_strncpy(canvas->error, N_("No frames to bake"), sizeof(canvas->error)); - return; - } - - /* Show progress bar. */ - *(job->do_update) = true; - - /* Set frame to start point (also inits modifier data) */ - frame = surface->start_frame; - orig_frame = scene->r.cfra; - scene->r.cfra = (int)frame; - ED_update_for_newframe(job->bmain, job->depsgraph); - - /* Init surface */ - if (!dynamicPaint_createUVSurface(scene, surface, job->progress, job->do_update)) { - job->success = 0; - return; - } - - /* Loop through selected frames */ - for (frame = surface->start_frame; frame <= surface->end_frame; frame++) { - /* The first 10% are for createUVSurface... */ - const float progress = 0.1f + 0.9f * (frame - surface->start_frame) / (float)frames; - surface->current_frame = frame; - - /* If user requested stop, quit baking */ - if (G.is_break) { - job->success = 0; - return; - } - - /* Update progress bar */ - *(job->do_update) = true; - *(job->progress) = progress; - - /* calculate a frame */ - scene->r.cfra = (int)frame; - ED_update_for_newframe(job->bmain, job->depsgraph); - if (!dynamicPaint_calculateFrame(surface, job->depsgraph, scene, cObject, frame)) { - job->success = 0; - return; - } - - /* - * Save output images - */ - { - char filename[FILE_MAX]; - - /* primary output layer */ - if (surface->flags & MOD_DPAINT_OUT1) { - /* set filepath */ - BLI_join_dirfile(filename, sizeof(filename), surface->image_output_path, surface->output_name); - BLI_path_frame(filename, frame, 4); - - /* save image */ - dynamicPaint_outputSurfaceImage(surface, filename, 0); - } - /* secondary output */ - if (surface->flags & MOD_DPAINT_OUT2 && surface->type == MOD_DPAINT_SURFACE_T_PAINT) { - /* set filepath */ - BLI_join_dirfile(filename, sizeof(filename), surface->image_output_path, surface->output_name2); - BLI_path_frame(filename, frame, 4); - - /* save image */ - dynamicPaint_outputSurfaceImage(surface, filename, 1); - } - } - } - - scene->r.cfra = orig_frame; + DynamicPaintSurface *surface = job->surface; + Object *cObject = job->ob; + DynamicPaintCanvasSettings *canvas = surface->canvas; + Scene *scene = job->scene; + int frame = 1, orig_frame; + int frames; + + frames = surface->end_frame - surface->start_frame + 1; + if (frames <= 0) { + BLI_strncpy(canvas->error, N_("No frames to bake"), sizeof(canvas->error)); + return; + } + + /* Show progress bar. */ + *(job->do_update) = true; + + /* Set frame to start point (also inits modifier data) */ + frame = surface->start_frame; + orig_frame = scene->r.cfra; + scene->r.cfra = (int)frame; + ED_update_for_newframe(job->bmain, job->depsgraph); + + /* Init surface */ + if (!dynamicPaint_createUVSurface(scene, surface, job->progress, job->do_update)) { + job->success = 0; + return; + } + + /* Loop through selected frames */ + for (frame = surface->start_frame; frame <= surface->end_frame; frame++) { + /* The first 10% are for createUVSurface... */ + const float progress = 0.1f + 0.9f * (frame - surface->start_frame) / (float)frames; + surface->current_frame = frame; + + /* If user requested stop, quit baking */ + if (G.is_break) { + job->success = 0; + return; + } + + /* Update progress bar */ + *(job->do_update) = true; + *(job->progress) = progress; + + /* calculate a frame */ + scene->r.cfra = (int)frame; + ED_update_for_newframe(job->bmain, job->depsgraph); + if (!dynamicPaint_calculateFrame(surface, job->depsgraph, scene, cObject, frame)) { + job->success = 0; + return; + } + + /* + * Save output images + */ + { + char filename[FILE_MAX]; + + /* primary output layer */ + if (surface->flags & MOD_DPAINT_OUT1) { + /* set filepath */ + BLI_join_dirfile( + filename, sizeof(filename), surface->image_output_path, surface->output_name); + BLI_path_frame(filename, frame, 4); + + /* save image */ + dynamicPaint_outputSurfaceImage(surface, filename, 0); + } + /* secondary output */ + if (surface->flags & MOD_DPAINT_OUT2 && surface->type == MOD_DPAINT_SURFACE_T_PAINT) { + /* set filepath */ + BLI_join_dirfile( + filename, sizeof(filename), surface->image_output_path, surface->output_name2); + BLI_path_frame(filename, frame, 4); + + /* save image */ + dynamicPaint_outputSurfaceImage(surface, filename, 1); + } + } + } + + scene->r.cfra = orig_frame; } static void dpaint_bake_startjob(void *customdata, short *stop, short *do_update, float *progress) { - DynamicPaintBakeJob *job = customdata; + DynamicPaintBakeJob *job = customdata; - job->stop = stop; - job->do_update = do_update; - job->progress = progress; - job->start = PIL_check_seconds_timer(); - job->success = 1; + job->stop = stop; + job->do_update = do_update; + job->progress = progress; + job->start = PIL_check_seconds_timer(); + job->success = 1; - G.is_break = false; /* reset BKE_blender_test_break*/ + G.is_break = false; /* reset BKE_blender_test_break*/ - /* XXX annoying hack: needed to prevent data corruption when changing - * scene frame in separate threads - */ - G.is_rendering = true; - BKE_spacedata_draw_locks(true); + /* XXX annoying hack: needed to prevent data corruption when changing + * scene frame in separate threads + */ + G.is_rendering = true; + BKE_spacedata_draw_locks(true); - dynamicPaint_bakeImageSequence(job); + dynamicPaint_bakeImageSequence(job); - *do_update = true; - *stop = 0; + *do_update = true; + *stop = 0; } /* @@ -447,66 +460,69 @@ static void dpaint_bake_startjob(void *customdata, short *stop, short *do_update */ static int dynamicpaint_bake_exec(struct bContext *C, struct wmOperator *op) { - DynamicPaintModifierData *pmd = NULL; - DynamicPaintCanvasSettings *canvas; - Object *ob = ED_object_context(C); - Scene *scene = CTX_data_scene(C); - - DynamicPaintSurface *surface; - - /* - * Get modifier data - */ - pmd = (DynamicPaintModifierData *)modifiers_findByType(ob, eModifierType_DynamicPaint); - if (!pmd) { - BKE_report(op->reports, RPT_ERROR, "Bake failed: no Dynamic Paint modifier found"); - return OPERATOR_CANCELLED; - } - - /* Make sure we're dealing with a canvas */ - canvas = pmd->canvas; - if (!canvas) { - BKE_report(op->reports, RPT_ERROR, "Bake failed: invalid canvas"); - return OPERATOR_CANCELLED; - } - surface = get_activeSurface(canvas); - - /* Set state to baking and init surface */ - canvas->error[0] = '\0'; - canvas->flags |= MOD_DPAINT_BAKING; - - DynamicPaintBakeJob *job = MEM_mallocN(sizeof(DynamicPaintBakeJob), "DynamicPaintBakeJob"); - job->bmain = CTX_data_main(C); - job->scene = scene; - job->depsgraph = CTX_data_depsgraph(C); - job->ob = ob; - job->canvas = canvas; - job->surface = surface; - - wmJob *wm_job = WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), scene, - "Dynamic Paint Bake", WM_JOB_PROGRESS, - WM_JOB_TYPE_DPAINT_BAKE); - - WM_jobs_customdata_set(wm_job, job, dpaint_bake_free); - WM_jobs_timer(wm_job, 0.1, NC_OBJECT | ND_MODIFIER, NC_OBJECT | ND_MODIFIER); - WM_jobs_callbacks(wm_job, dpaint_bake_startjob, NULL, NULL, dpaint_bake_endjob); - - WM_set_locked_interface(CTX_wm_manager(C), true); - - /* Bake Dynamic Paint */ - WM_jobs_start(CTX_wm_manager(C), wm_job); - - return OPERATOR_FINISHED; + DynamicPaintModifierData *pmd = NULL; + DynamicPaintCanvasSettings *canvas; + Object *ob = ED_object_context(C); + Scene *scene = CTX_data_scene(C); + + DynamicPaintSurface *surface; + + /* + * Get modifier data + */ + pmd = (DynamicPaintModifierData *)modifiers_findByType(ob, eModifierType_DynamicPaint); + if (!pmd) { + BKE_report(op->reports, RPT_ERROR, "Bake failed: no Dynamic Paint modifier found"); + return OPERATOR_CANCELLED; + } + + /* Make sure we're dealing with a canvas */ + canvas = pmd->canvas; + if (!canvas) { + BKE_report(op->reports, RPT_ERROR, "Bake failed: invalid canvas"); + return OPERATOR_CANCELLED; + } + surface = get_activeSurface(canvas); + + /* Set state to baking and init surface */ + canvas->error[0] = '\0'; + canvas->flags |= MOD_DPAINT_BAKING; + + DynamicPaintBakeJob *job = MEM_mallocN(sizeof(DynamicPaintBakeJob), "DynamicPaintBakeJob"); + job->bmain = CTX_data_main(C); + job->scene = scene; + job->depsgraph = CTX_data_depsgraph(C); + job->ob = ob; + job->canvas = canvas; + job->surface = surface; + + wmJob *wm_job = WM_jobs_get(CTX_wm_manager(C), + CTX_wm_window(C), + scene, + "Dynamic Paint Bake", + WM_JOB_PROGRESS, + WM_JOB_TYPE_DPAINT_BAKE); + + WM_jobs_customdata_set(wm_job, job, dpaint_bake_free); + WM_jobs_timer(wm_job, 0.1, NC_OBJECT | ND_MODIFIER, NC_OBJECT | ND_MODIFIER); + WM_jobs_callbacks(wm_job, dpaint_bake_startjob, NULL, NULL, dpaint_bake_endjob); + + WM_set_locked_interface(CTX_wm_manager(C), true); + + /* Bake Dynamic Paint */ + WM_jobs_start(CTX_wm_manager(C), wm_job); + + return OPERATOR_FINISHED; } void DPAINT_OT_bake(wmOperatorType *ot) { - /* identifiers */ - ot->name = "Dynamic Paint Bake"; - ot->description = "Bake dynamic paint image sequence surface"; - ot->idname = "DPAINT_OT_bake"; - - /* api callbacks */ - ot->exec = dynamicpaint_bake_exec; - ot->poll = ED_operator_object_active_editable; + /* identifiers */ + ot->name = "Dynamic Paint Bake"; + ot->description = "Bake dynamic paint image sequence surface"; + ot->idname = "DPAINT_OT_bake"; + + /* api callbacks */ + ot->exec = dynamicpaint_bake_exec; + ot->poll = ED_operator_object_active_editable; } diff --git a/source/blender/editors/physics/particle_boids.c b/source/blender/editors/physics/particle_boids.c index 7ddb193b0e5..cedb7d6cbc1 100644 --- a/source/blender/editors/physics/particle_boids.c +++ b/source/blender/editors/physics/particle_boids.c @@ -21,7 +21,6 @@ * \ingroup edphys */ - #include #include "MEM_guardedalloc.h" @@ -51,316 +50,315 @@ /************************ add/del boid rule operators *********************/ static int rule_add_exec(bContext *C, wmOperator *op) { - PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_settings", &RNA_ParticleSettings); - ParticleSettings *part = ptr.data; - int type = RNA_enum_get(op->ptr, "type"); + PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_settings", &RNA_ParticleSettings); + ParticleSettings *part = ptr.data; + int type = RNA_enum_get(op->ptr, "type"); - BoidRule *rule; - BoidState *state; + BoidRule *rule; + BoidState *state; - if (!part || part->phystype != PART_PHYS_BOIDS) - return OPERATOR_CANCELLED; + if (!part || part->phystype != PART_PHYS_BOIDS) + return OPERATOR_CANCELLED; - state = boid_get_current_state(part->boids); + state = boid_get_current_state(part->boids); - for (rule = state->rules.first; rule; rule = rule->next) - rule->flag &= ~BOIDRULE_CURRENT; + for (rule = state->rules.first; rule; rule = rule->next) + rule->flag &= ~BOIDRULE_CURRENT; - rule = boid_new_rule(type); - rule->flag |= BOIDRULE_CURRENT; + rule = boid_new_rule(type); + rule->flag |= BOIDRULE_CURRENT; - BLI_addtail(&state->rules, rule); + BLI_addtail(&state->rules, rule); - DEG_id_tag_update(&part->id, ID_RECALC_GEOMETRY | ID_RECALC_PSYS_RESET); + DEG_id_tag_update(&part->id, ID_RECALC_GEOMETRY | ID_RECALC_PSYS_RESET); - return OPERATOR_FINISHED; + return OPERATOR_FINISHED; } void BOID_OT_rule_add(wmOperatorType *ot) { - /* identifiers */ - ot->name = "Add Boid Rule"; - ot->description = "Add a boid rule to the current boid state"; - ot->idname = "BOID_OT_rule_add"; + /* identifiers */ + ot->name = "Add Boid Rule"; + ot->description = "Add a boid rule to the current boid state"; + ot->idname = "BOID_OT_rule_add"; - /* api callbacks */ - ot->invoke = WM_menu_invoke; - ot->exec = rule_add_exec; + /* api callbacks */ + ot->invoke = WM_menu_invoke; + ot->exec = rule_add_exec; - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; - ot->prop = RNA_def_enum(ot->srna, "type", rna_enum_boidrule_type_items, 0, "Type", ""); + ot->prop = RNA_def_enum(ot->srna, "type", rna_enum_boidrule_type_items, 0, "Type", ""); } static int rule_del_exec(bContext *C, wmOperator *UNUSED(op)) { - Main *bmain = CTX_data_main(C); - PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_settings", &RNA_ParticleSettings); - ParticleSettings *part = ptr.data; - BoidRule *rule; - BoidState *state; + Main *bmain = CTX_data_main(C); + PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_settings", &RNA_ParticleSettings); + ParticleSettings *part = ptr.data; + BoidRule *rule; + BoidState *state; - if (!part || part->phystype != PART_PHYS_BOIDS) - return OPERATOR_CANCELLED; + if (!part || part->phystype != PART_PHYS_BOIDS) + return OPERATOR_CANCELLED; - state = boid_get_current_state(part->boids); + state = boid_get_current_state(part->boids); - for (rule = state->rules.first; rule; rule = rule->next) { - if (rule->flag & BOIDRULE_CURRENT) { - BLI_remlink(&state->rules, rule); - MEM_freeN(rule); - break; - } - } - rule = state->rules.first; + for (rule = state->rules.first; rule; rule = rule->next) { + if (rule->flag & BOIDRULE_CURRENT) { + BLI_remlink(&state->rules, rule); + MEM_freeN(rule); + break; + } + } + rule = state->rules.first; - if (rule) - rule->flag |= BOIDRULE_CURRENT; + if (rule) + rule->flag |= BOIDRULE_CURRENT; - DEG_relations_tag_update(bmain); - DEG_id_tag_update(&part->id, ID_RECALC_GEOMETRY | ID_RECALC_PSYS_RESET); + DEG_relations_tag_update(bmain); + DEG_id_tag_update(&part->id, ID_RECALC_GEOMETRY | ID_RECALC_PSYS_RESET); - return OPERATOR_FINISHED; + return OPERATOR_FINISHED; } void BOID_OT_rule_del(wmOperatorType *ot) { - /* identifiers */ - ot->name = "Remove Boid Rule"; - ot->idname = "BOID_OT_rule_del"; - ot->description = "Delete current boid rule"; + /* identifiers */ + ot->name = "Remove Boid Rule"; + ot->idname = "BOID_OT_rule_del"; + ot->description = "Delete current boid rule"; - /* api callbacks */ - ot->exec = rule_del_exec; + /* api callbacks */ + ot->exec = rule_del_exec; - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } /************************ move up/down boid rule operators *********************/ static int rule_move_up_exec(bContext *C, wmOperator *UNUSED(op)) { - PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_settings", &RNA_ParticleSettings); - ParticleSettings *part = ptr.data; - BoidRule *rule; - BoidState *state; - - if (!part || part->phystype != PART_PHYS_BOIDS) - return OPERATOR_CANCELLED; - - state = boid_get_current_state(part->boids); - for (rule = state->rules.first; rule; rule = rule->next) { - if (rule->flag & BOIDRULE_CURRENT && rule->prev) { - BLI_remlink(&state->rules, rule); - BLI_insertlinkbefore(&state->rules, rule->prev, rule); - - DEG_id_tag_update(&part->id, ID_RECALC_GEOMETRY | ID_RECALC_PSYS_RESET); - break; - } - } - - return OPERATOR_FINISHED; + PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_settings", &RNA_ParticleSettings); + ParticleSettings *part = ptr.data; + BoidRule *rule; + BoidState *state; + + if (!part || part->phystype != PART_PHYS_BOIDS) + return OPERATOR_CANCELLED; + + state = boid_get_current_state(part->boids); + for (rule = state->rules.first; rule; rule = rule->next) { + if (rule->flag & BOIDRULE_CURRENT && rule->prev) { + BLI_remlink(&state->rules, rule); + BLI_insertlinkbefore(&state->rules, rule->prev, rule); + + DEG_id_tag_update(&part->id, ID_RECALC_GEOMETRY | ID_RECALC_PSYS_RESET); + break; + } + } + + return OPERATOR_FINISHED; } void BOID_OT_rule_move_up(wmOperatorType *ot) { - ot->name = "Move Up Boid Rule"; - ot->description = "Move boid rule up in the list"; - ot->idname = "BOID_OT_rule_move_up"; + ot->name = "Move Up Boid Rule"; + ot->description = "Move boid rule up in the list"; + ot->idname = "BOID_OT_rule_move_up"; - ot->exec = rule_move_up_exec; + ot->exec = rule_move_up_exec; - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } static int rule_move_down_exec(bContext *C, wmOperator *UNUSED(op)) { - PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_settings", &RNA_ParticleSettings); - ParticleSettings *part = ptr.data; - BoidRule *rule; - BoidState *state; - - if (!part || part->phystype != PART_PHYS_BOIDS) - return OPERATOR_CANCELLED; - - state = boid_get_current_state(part->boids); - for (rule = state->rules.first; rule; rule = rule->next) { - if (rule->flag & BOIDRULE_CURRENT && rule->next) { - BLI_remlink(&state->rules, rule); - BLI_insertlinkafter(&state->rules, rule->next, rule); - - DEG_id_tag_update(&part->id, ID_RECALC_GEOMETRY | ID_RECALC_PSYS_RESET); - break; - } - } - - return OPERATOR_FINISHED; + PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_settings", &RNA_ParticleSettings); + ParticleSettings *part = ptr.data; + BoidRule *rule; + BoidState *state; + + if (!part || part->phystype != PART_PHYS_BOIDS) + return OPERATOR_CANCELLED; + + state = boid_get_current_state(part->boids); + for (rule = state->rules.first; rule; rule = rule->next) { + if (rule->flag & BOIDRULE_CURRENT && rule->next) { + BLI_remlink(&state->rules, rule); + BLI_insertlinkafter(&state->rules, rule->next, rule); + + DEG_id_tag_update(&part->id, ID_RECALC_GEOMETRY | ID_RECALC_PSYS_RESET); + break; + } + } + + return OPERATOR_FINISHED; } void BOID_OT_rule_move_down(wmOperatorType *ot) { - ot->name = "Move Down Boid Rule"; - ot->description = "Move boid rule down in the list"; - ot->idname = "BOID_OT_rule_move_down"; + ot->name = "Move Down Boid Rule"; + ot->description = "Move boid rule down in the list"; + ot->idname = "BOID_OT_rule_move_down"; - ot->exec = rule_move_down_exec; + ot->exec = rule_move_down_exec; - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } - /************************ add/del boid state operators *********************/ static int state_add_exec(bContext *C, wmOperator *UNUSED(op)) { - PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_settings", &RNA_ParticleSettings); - ParticleSettings *part = ptr.data; - BoidState *state; + PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_settings", &RNA_ParticleSettings); + ParticleSettings *part = ptr.data; + BoidState *state; - if (!part || part->phystype != PART_PHYS_BOIDS) - return OPERATOR_CANCELLED; + if (!part || part->phystype != PART_PHYS_BOIDS) + return OPERATOR_CANCELLED; - for (state = part->boids->states.first; state; state = state->next) - state->flag &= ~BOIDSTATE_CURRENT; + for (state = part->boids->states.first; state; state = state->next) + state->flag &= ~BOIDSTATE_CURRENT; - state = boid_new_state(part->boids); - state->flag |= BOIDSTATE_CURRENT; + state = boid_new_state(part->boids); + state->flag |= BOIDSTATE_CURRENT; - BLI_addtail(&part->boids->states, state); + BLI_addtail(&part->boids->states, state); - return OPERATOR_FINISHED; + return OPERATOR_FINISHED; } void BOID_OT_state_add(wmOperatorType *ot) { - /* identifiers */ - ot->name = "Add Boid State"; - ot->description = "Add a boid state to the particle system"; - ot->idname = "BOID_OT_state_add"; + /* identifiers */ + ot->name = "Add Boid State"; + ot->description = "Add a boid state to the particle system"; + ot->idname = "BOID_OT_state_add"; - /* api callbacks */ - ot->exec = state_add_exec; + /* api callbacks */ + ot->exec = state_add_exec; - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } static int state_del_exec(bContext *C, wmOperator *UNUSED(op)) { - Main *bmain = CTX_data_main(C); - PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_settings", &RNA_ParticleSettings); - ParticleSettings *part = ptr.data; - BoidState *state; - - if (!part || part->phystype != PART_PHYS_BOIDS) - return OPERATOR_CANCELLED; - - for (state = part->boids->states.first; state; state = state->next) { - if (state->flag & BOIDSTATE_CURRENT) { - BLI_remlink(&part->boids->states, state); - MEM_freeN(state); - break; - } - } - - /* there must be at least one state */ - if (!part->boids->states.first) { - state = boid_new_state(part->boids); - BLI_addtail(&part->boids->states, state); - } - else - state = part->boids->states.first; - - state->flag |= BOIDSTATE_CURRENT; - - DEG_relations_tag_update(bmain); - DEG_id_tag_update(&part->id, ID_RECALC_GEOMETRY | ID_RECALC_PSYS_RESET); - - return OPERATOR_FINISHED; + Main *bmain = CTX_data_main(C); + PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_settings", &RNA_ParticleSettings); + ParticleSettings *part = ptr.data; + BoidState *state; + + if (!part || part->phystype != PART_PHYS_BOIDS) + return OPERATOR_CANCELLED; + + for (state = part->boids->states.first; state; state = state->next) { + if (state->flag & BOIDSTATE_CURRENT) { + BLI_remlink(&part->boids->states, state); + MEM_freeN(state); + break; + } + } + + /* there must be at least one state */ + if (!part->boids->states.first) { + state = boid_new_state(part->boids); + BLI_addtail(&part->boids->states, state); + } + else + state = part->boids->states.first; + + state->flag |= BOIDSTATE_CURRENT; + + DEG_relations_tag_update(bmain); + DEG_id_tag_update(&part->id, ID_RECALC_GEOMETRY | ID_RECALC_PSYS_RESET); + + return OPERATOR_FINISHED; } void BOID_OT_state_del(wmOperatorType *ot) { - /* identifiers */ - ot->name = "Remove Boid State"; - ot->idname = "BOID_OT_state_del"; - ot->description = "Delete current boid state"; + /* identifiers */ + ot->name = "Remove Boid State"; + ot->idname = "BOID_OT_state_del"; + ot->description = "Delete current boid state"; - /* api callbacks */ - ot->exec = state_del_exec; + /* api callbacks */ + ot->exec = state_del_exec; - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } /************************ move up/down boid state operators *********************/ static int state_move_up_exec(bContext *C, wmOperator *UNUSED(op)) { - PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_settings", &RNA_ParticleSettings); - ParticleSettings *part = ptr.data; - BoidSettings *boids; - BoidState *state; + PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_settings", &RNA_ParticleSettings); + ParticleSettings *part = ptr.data; + BoidSettings *boids; + BoidState *state; - if (!part || part->phystype != PART_PHYS_BOIDS) - return OPERATOR_CANCELLED; + if (!part || part->phystype != PART_PHYS_BOIDS) + return OPERATOR_CANCELLED; - boids = part->boids; + boids = part->boids; - for (state = boids->states.first; state; state = state->next) { - if (state->flag & BOIDSTATE_CURRENT && state->prev) { - BLI_remlink(&boids->states, state); - BLI_insertlinkbefore(&boids->states, state->prev, state); - break; - } - } + for (state = boids->states.first; state; state = state->next) { + if (state->flag & BOIDSTATE_CURRENT && state->prev) { + BLI_remlink(&boids->states, state); + BLI_insertlinkbefore(&boids->states, state->prev, state); + break; + } + } - return OPERATOR_FINISHED; + return OPERATOR_FINISHED; } void BOID_OT_state_move_up(wmOperatorType *ot) { - ot->name = "Move Up Boid State"; - ot->description = "Move boid state up in the list"; - ot->idname = "BOID_OT_state_move_up"; + ot->name = "Move Up Boid State"; + ot->description = "Move boid state up in the list"; + ot->idname = "BOID_OT_state_move_up"; - ot->exec = state_move_up_exec; + ot->exec = state_move_up_exec; - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } static int state_move_down_exec(bContext *C, wmOperator *UNUSED(op)) { - PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_settings", &RNA_ParticleSettings); - ParticleSettings *part = ptr.data; - BoidSettings *boids; - BoidState *state; - - if (!part || part->phystype != PART_PHYS_BOIDS) - return OPERATOR_CANCELLED; - - boids = part->boids; - - for (state = boids->states.first; state; state = state->next) { - if (state->flag & BOIDSTATE_CURRENT && state->next) { - BLI_remlink(&boids->states, state); - BLI_insertlinkafter(&boids->states, state->next, state); - DEG_id_tag_update(&part->id, ID_RECALC_GEOMETRY | ID_RECALC_PSYS_RESET); - break; - } - } - - return OPERATOR_FINISHED; + PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_settings", &RNA_ParticleSettings); + ParticleSettings *part = ptr.data; + BoidSettings *boids; + BoidState *state; + + if (!part || part->phystype != PART_PHYS_BOIDS) + return OPERATOR_CANCELLED; + + boids = part->boids; + + for (state = boids->states.first; state; state = state->next) { + if (state->flag & BOIDSTATE_CURRENT && state->next) { + BLI_remlink(&boids->states, state); + BLI_insertlinkafter(&boids->states, state->next, state); + DEG_id_tag_update(&part->id, ID_RECALC_GEOMETRY | ID_RECALC_PSYS_RESET); + break; + } + } + + return OPERATOR_FINISHED; } void BOID_OT_state_move_down(wmOperatorType *ot) { - ot->name = "Move Down Boid State"; - ot->description = "Move boid state down in the list"; - ot->idname = "BOID_OT_state_move_down"; + ot->name = "Move Down Boid State"; + ot->description = "Move boid state down in the list"; + ot->idname = "BOID_OT_state_move_down"; - ot->exec = state_move_down_exec; + ot->exec = state_move_down_exec; - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } diff --git a/source/blender/editors/physics/particle_edit.c b/source/blender/editors/physics/particle_edit.c index f2d9871a99d..627ffd68bbb 100644 --- a/source/blender/editors/physics/particle_edit.c +++ b/source/blender/editors/physics/particle_edit.c @@ -59,7 +59,6 @@ #include "DEG_depsgraph.h" - #include "ED_object.h" #include "ED_physics.h" #include "ED_mesh.h" @@ -94,118 +93,117 @@ bool PE_poll(bContext *C) { - Scene *scene = CTX_data_scene(C); - Object *ob = CTX_data_active_object(C); + Scene *scene = CTX_data_scene(C); + Object *ob = CTX_data_active_object(C); - if (!scene || !ob || !(ob->mode & OB_MODE_PARTICLE_EDIT)) { - return 0; - } - return (PE_get_current(scene, ob) != NULL); + if (!scene || !ob || !(ob->mode & OB_MODE_PARTICLE_EDIT)) { + return 0; + } + return (PE_get_current(scene, ob) != NULL); } bool PE_hair_poll(bContext *C) { - Scene *scene = CTX_data_scene(C); - Object *ob = CTX_data_active_object(C); - PTCacheEdit *edit; + Scene *scene = CTX_data_scene(C); + Object *ob = CTX_data_active_object(C); + PTCacheEdit *edit; - if (!scene || !ob || !(ob->mode & OB_MODE_PARTICLE_EDIT)) { - return 0; - } - edit = PE_get_current(scene, ob); + if (!scene || !ob || !(ob->mode & OB_MODE_PARTICLE_EDIT)) { + return 0; + } + edit = PE_get_current(scene, ob); - return (edit && edit->psys); + return (edit && edit->psys); } bool PE_poll_view3d(bContext *C) { - ScrArea *sa = CTX_wm_area(C); - ARegion *ar = CTX_wm_region(C); + ScrArea *sa = CTX_wm_area(C); + ARegion *ar = CTX_wm_region(C); - return (PE_poll(C) && - (sa && sa->spacetype == SPACE_VIEW3D) && - (ar && ar->regiontype == RGN_TYPE_WINDOW)); + return (PE_poll(C) && (sa && sa->spacetype == SPACE_VIEW3D) && + (ar && ar->regiontype == RGN_TYPE_WINDOW)); } void PE_free_ptcache_edit(PTCacheEdit *edit) { - POINT_P; + POINT_P; - if (edit == 0) return; + if (edit == 0) + return; - if (edit->points) { - LOOP_POINTS { - if (point->keys) - MEM_freeN(point->keys); - } + if (edit->points) { + LOOP_POINTS + { + if (point->keys) + MEM_freeN(point->keys); + } - MEM_freeN(edit->points); - } + MEM_freeN(edit->points); + } - if (edit->mirror_cache) - MEM_freeN(edit->mirror_cache); + if (edit->mirror_cache) + MEM_freeN(edit->mirror_cache); - if (edit->emitter_cosnos) { - MEM_freeN(edit->emitter_cosnos); - edit->emitter_cosnos = 0; - } + if (edit->emitter_cosnos) { + MEM_freeN(edit->emitter_cosnos); + edit->emitter_cosnos = 0; + } - if (edit->emitter_field) { - BLI_kdtree_3d_free(edit->emitter_field); - edit->emitter_field = 0; - } + if (edit->emitter_field) { + BLI_kdtree_3d_free(edit->emitter_field); + edit->emitter_field = 0; + } - psys_free_path_cache(edit->psys, edit); + psys_free_path_cache(edit->psys, edit); - MEM_freeN(edit); + MEM_freeN(edit); } /************************************************/ -/* Edit Mode Helpers */ +/* Edit Mode Helpers */ /************************************************/ int PE_start_edit(PTCacheEdit *edit) { - if (edit) { - edit->edited = 1; - if (edit->psys) - edit->psys->flag |= PSYS_EDITED; - return 1; - } + if (edit) { + edit->edited = 1; + if (edit->psys) + edit->psys->flag |= PSYS_EDITED; + return 1; + } - return 0; + return 0; } ParticleEditSettings *PE_settings(Scene *scene) { - return scene->toolsettings ? &scene->toolsettings->particle : NULL; + return scene->toolsettings ? &scene->toolsettings->particle : NULL; } static float pe_brush_size_get(const Scene *UNUSED(scene), ParticleBrushData *brush) { - // here we can enable unified brush size, needs more work... - // UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings; - // float size = (ups->flag & UNIFIED_PAINT_SIZE) ? ups->size : brush->size; + // here we can enable unified brush size, needs more work... + // UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings; + // float size = (ups->flag & UNIFIED_PAINT_SIZE) ? ups->size : brush->size; - return brush->size * U.pixelsize; + return brush->size * U.pixelsize; } PTCacheEdit *PE_get_current_from_psys(ParticleSystem *psys) { - if (psys->part && psys->part->type == PART_HAIR) { - if ((psys->flag & PSYS_HAIR_DYNAMICS) != 0 && - (psys->pointcache->flag & PTCACHE_BAKED) != 0) - { - return psys->pointcache->edit; - } - else { - return psys->edit; - } - } - else if (psys->pointcache->flag & PTCACHE_BAKED) { - return psys->pointcache->edit; - } - return NULL; + if (psys->part && psys->part->type == PART_HAIR) { + if ((psys->flag & PSYS_HAIR_DYNAMICS) != 0 && (psys->pointcache->flag & PTCACHE_BAKED) != 0) { + return psys->pointcache->edit; + } + else { + return psys->edit; + } + } + else if (psys->pointcache->flag & PTCACHE_BAKED) { + return psys->pointcache->edit; + } + return NULL; } /* NOTE: Similar to creation of edit, but only updates pointers in the @@ -213,1678 +211,1722 @@ PTCacheEdit *PE_get_current_from_psys(ParticleSystem *psys) */ static void pe_update_hair_particle_edit_pointers(PTCacheEdit *edit) { - ParticleSystem *psys = edit->psys; - ParticleData *pa = psys->particles; - for (int p = 0; p < edit->totpoint; p++) { - PTCacheEditPoint *point = &edit->points[p]; - HairKey *hair_key = pa->hair; - for (int k = 0; k < point->totkey; k++) { - PTCacheEditKey *key = &point->keys[k]; - key->co = hair_key->co; - key->time = &hair_key->time; - key->flag = hair_key->editflag; - if (!(psys->flag & PSYS_GLOBAL_HAIR)) { - key->flag |= PEK_USE_WCO; - hair_key->editflag |= PEK_USE_WCO; - } - hair_key++; - } - pa++; - } + ParticleSystem *psys = edit->psys; + ParticleData *pa = psys->particles; + for (int p = 0; p < edit->totpoint; p++) { + PTCacheEditPoint *point = &edit->points[p]; + HairKey *hair_key = pa->hair; + for (int k = 0; k < point->totkey; k++) { + PTCacheEditKey *key = &point->keys[k]; + key->co = hair_key->co; + key->time = &hair_key->time; + key->flag = hair_key->editflag; + if (!(psys->flag & PSYS_GLOBAL_HAIR)) { + key->flag |= PEK_USE_WCO; + hair_key->editflag |= PEK_USE_WCO; + } + hair_key++; + } + pa++; + } } /* always gets at least the first particlesystem even if PSYS_CURRENT flag is not set * * note: this function runs on poll, therefor it can runs many times a second * keep it fast! */ -static PTCacheEdit *pe_get_current( - Depsgraph *depsgraph, Scene *scene, Object *ob, int create) -{ - ParticleEditSettings *pset = PE_settings(scene); - PTCacheEdit *edit = NULL; - ListBase pidlist; - PTCacheID *pid; - - if (pset == NULL || ob == NULL) - return NULL; - - pset->scene = scene; - pset->object = ob; - - BKE_ptcache_ids_from_object(&pidlist, ob, NULL, 0); - - /* in the case of only one editable thing, set pset->edittype accordingly */ - if (BLI_listbase_is_single(&pidlist)) { - pid = pidlist.first; - switch (pid->type) { - case PTCACHE_TYPE_PARTICLES: - pset->edittype = PE_TYPE_PARTICLES; - break; - case PTCACHE_TYPE_SOFTBODY: - pset->edittype = PE_TYPE_SOFTBODY; - break; - case PTCACHE_TYPE_CLOTH: - pset->edittype = PE_TYPE_CLOTH; - break; - } - } - - for (pid = pidlist.first; pid; pid = pid->next) { - if (pset->edittype == PE_TYPE_PARTICLES && pid->type == PTCACHE_TYPE_PARTICLES) { - ParticleSystem *psys = pid->calldata; - - if (psys->flag & PSYS_CURRENT) { - if (psys->part && psys->part->type == PART_HAIR) { - if (psys->flag & PSYS_HAIR_DYNAMICS && psys->pointcache->flag & PTCACHE_BAKED) { - if (create && !psys->pointcache->edit) - PE_create_particle_edit(depsgraph, scene, ob, pid->cache, NULL); - edit = pid->cache->edit; - } - else { - if (create && !psys->edit) { - if (psys->flag & PSYS_HAIR_DONE) { - PE_create_particle_edit(depsgraph, scene, ob, NULL, psys); - } - } - edit = psys->edit; - } - } - else { - if (create && pid->cache->flag & PTCACHE_BAKED && !pid->cache->edit) - PE_create_particle_edit(depsgraph, scene, ob, pid->cache, psys); - edit = pid->cache->edit; - } - - break; - } - } - else if (pset->edittype == PE_TYPE_SOFTBODY && pid->type == PTCACHE_TYPE_SOFTBODY) { - if (create && pid->cache->flag & PTCACHE_BAKED && !pid->cache->edit) { - pset->flag |= PE_FADE_TIME; - // NICE TO HAVE but doesn't work: pset->brushtype = PE_BRUSH_COMB; - PE_create_particle_edit(depsgraph, scene, ob, pid->cache, NULL); - } - edit = pid->cache->edit; - break; - } - else if (pset->edittype == PE_TYPE_CLOTH && pid->type == PTCACHE_TYPE_CLOTH) { - if (create && pid->cache->flag & PTCACHE_BAKED && !pid->cache->edit) { - pset->flag |= PE_FADE_TIME; - // NICE TO HAVE but doesn't work: pset->brushtype = PE_BRUSH_COMB; - PE_create_particle_edit(depsgraph, scene, ob, pid->cache, NULL); - } - edit = pid->cache->edit; - break; - } - } - - if (edit) { - edit->pid = *pid; - if (edit->flags & PT_CACHE_EDIT_UPDATE_PARTICLE_FROM_EVAL) { - if (edit->psys != NULL) { - psys_copy_particles(edit->psys, edit->psys_eval); - pe_update_hair_particle_edit_pointers(edit); - } - edit->flags &= ~PT_CACHE_EDIT_UPDATE_PARTICLE_FROM_EVAL; - } - } - - BLI_freelistN(&pidlist); - - return edit; +static PTCacheEdit *pe_get_current(Depsgraph *depsgraph, Scene *scene, Object *ob, int create) +{ + ParticleEditSettings *pset = PE_settings(scene); + PTCacheEdit *edit = NULL; + ListBase pidlist; + PTCacheID *pid; + + if (pset == NULL || ob == NULL) + return NULL; + + pset->scene = scene; + pset->object = ob; + + BKE_ptcache_ids_from_object(&pidlist, ob, NULL, 0); + + /* in the case of only one editable thing, set pset->edittype accordingly */ + if (BLI_listbase_is_single(&pidlist)) { + pid = pidlist.first; + switch (pid->type) { + case PTCACHE_TYPE_PARTICLES: + pset->edittype = PE_TYPE_PARTICLES; + break; + case PTCACHE_TYPE_SOFTBODY: + pset->edittype = PE_TYPE_SOFTBODY; + break; + case PTCACHE_TYPE_CLOTH: + pset->edittype = PE_TYPE_CLOTH; + break; + } + } + + for (pid = pidlist.first; pid; pid = pid->next) { + if (pset->edittype == PE_TYPE_PARTICLES && pid->type == PTCACHE_TYPE_PARTICLES) { + ParticleSystem *psys = pid->calldata; + + if (psys->flag & PSYS_CURRENT) { + if (psys->part && psys->part->type == PART_HAIR) { + if (psys->flag & PSYS_HAIR_DYNAMICS && psys->pointcache->flag & PTCACHE_BAKED) { + if (create && !psys->pointcache->edit) + PE_create_particle_edit(depsgraph, scene, ob, pid->cache, NULL); + edit = pid->cache->edit; + } + else { + if (create && !psys->edit) { + if (psys->flag & PSYS_HAIR_DONE) { + PE_create_particle_edit(depsgraph, scene, ob, NULL, psys); + } + } + edit = psys->edit; + } + } + else { + if (create && pid->cache->flag & PTCACHE_BAKED && !pid->cache->edit) + PE_create_particle_edit(depsgraph, scene, ob, pid->cache, psys); + edit = pid->cache->edit; + } + + break; + } + } + else if (pset->edittype == PE_TYPE_SOFTBODY && pid->type == PTCACHE_TYPE_SOFTBODY) { + if (create && pid->cache->flag & PTCACHE_BAKED && !pid->cache->edit) { + pset->flag |= PE_FADE_TIME; + // NICE TO HAVE but doesn't work: pset->brushtype = PE_BRUSH_COMB; + PE_create_particle_edit(depsgraph, scene, ob, pid->cache, NULL); + } + edit = pid->cache->edit; + break; + } + else if (pset->edittype == PE_TYPE_CLOTH && pid->type == PTCACHE_TYPE_CLOTH) { + if (create && pid->cache->flag & PTCACHE_BAKED && !pid->cache->edit) { + pset->flag |= PE_FADE_TIME; + // NICE TO HAVE but doesn't work: pset->brushtype = PE_BRUSH_COMB; + PE_create_particle_edit(depsgraph, scene, ob, pid->cache, NULL); + } + edit = pid->cache->edit; + break; + } + } + + if (edit) { + edit->pid = *pid; + if (edit->flags & PT_CACHE_EDIT_UPDATE_PARTICLE_FROM_EVAL) { + if (edit->psys != NULL) { + psys_copy_particles(edit->psys, edit->psys_eval); + pe_update_hair_particle_edit_pointers(edit); + } + edit->flags &= ~PT_CACHE_EDIT_UPDATE_PARTICLE_FROM_EVAL; + } + } + + BLI_freelistN(&pidlist); + + return edit; } PTCacheEdit *PE_get_current(Scene *scene, Object *ob) { - return pe_get_current(NULL, scene, ob, 0); + return pe_get_current(NULL, scene, ob, 0); } PTCacheEdit *PE_create_current(Depsgraph *depsgraph, Scene *scene, Object *ob) { - return pe_get_current(depsgraph, scene, ob, 1); + return pe_get_current(depsgraph, scene, ob, 1); } void PE_current_changed(Depsgraph *depsgraph, Scene *scene, Object *ob) { - if (ob->mode == OB_MODE_PARTICLE_EDIT) { - PE_create_current(depsgraph, scene, ob); - } + if (ob->mode == OB_MODE_PARTICLE_EDIT) { + PE_create_current(depsgraph, scene, ob); + } } void PE_hide_keys_time(Scene *scene, PTCacheEdit *edit, float cfra) { - ParticleEditSettings *pset = PE_settings(scene); - POINT_P; KEY_K; - - - if (pset->flag & PE_FADE_TIME && pset->selectmode == SCE_SELECT_POINT) { - LOOP_POINTS { - LOOP_KEYS { - if (fabsf(cfra - *key->time) < pset->fade_frames) - key->flag &= ~PEK_HIDE; - else { - key->flag |= PEK_HIDE; - //key->flag &= ~PEK_SELECT; - } - } - } - } - else { - LOOP_POINTS { - LOOP_KEYS { - key->flag &= ~PEK_HIDE; - } - } - } + ParticleEditSettings *pset = PE_settings(scene); + POINT_P; + KEY_K; + + if (pset->flag & PE_FADE_TIME && pset->selectmode == SCE_SELECT_POINT) { + LOOP_POINTS + { + LOOP_KEYS + { + if (fabsf(cfra - *key->time) < pset->fade_frames) + key->flag &= ~PEK_HIDE; + else { + key->flag |= PEK_HIDE; + //key->flag &= ~PEK_SELECT; + } + } + } + } + else { + LOOP_POINTS + { + LOOP_KEYS + { + key->flag &= ~PEK_HIDE; + } + } + } } static int pe_x_mirror(Object *ob) { - if (ob->type == OB_MESH) - return (((Mesh *)ob->data)->editflag & ME_EDIT_MIRROR_X); + if (ob->type == OB_MESH) + return (((Mesh *)ob->data)->editflag & ME_EDIT_MIRROR_X); - return 0; + return 0; } /****************** common struct passed to callbacks ******************/ typedef struct PEData { - ViewContext vc; - - const bContext *context; - Main *bmain; - Scene *scene; - ViewLayer *view_layer; - Object *ob; - Mesh *mesh; - PTCacheEdit *edit; - BVHTreeFromMesh shape_bvh; - Depsgraph *depsgraph; - - RNG *rng; - - const int *mval; - const rcti *rect; - float rad; - float dval; - int select; - eSelectOp sel_op; - - float *dvec; - float combfac; - float pufffac; - float cutfac; - float smoothfac; - float weightfac; - float growfac; - int totrekey; - - int invert; - int tot; - float vec[3]; - - int select_action; - int select_toggle_action; - bool is_changed; + ViewContext vc; + + const bContext *context; + Main *bmain; + Scene *scene; + ViewLayer *view_layer; + Object *ob; + Mesh *mesh; + PTCacheEdit *edit; + BVHTreeFromMesh shape_bvh; + Depsgraph *depsgraph; + + RNG *rng; + + const int *mval; + const rcti *rect; + float rad; + float dval; + int select; + eSelectOp sel_op; + + float *dvec; + float combfac; + float pufffac; + float cutfac; + float smoothfac; + float weightfac; + float growfac; + int totrekey; + + int invert; + int tot; + float vec[3]; + + int select_action; + int select_toggle_action; + bool is_changed; } PEData; static void PE_set_data(bContext *C, PEData *data) { - memset(data, 0, sizeof(*data)); + memset(data, 0, sizeof(*data)); - data->context = C; - data->bmain = CTX_data_main(C); - data->scene = CTX_data_scene(C); - data->view_layer = CTX_data_view_layer(C); - data->ob = CTX_data_active_object(C); - data->depsgraph = CTX_data_depsgraph(C); - data->edit = PE_get_current(data->scene, data->ob); + data->context = C; + data->bmain = CTX_data_main(C); + data->scene = CTX_data_scene(C); + data->view_layer = CTX_data_view_layer(C); + data->ob = CTX_data_active_object(C); + data->depsgraph = CTX_data_depsgraph(C); + data->edit = PE_get_current(data->scene, data->ob); } static void PE_set_view3d_data(bContext *C, PEData *data) { - PE_set_data(C, data); + PE_set_data(C, data); - ED_view3d_viewcontext_init(C, &data->vc); + ED_view3d_viewcontext_init(C, &data->vc); - if (!XRAY_ENABLED(data->vc.v3d)) { - if (data->vc.v3d->flag & V3D_INVALID_BACKBUF) { - /* needed or else the draw matrix can be incorrect */ - view3d_operator_needs_opengl(C); + if (!XRAY_ENABLED(data->vc.v3d)) { + if (data->vc.v3d->flag & V3D_INVALID_BACKBUF) { + /* needed or else the draw matrix can be incorrect */ + view3d_operator_needs_opengl(C); - ED_view3d_backbuf_depth_validate(&data->vc); - /* we may need to force an update here by setting the rv3d as dirty - * for now it seems ok, but take care!: - * rv3d->depths->dirty = 1; */ - ED_view3d_depth_update(data->vc.ar); - } - } + ED_view3d_backbuf_depth_validate(&data->vc); + /* we may need to force an update here by setting the rv3d as dirty + * for now it seems ok, but take care!: + * rv3d->depths->dirty = 1; */ + ED_view3d_depth_update(data->vc.ar); + } + } } static bool PE_create_shape_tree(PEData *data, Object *shapeob) { - Mesh *mesh = BKE_object_get_evaluated_mesh(data->depsgraph, shapeob); + Mesh *mesh = BKE_object_get_evaluated_mesh(data->depsgraph, shapeob); - memset(&data->shape_bvh, 0, sizeof(data->shape_bvh)); + memset(&data->shape_bvh, 0, sizeof(data->shape_bvh)); - if (!mesh) { - return false; - } + if (!mesh) { + return false; + } - return (BKE_bvhtree_from_mesh_get(&data->shape_bvh, mesh, BVHTREE_FROM_LOOPTRI, 4) != NULL); + return (BKE_bvhtree_from_mesh_get(&data->shape_bvh, mesh, BVHTREE_FROM_LOOPTRI, 4) != NULL); } static void PE_free_shape_tree(PEData *data) { - free_bvhtree_from_mesh(&data->shape_bvh); + free_bvhtree_from_mesh(&data->shape_bvh); } static void PE_create_random_generator(PEData *data) { - uint rng_seed = (uint)(PIL_check_seconds_timer_i() & UINT_MAX); - rng_seed ^= POINTER_AS_UINT(data->ob); - rng_seed ^= POINTER_AS_UINT(data->edit); - data->rng = BLI_rng_new(rng_seed); + uint rng_seed = (uint)(PIL_check_seconds_timer_i() & UINT_MAX); + rng_seed ^= POINTER_AS_UINT(data->ob); + rng_seed ^= POINTER_AS_UINT(data->edit); + data->rng = BLI_rng_new(rng_seed); } static void PE_free_random_generator(PEData *data) { - if (data->rng != NULL) { - BLI_rng_free(data->rng); - data->rng = NULL; - } + if (data->rng != NULL) { + BLI_rng_free(data->rng); + data->rng = NULL; + } } /*************************** selection utilities *******************************/ static bool key_test_depth(const PEData *data, const float co[3], const int screen_co[2]) { - View3D *v3d = data->vc.v3d; - ViewDepths *vd = data->vc.rv3d->depths; - float depth; + View3D *v3d = data->vc.v3d; + ViewDepths *vd = data->vc.rv3d->depths; + float depth; - /* nothing to do */ - if (XRAY_ENABLED(v3d)) - return true; + /* nothing to do */ + if (XRAY_ENABLED(v3d)) + return true; - /* used to calculate here but all callers have the screen_co already, so pass as arg */ + /* used to calculate here but all callers have the screen_co already, so pass as arg */ #if 0 - if (ED_view3d_project_int_global(data->vc.ar, co, screen_co, - V3D_PROJ_TEST_CLIP_BB | V3D_PROJ_TEST_CLIP_WIN | V3D_PROJ_TEST_CLIP_NEAR) != V3D_PROJ_RET_OK) - { - return 0; - } + if (ED_view3d_project_int_global(data->vc.ar, co, screen_co, + V3D_PROJ_TEST_CLIP_BB | V3D_PROJ_TEST_CLIP_WIN | V3D_PROJ_TEST_CLIP_NEAR) != V3D_PROJ_RET_OK) + { + return 0; + } #endif - /* check if screen_co is within bounds because brush_cut uses out of screen coords */ - if (screen_co[0] >= 0 && screen_co[0] < vd->w && screen_co[1] >= 0 && screen_co[1] < vd->h) { - BLI_assert(vd && vd->depths); - /* we know its not clipped */ - depth = vd->depths[screen_co[1] * vd->w + screen_co[0]]; - } - else - return 0; + /* check if screen_co is within bounds because brush_cut uses out of screen coords */ + if (screen_co[0] >= 0 && screen_co[0] < vd->w && screen_co[1] >= 0 && screen_co[1] < vd->h) { + BLI_assert(vd && vd->depths); + /* we know its not clipped */ + depth = vd->depths[screen_co[1] * vd->w + screen_co[0]]; + } + else + return 0; - float win[3]; - ED_view3d_project(data->vc.ar, co, win); + float win[3]; + ED_view3d_project(data->vc.ar, co, win); - if (win[2] - 0.00001f > depth) - return 0; - else - return 1; + if (win[2] - 0.00001f > depth) + return 0; + else + return 1; } static bool key_inside_circle(const PEData *data, float rad, const float co[3], float *distance) { - float dx, dy, dist; - int screen_co[2]; + float dx, dy, dist; + int screen_co[2]; - /* TODO, should this check V3D_PROJ_TEST_CLIP_BB too? */ - if (ED_view3d_project_int_global(data->vc.ar, co, screen_co, V3D_PROJ_TEST_CLIP_WIN) != V3D_PROJ_RET_OK) { - return 0; - } + /* TODO, should this check V3D_PROJ_TEST_CLIP_BB too? */ + if (ED_view3d_project_int_global(data->vc.ar, co, screen_co, V3D_PROJ_TEST_CLIP_WIN) != + V3D_PROJ_RET_OK) { + return 0; + } - dx = data->mval[0] - screen_co[0]; - dy = data->mval[1] - screen_co[1]; - dist = sqrtf(dx * dx + dy * dy); + dx = data->mval[0] - screen_co[0]; + dy = data->mval[1] - screen_co[1]; + dist = sqrtf(dx * dx + dy * dy); - if (dist > rad) - return 0; + if (dist > rad) + return 0; - if (key_test_depth(data, co, screen_co)) { - if (distance) - *distance = dist; + if (key_test_depth(data, co, screen_co)) { + if (distance) + *distance = dist; - return 1; - } + return 1; + } - return 0; + return 0; } static bool key_inside_rect(PEData *data, const float co[3]) { - int screen_co[2]; + int screen_co[2]; - if (ED_view3d_project_int_global(data->vc.ar, co, screen_co, V3D_PROJ_TEST_CLIP_WIN) != V3D_PROJ_RET_OK) { - return 0; - } + if (ED_view3d_project_int_global(data->vc.ar, co, screen_co, V3D_PROJ_TEST_CLIP_WIN) != + V3D_PROJ_RET_OK) { + return 0; + } - if (screen_co[0] > data->rect->xmin && screen_co[0] < data->rect->xmax && - screen_co[1] > data->rect->ymin && screen_co[1] < data->rect->ymax) - { - return key_test_depth(data, co, screen_co); - } + if (screen_co[0] > data->rect->xmin && screen_co[0] < data->rect->xmax && + screen_co[1] > data->rect->ymin && screen_co[1] < data->rect->ymax) { + return key_test_depth(data, co, screen_co); + } - return 0; + return 0; } static bool key_inside_test(PEData *data, const float co[3]) { - if (data->mval) - return key_inside_circle(data, data->rad, co, NULL); - else - return key_inside_rect(data, co); + if (data->mval) + return key_inside_circle(data, data->rad, co, NULL); + else + return key_inside_rect(data, co); } static bool point_is_selected(PTCacheEditPoint *point) { - KEY_K; + KEY_K; - if (point->flag & PEP_HIDE) - return 0; + if (point->flag & PEP_HIDE) + return 0; - LOOP_SELECTED_KEYS { - return 1; - } + LOOP_SELECTED_KEYS + { + return 1; + } - return 0; + return 0; } /*************************** iterators *******************************/ -typedef void (*ForPointFunc)( - PEData *data, - int point_index); -typedef void (*ForHitPointFunc)( - PEData *data, - int point_index, - float mouse_distance); - -typedef void (*ForKeyFunc)( - PEData *data, - int point_index, - int key_index, - bool is_inside); - -typedef void (*ForKeyMatFunc)( - PEData *data, - float mat[4][4], - float imat[4][4], - int point_index, - int key_index, - PTCacheEditKey *key); -typedef void (*ForHitKeyMatFunc)( - PEData *data, - float mat[4][4], - float imat[4][4], - int point_index, - int key_index, - PTCacheEditKey *key, - float mouse_distance); +typedef void (*ForPointFunc)(PEData *data, int point_index); +typedef void (*ForHitPointFunc)(PEData *data, int point_index, float mouse_distance); + +typedef void (*ForKeyFunc)(PEData *data, int point_index, int key_index, bool is_inside); + +typedef void (*ForKeyMatFunc)(PEData *data, + float mat[4][4], + float imat[4][4], + int point_index, + int key_index, + PTCacheEditKey *key); +typedef void (*ForHitKeyMatFunc)(PEData *data, + float mat[4][4], + float imat[4][4], + int point_index, + int key_index, + PTCacheEditKey *key, + float mouse_distance); enum eParticleSelectFlag { - PSEL_NEAREST = (1 << 0), - PSEL_ALL_KEYS = (1 << 1), + PSEL_NEAREST = (1 << 0), + PSEL_ALL_KEYS = (1 << 1), }; static void for_mouse_hit_keys(PEData *data, ForKeyFunc func, const enum eParticleSelectFlag flag) { - ParticleEditSettings *pset = PE_settings(data->scene); - PTCacheEdit *edit = data->edit; - POINT_P; KEY_K; - int nearest_point, nearest_key; - float dist = data->rad; - - /* in path select mode we have no keys */ - if (pset->selectmode == SCE_SELECT_PATH) - return; - - nearest_point = -1; - nearest_key = -1; - - LOOP_VISIBLE_POINTS { - if (pset->selectmode == SCE_SELECT_END) { - if (point->totkey) { - /* only do end keys */ - key = point->keys + point->totkey - 1; - - if (flag & PSEL_NEAREST) { - if (key_inside_circle(data, dist, KEY_WCO, &dist)) { - nearest_point = p; - nearest_key = point->totkey - 1; - } - } - else { - const bool is_inside = key_inside_test(data, KEY_WCO); - if (is_inside || (flag & PSEL_ALL_KEYS)) { - func(data, p, point->totkey - 1, is_inside); - } - } - } - } - else { - /* do all keys */ - LOOP_VISIBLE_KEYS { - if (flag & PSEL_NEAREST) { - if (key_inside_circle(data, dist, KEY_WCO, &dist)) { - nearest_point = p; - nearest_key = k; - } - } - else { - const bool is_inside = key_inside_test(data, KEY_WCO); - if (is_inside || (flag & PSEL_ALL_KEYS)) { - func(data, p, k, is_inside); - } - } - } - } - } - - /* do nearest only */ - if (flag & PSEL_NEAREST) { - if (nearest_point != -1) { - func(data, nearest_point, nearest_key, true); - } - } + ParticleEditSettings *pset = PE_settings(data->scene); + PTCacheEdit *edit = data->edit; + POINT_P; + KEY_K; + int nearest_point, nearest_key; + float dist = data->rad; + + /* in path select mode we have no keys */ + if (pset->selectmode == SCE_SELECT_PATH) + return; + + nearest_point = -1; + nearest_key = -1; + + LOOP_VISIBLE_POINTS + { + if (pset->selectmode == SCE_SELECT_END) { + if (point->totkey) { + /* only do end keys */ + key = point->keys + point->totkey - 1; + + if (flag & PSEL_NEAREST) { + if (key_inside_circle(data, dist, KEY_WCO, &dist)) { + nearest_point = p; + nearest_key = point->totkey - 1; + } + } + else { + const bool is_inside = key_inside_test(data, KEY_WCO); + if (is_inside || (flag & PSEL_ALL_KEYS)) { + func(data, p, point->totkey - 1, is_inside); + } + } + } + } + else { + /* do all keys */ + LOOP_VISIBLE_KEYS + { + if (flag & PSEL_NEAREST) { + if (key_inside_circle(data, dist, KEY_WCO, &dist)) { + nearest_point = p; + nearest_key = k; + } + } + else { + const bool is_inside = key_inside_test(data, KEY_WCO); + if (is_inside || (flag & PSEL_ALL_KEYS)) { + func(data, p, k, is_inside); + } + } + } + } + } + + /* do nearest only */ + if (flag & PSEL_NEAREST) { + if (nearest_point != -1) { + func(data, nearest_point, nearest_key, true); + } + } } static void foreach_mouse_hit_point(PEData *data, ForHitPointFunc func, int selected) { - ParticleEditSettings *pset = PE_settings(data->scene); - PTCacheEdit *edit = data->edit; - POINT_P; KEY_K; - - /* all is selected in path mode */ - if (pset->selectmode == SCE_SELECT_PATH) - selected = 0; - - LOOP_VISIBLE_POINTS { - if (pset->selectmode == SCE_SELECT_END) { - if (point->totkey) { - /* only do end keys */ - key = point->keys + point->totkey - 1; - - if (selected == 0 || key->flag & PEK_SELECT) { - float mouse_distance; - if (key_inside_circle(data, data->rad, KEY_WCO, &mouse_distance)) { - func(data, p, mouse_distance); - } - } - } - } - else { - /* do all keys */ - LOOP_VISIBLE_KEYS { - if (selected == 0 || key->flag & PEK_SELECT) { - float mouse_distance; - if (key_inside_circle(data, data->rad, KEY_WCO, &mouse_distance)) { - func(data, p, mouse_distance); - break; - } - } - } - } - } + ParticleEditSettings *pset = PE_settings(data->scene); + PTCacheEdit *edit = data->edit; + POINT_P; + KEY_K; + + /* all is selected in path mode */ + if (pset->selectmode == SCE_SELECT_PATH) + selected = 0; + + LOOP_VISIBLE_POINTS + { + if (pset->selectmode == SCE_SELECT_END) { + if (point->totkey) { + /* only do end keys */ + key = point->keys + point->totkey - 1; + + if (selected == 0 || key->flag & PEK_SELECT) { + float mouse_distance; + if (key_inside_circle(data, data->rad, KEY_WCO, &mouse_distance)) { + func(data, p, mouse_distance); + } + } + } + } + else { + /* do all keys */ + LOOP_VISIBLE_KEYS + { + if (selected == 0 || key->flag & PEK_SELECT) { + float mouse_distance; + if (key_inside_circle(data, data->rad, KEY_WCO, &mouse_distance)) { + func(data, p, mouse_distance); + break; + } + } + } + } + } } typedef struct KeyIterData { - PEData *data; - PTCacheEdit *edit; - int selected; - ForHitKeyMatFunc func; + PEData *data; + PTCacheEdit *edit; + int selected; + ForHitKeyMatFunc func; } KeyIterData; -static void foreach_mouse_hit_key_iter( - void *__restrict iter_data_v, - const int iter, - const ParallelRangeTLS *__restrict UNUSED(tls)) -{ - KeyIterData *iter_data = (KeyIterData *)iter_data_v; - PEData *data = iter_data->data; - PTCacheEdit *edit = data->edit; - PTCacheEditPoint *point = &edit->points[iter]; - if (point->flag & PEP_HIDE) { - return; - } - ParticleSystem *psys = edit->psys; - ParticleSystemModifierData *psmd_eval = iter_data->edit->psmd_eval; - ParticleEditSettings *pset = PE_settings(data->scene); - const int selected = iter_data->selected; - float mat[4][4], imat[4][4]; - unit_m4(mat); - unit_m4(imat); - if (pset->selectmode == SCE_SELECT_END) { - if (point->totkey) { - /* only do end keys */ - PTCacheEditKey *key = point->keys + point->totkey - 1; - - if (selected == 0 || key->flag & PEK_SELECT) { - float mouse_distance; - if (key_inside_circle(data, data->rad, KEY_WCO, &mouse_distance)) { - if (edit->psys && !(edit->psys->flag & PSYS_GLOBAL_HAIR)) { - psys_mat_hair_to_global(data->ob, psmd_eval->mesh_final, psys->part->from, psys->particles + iter, mat); - invert_m4_m4(imat, mat); - } - iter_data->func(data, mat, imat, iter, point->totkey - 1, key, mouse_distance); - } - } - } - } - else { - /* do all keys */ - PTCacheEditKey *key; - int k; - LOOP_VISIBLE_KEYS { - if (selected == 0 || key->flag & PEK_SELECT) { - float mouse_distance; - if (key_inside_circle(data, data->rad, KEY_WCO, &mouse_distance)) { - if (edit->psys && !(edit->psys->flag & PSYS_GLOBAL_HAIR)) { - psys_mat_hair_to_global(data->ob, psmd_eval->mesh_final, psys->part->from, psys->particles + iter, mat); - invert_m4_m4(imat, mat); - } - iter_data->func(data, mat, imat, iter, k, key, mouse_distance); - } - } - } - } +static void foreach_mouse_hit_key_iter(void *__restrict iter_data_v, + const int iter, + const ParallelRangeTLS *__restrict UNUSED(tls)) +{ + KeyIterData *iter_data = (KeyIterData *)iter_data_v; + PEData *data = iter_data->data; + PTCacheEdit *edit = data->edit; + PTCacheEditPoint *point = &edit->points[iter]; + if (point->flag & PEP_HIDE) { + return; + } + ParticleSystem *psys = edit->psys; + ParticleSystemModifierData *psmd_eval = iter_data->edit->psmd_eval; + ParticleEditSettings *pset = PE_settings(data->scene); + const int selected = iter_data->selected; + float mat[4][4], imat[4][4]; + unit_m4(mat); + unit_m4(imat); + if (pset->selectmode == SCE_SELECT_END) { + if (point->totkey) { + /* only do end keys */ + PTCacheEditKey *key = point->keys + point->totkey - 1; + + if (selected == 0 || key->flag & PEK_SELECT) { + float mouse_distance; + if (key_inside_circle(data, data->rad, KEY_WCO, &mouse_distance)) { + if (edit->psys && !(edit->psys->flag & PSYS_GLOBAL_HAIR)) { + psys_mat_hair_to_global( + data->ob, psmd_eval->mesh_final, psys->part->from, psys->particles + iter, mat); + invert_m4_m4(imat, mat); + } + iter_data->func(data, mat, imat, iter, point->totkey - 1, key, mouse_distance); + } + } + } + } + else { + /* do all keys */ + PTCacheEditKey *key; + int k; + LOOP_VISIBLE_KEYS + { + if (selected == 0 || key->flag & PEK_SELECT) { + float mouse_distance; + if (key_inside_circle(data, data->rad, KEY_WCO, &mouse_distance)) { + if (edit->psys && !(edit->psys->flag & PSYS_GLOBAL_HAIR)) { + psys_mat_hair_to_global( + data->ob, psmd_eval->mesh_final, psys->part->from, psys->particles + iter, mat); + invert_m4_m4(imat, mat); + } + iter_data->func(data, mat, imat, iter, k, key, mouse_distance); + } + } + } + } } static void foreach_mouse_hit_key(PEData *data, ForHitKeyMatFunc func, int selected) { - PTCacheEdit *edit = data->edit; - ParticleEditSettings *pset = PE_settings(data->scene); - /* all is selected in path mode */ - if (pset->selectmode == SCE_SELECT_PATH) { - selected = 0; - } + PTCacheEdit *edit = data->edit; + ParticleEditSettings *pset = PE_settings(data->scene); + /* all is selected in path mode */ + if (pset->selectmode == SCE_SELECT_PATH) { + selected = 0; + } - KeyIterData iter_data; - iter_data.data = data; - iter_data.edit = edit; - iter_data.selected = selected; - iter_data.func = func; + KeyIterData iter_data; + iter_data.data = data; + iter_data.edit = edit; + iter_data.selected = selected; + iter_data.func = func; - ParallelRangeSettings settings; - BLI_parallel_range_settings_defaults(&settings); - settings.scheduling_mode = TASK_SCHEDULING_DYNAMIC; - BLI_task_parallel_range(0, edit->totpoint, &iter_data, foreach_mouse_hit_key_iter, &settings); + ParallelRangeSettings settings; + BLI_parallel_range_settings_defaults(&settings); + settings.scheduling_mode = TASK_SCHEDULING_DYNAMIC; + BLI_task_parallel_range(0, edit->totpoint, &iter_data, foreach_mouse_hit_key_iter, &settings); } static void foreach_selected_point(PEData *data, ForPointFunc func) { - PTCacheEdit *edit = data->edit; - POINT_P; + PTCacheEdit *edit = data->edit; + POINT_P; - LOOP_SELECTED_POINTS { - func(data, p); - } + LOOP_SELECTED_POINTS + { + func(data, p); + } } static void foreach_selected_key(PEData *data, ForKeyFunc func) { - PTCacheEdit *edit = data->edit; - POINT_P; KEY_K; + PTCacheEdit *edit = data->edit; + POINT_P; + KEY_K; - LOOP_VISIBLE_POINTS { - LOOP_SELECTED_KEYS { - func(data, p, k, true); - } - } + LOOP_VISIBLE_POINTS + { + LOOP_SELECTED_KEYS + { + func(data, p, k, true); + } + } } static void foreach_point(PEData *data, ForPointFunc func) { - PTCacheEdit *edit = data->edit; - POINT_P; + PTCacheEdit *edit = data->edit; + POINT_P; - LOOP_POINTS { - func(data, p); - } + LOOP_POINTS + { + func(data, p); + } } static int count_selected_keys(Scene *scene, PTCacheEdit *edit) { - ParticleEditSettings *pset = PE_settings(scene); - POINT_P; KEY_K; - int sel = 0; - - LOOP_VISIBLE_POINTS { - if (pset->selectmode == SCE_SELECT_POINT) { - LOOP_SELECTED_KEYS { - sel++; - } - } - else if (pset->selectmode == SCE_SELECT_END) { - if (point->totkey) { - key = point->keys + point->totkey - 1; - if (key->flag & PEK_SELECT) - sel++; - } - } - } - - return sel; + ParticleEditSettings *pset = PE_settings(scene); + POINT_P; + KEY_K; + int sel = 0; + + LOOP_VISIBLE_POINTS + { + if (pset->selectmode == SCE_SELECT_POINT) { + LOOP_SELECTED_KEYS + { + sel++; + } + } + else if (pset->selectmode == SCE_SELECT_END) { + if (point->totkey) { + key = point->keys + point->totkey - 1; + if (key->flag & PEK_SELECT) + sel++; + } + } + } + + return sel; } /************************************************/ -/* Particle Edit Mirroring */ +/* Particle Edit Mirroring */ /************************************************/ static void PE_update_mirror_cache(Object *ob, ParticleSystem *psys) { - PTCacheEdit *edit; - ParticleSystemModifierData *psmd_eval; - KDTree_3d *tree; - KDTreeNearest_3d nearest; - HairKey *key; - PARTICLE_P; - float mat[4][4], co[3]; - int index, totpart; - - edit = psys->edit; - psmd_eval = edit->psmd_eval; - totpart = psys->totpart; - - if (!psmd_eval->mesh_final) - return; - - tree = BLI_kdtree_3d_new(totpart); - - /* insert particles into kd tree */ - LOOP_PARTICLES { - key = pa->hair; - psys_mat_hair_to_orco(ob, psmd_eval->mesh_final, psys->part->from, pa, mat); - copy_v3_v3(co, key->co); - mul_m4_v3(mat, co); - BLI_kdtree_3d_insert(tree, p, co); - } - - BLI_kdtree_3d_balance(tree); - - /* lookup particles and set in mirror cache */ - if (!edit->mirror_cache) - edit->mirror_cache = MEM_callocN(sizeof(int) * totpart, "PE mirror cache"); - - LOOP_PARTICLES { - key = pa->hair; - psys_mat_hair_to_orco(ob, psmd_eval->mesh_final, psys->part->from, pa, mat); - copy_v3_v3(co, key->co); - mul_m4_v3(mat, co); - co[0] = -co[0]; - - index = BLI_kdtree_3d_find_nearest(tree, co, &nearest); - - /* this needs a custom threshold still, duplicated for editmode mirror */ - if (index != -1 && index != p && (nearest.dist <= 0.0002f)) - edit->mirror_cache[p] = index; - else - edit->mirror_cache[p] = -1; - } - - /* make sure mirrors are in two directions */ - LOOP_PARTICLES { - if (edit->mirror_cache[p]) { - index = edit->mirror_cache[p]; - if (edit->mirror_cache[index] != p) - edit->mirror_cache[p] = -1; - } - } - - BLI_kdtree_3d_free(tree); -} - -static void PE_mirror_particle(Object *ob, Mesh *mesh, ParticleSystem *psys, ParticleData *pa, ParticleData *mpa) -{ - HairKey *hkey, *mhkey; - PTCacheEditPoint *point, *mpoint; - PTCacheEditKey *key, *mkey; - PTCacheEdit *edit; - float mat[4][4], mmat[4][4], immat[4][4]; - int i, mi, k; - - edit = psys->edit; - i = pa - psys->particles; - - /* find mirrored particle if needed */ - if (!mpa) { - if (!edit->mirror_cache) - PE_update_mirror_cache(ob, psys); - - if (!edit->mirror_cache) - return; /* something went wrong! */ - - mi = edit->mirror_cache[i]; - if (mi == -1) - return; - mpa = psys->particles + mi; - } - else - mi = mpa - psys->particles; - - point = edit->points + i; - mpoint = edit->points + mi; - - /* make sure they have the same amount of keys */ - if (pa->totkey != mpa->totkey) { - if (mpa->hair) MEM_freeN(mpa->hair); - if (mpoint->keys) MEM_freeN(mpoint->keys); - - mpa->hair = MEM_dupallocN(pa->hair); - mpa->totkey = pa->totkey; - mpoint->keys = MEM_dupallocN(point->keys); - mpoint->totkey = point->totkey; - - mhkey = mpa->hair; - mkey = mpoint->keys; - for (k = 0; k < mpa->totkey; k++, mkey++, mhkey++) { - mkey->co = mhkey->co; - mkey->time = &mhkey->time; - mkey->flag &= ~PEK_SELECT; - } - } - - /* mirror positions and tags */ - psys_mat_hair_to_orco(ob, mesh, psys->part->from, pa, mat); - psys_mat_hair_to_orco(ob, mesh, psys->part->from, mpa, mmat); - invert_m4_m4(immat, mmat); - - hkey = pa->hair; - mhkey = mpa->hair; - key = point->keys; - mkey = mpoint->keys; - for (k = 0; k < pa->totkey; k++, hkey++, mhkey++, key++, mkey++) { - copy_v3_v3(mhkey->co, hkey->co); - mul_m4_v3(mat, mhkey->co); - mhkey->co[0] = -mhkey->co[0]; - mul_m4_v3(immat, mhkey->co); - - if (key->flag & PEK_TAG) - mkey->flag |= PEK_TAG; - - mkey->length = key->length; - } - - if (point->flag & PEP_TAG) - mpoint->flag |= PEP_TAG; - if (point->flag & PEP_EDIT_RECALC) - mpoint->flag |= PEP_EDIT_RECALC; + PTCacheEdit *edit; + ParticleSystemModifierData *psmd_eval; + KDTree_3d *tree; + KDTreeNearest_3d nearest; + HairKey *key; + PARTICLE_P; + float mat[4][4], co[3]; + int index, totpart; + + edit = psys->edit; + psmd_eval = edit->psmd_eval; + totpart = psys->totpart; + + if (!psmd_eval->mesh_final) + return; + + tree = BLI_kdtree_3d_new(totpart); + + /* insert particles into kd tree */ + LOOP_PARTICLES + { + key = pa->hair; + psys_mat_hair_to_orco(ob, psmd_eval->mesh_final, psys->part->from, pa, mat); + copy_v3_v3(co, key->co); + mul_m4_v3(mat, co); + BLI_kdtree_3d_insert(tree, p, co); + } + + BLI_kdtree_3d_balance(tree); + + /* lookup particles and set in mirror cache */ + if (!edit->mirror_cache) + edit->mirror_cache = MEM_callocN(sizeof(int) * totpart, "PE mirror cache"); + + LOOP_PARTICLES + { + key = pa->hair; + psys_mat_hair_to_orco(ob, psmd_eval->mesh_final, psys->part->from, pa, mat); + copy_v3_v3(co, key->co); + mul_m4_v3(mat, co); + co[0] = -co[0]; + + index = BLI_kdtree_3d_find_nearest(tree, co, &nearest); + + /* this needs a custom threshold still, duplicated for editmode mirror */ + if (index != -1 && index != p && (nearest.dist <= 0.0002f)) + edit->mirror_cache[p] = index; + else + edit->mirror_cache[p] = -1; + } + + /* make sure mirrors are in two directions */ + LOOP_PARTICLES + { + if (edit->mirror_cache[p]) { + index = edit->mirror_cache[p]; + if (edit->mirror_cache[index] != p) + edit->mirror_cache[p] = -1; + } + } + + BLI_kdtree_3d_free(tree); +} + +static void PE_mirror_particle( + Object *ob, Mesh *mesh, ParticleSystem *psys, ParticleData *pa, ParticleData *mpa) +{ + HairKey *hkey, *mhkey; + PTCacheEditPoint *point, *mpoint; + PTCacheEditKey *key, *mkey; + PTCacheEdit *edit; + float mat[4][4], mmat[4][4], immat[4][4]; + int i, mi, k; + + edit = psys->edit; + i = pa - psys->particles; + + /* find mirrored particle if needed */ + if (!mpa) { + if (!edit->mirror_cache) + PE_update_mirror_cache(ob, psys); + + if (!edit->mirror_cache) + return; /* something went wrong! */ + + mi = edit->mirror_cache[i]; + if (mi == -1) + return; + mpa = psys->particles + mi; + } + else + mi = mpa - psys->particles; + + point = edit->points + i; + mpoint = edit->points + mi; + + /* make sure they have the same amount of keys */ + if (pa->totkey != mpa->totkey) { + if (mpa->hair) + MEM_freeN(mpa->hair); + if (mpoint->keys) + MEM_freeN(mpoint->keys); + + mpa->hair = MEM_dupallocN(pa->hair); + mpa->totkey = pa->totkey; + mpoint->keys = MEM_dupallocN(point->keys); + mpoint->totkey = point->totkey; + + mhkey = mpa->hair; + mkey = mpoint->keys; + for (k = 0; k < mpa->totkey; k++, mkey++, mhkey++) { + mkey->co = mhkey->co; + mkey->time = &mhkey->time; + mkey->flag &= ~PEK_SELECT; + } + } + + /* mirror positions and tags */ + psys_mat_hair_to_orco(ob, mesh, psys->part->from, pa, mat); + psys_mat_hair_to_orco(ob, mesh, psys->part->from, mpa, mmat); + invert_m4_m4(immat, mmat); + + hkey = pa->hair; + mhkey = mpa->hair; + key = point->keys; + mkey = mpoint->keys; + for (k = 0; k < pa->totkey; k++, hkey++, mhkey++, key++, mkey++) { + copy_v3_v3(mhkey->co, hkey->co); + mul_m4_v3(mat, mhkey->co); + mhkey->co[0] = -mhkey->co[0]; + mul_m4_v3(immat, mhkey->co); + + if (key->flag & PEK_TAG) + mkey->flag |= PEK_TAG; + + mkey->length = key->length; + } + + if (point->flag & PEP_TAG) + mpoint->flag |= PEP_TAG; + if (point->flag & PEP_EDIT_RECALC) + mpoint->flag |= PEP_EDIT_RECALC; } static void PE_apply_mirror(Object *ob, ParticleSystem *psys) { - PTCacheEdit *edit; - ParticleSystemModifierData *psmd_eval; - POINT_P; + PTCacheEdit *edit; + ParticleSystemModifierData *psmd_eval; + POINT_P; - if (!psys) - return; + if (!psys) + return; - edit = psys->edit; - psmd_eval = edit->psmd_eval; + edit = psys->edit; + psmd_eval = edit->psmd_eval; - if (!psmd_eval->mesh_final) - return; + if (!psmd_eval->mesh_final) + return; - if (!edit->mirror_cache) - PE_update_mirror_cache(ob, psys); + if (!edit->mirror_cache) + PE_update_mirror_cache(ob, psys); - if (!edit->mirror_cache) - return; /* something went wrong */ + if (!edit->mirror_cache) + return; /* something went wrong */ - /* we delay settings the PARS_EDIT_RECALC for mirrored particles - * to avoid doing mirror twice */ - LOOP_POINTS { - if (point->flag & PEP_EDIT_RECALC) { - PE_mirror_particle(ob, psmd_eval->mesh_final, psys, psys->particles + p, NULL); + /* we delay settings the PARS_EDIT_RECALC for mirrored particles + * to avoid doing mirror twice */ + LOOP_POINTS + { + if (point->flag & PEP_EDIT_RECALC) { + PE_mirror_particle(ob, psmd_eval->mesh_final, psys, psys->particles + p, NULL); - if (edit->mirror_cache[p] != -1) - edit->points[edit->mirror_cache[p]].flag &= ~PEP_EDIT_RECALC; - } - } + if (edit->mirror_cache[p] != -1) + edit->points[edit->mirror_cache[p]].flag &= ~PEP_EDIT_RECALC; + } + } - LOOP_POINTS { - if (point->flag & PEP_EDIT_RECALC) - if (edit->mirror_cache[p] != -1) - edit->points[edit->mirror_cache[p]].flag |= PEP_EDIT_RECALC; - } + LOOP_POINTS + { + if (point->flag & PEP_EDIT_RECALC) + if (edit->mirror_cache[p] != -1) + edit->points[edit->mirror_cache[p]].flag |= PEP_EDIT_RECALC; + } } /************************************************/ -/* Edit Calculation */ +/* Edit Calculation */ /************************************************/ typedef struct DeflectEmitterIter { - Object *object; - ParticleSystem *psys; - PTCacheEdit *edit; - float dist; - float emitterdist; + Object *object; + ParticleSystem *psys; + PTCacheEdit *edit; + float dist; + float emitterdist; } DeflectEmitterIter; -static void deflect_emitter_iter( - void *__restrict iter_data_v, - const int iter, - const ParallelRangeTLS *__restrict UNUSED(tls)) -{ - DeflectEmitterIter *iter_data = (DeflectEmitterIter *)iter_data_v; - PTCacheEdit *edit = iter_data->edit; - PTCacheEditPoint *point = &edit->points[iter]; - if ((point->flag & PEP_EDIT_RECALC) == 0) { - return; - } - Object *object = iter_data->object; - ParticleSystem *psys = iter_data->psys; - ParticleSystemModifierData *psmd_eval = iter_data->edit->psmd_eval; - PTCacheEditKey *key; - int k; - float hairimat[4][4], hairmat[4][4]; - int index; - float *vec, *nor, dvec[3], dot, dist_1st = 0.0f; - const float dist = iter_data->dist; - const float emitterdist = iter_data->emitterdist; - psys_mat_hair_to_object(object, - psmd_eval->mesh_final, - psys->part->from, - psys->particles + iter, - hairmat); - - LOOP_KEYS { - mul_m4_v3(hairmat, key->co); - } - - LOOP_KEYS { - if (k == 0) { - dist_1st = len_v3v3((key + 1)->co, key->co); - dist_1st *= dist * emitterdist; - } - else { - index = BLI_kdtree_3d_find_nearest(edit->emitter_field, key->co, NULL); - - vec = edit->emitter_cosnos + index * 6; - nor = vec + 3; - - sub_v3_v3v3(dvec, key->co, vec); - - dot = dot_v3v3(dvec, nor); - copy_v3_v3(dvec, nor); - - if (dot > 0.0f) { - if (dot < dist_1st) { - normalize_v3(dvec); - mul_v3_fl(dvec, dist_1st - dot); - add_v3_v3(key->co, dvec); - } - } - else { - normalize_v3(dvec); - mul_v3_fl(dvec, dist_1st - dot); - add_v3_v3(key->co, dvec); - } - if (k == 1) { - dist_1st *= 1.3333f; - } - } - } - - invert_m4_m4(hairimat, hairmat); - - LOOP_KEYS { - mul_m4_v3(hairimat, key->co); - } +static void deflect_emitter_iter(void *__restrict iter_data_v, + const int iter, + const ParallelRangeTLS *__restrict UNUSED(tls)) +{ + DeflectEmitterIter *iter_data = (DeflectEmitterIter *)iter_data_v; + PTCacheEdit *edit = iter_data->edit; + PTCacheEditPoint *point = &edit->points[iter]; + if ((point->flag & PEP_EDIT_RECALC) == 0) { + return; + } + Object *object = iter_data->object; + ParticleSystem *psys = iter_data->psys; + ParticleSystemModifierData *psmd_eval = iter_data->edit->psmd_eval; + PTCacheEditKey *key; + int k; + float hairimat[4][4], hairmat[4][4]; + int index; + float *vec, *nor, dvec[3], dot, dist_1st = 0.0f; + const float dist = iter_data->dist; + const float emitterdist = iter_data->emitterdist; + psys_mat_hair_to_object( + object, psmd_eval->mesh_final, psys->part->from, psys->particles + iter, hairmat); + + LOOP_KEYS + { + mul_m4_v3(hairmat, key->co); + } + + LOOP_KEYS + { + if (k == 0) { + dist_1st = len_v3v3((key + 1)->co, key->co); + dist_1st *= dist * emitterdist; + } + else { + index = BLI_kdtree_3d_find_nearest(edit->emitter_field, key->co, NULL); + + vec = edit->emitter_cosnos + index * 6; + nor = vec + 3; + + sub_v3_v3v3(dvec, key->co, vec); + + dot = dot_v3v3(dvec, nor); + copy_v3_v3(dvec, nor); + + if (dot > 0.0f) { + if (dot < dist_1st) { + normalize_v3(dvec); + mul_v3_fl(dvec, dist_1st - dot); + add_v3_v3(key->co, dvec); + } + } + else { + normalize_v3(dvec); + mul_v3_fl(dvec, dist_1st - dot); + add_v3_v3(key->co, dvec); + } + if (k == 1) { + dist_1st *= 1.3333f; + } + } + } + + invert_m4_m4(hairimat, hairmat); + + LOOP_KEYS + { + mul_m4_v3(hairimat, key->co); + } } /* tries to stop edited particles from going through the emitter's surface */ static void pe_deflect_emitter(Scene *scene, Object *ob, PTCacheEdit *edit) { - ParticleEditSettings *pset = PE_settings(scene); - ParticleSystem *psys; - const float dist = ED_view3d_select_dist_px() * 0.01f; + ParticleEditSettings *pset = PE_settings(scene); + ParticleSystem *psys; + const float dist = ED_view3d_select_dist_px() * 0.01f; - if (edit == NULL || edit->psys == NULL || - (pset->flag & PE_DEFLECT_EMITTER) == 0 || - (edit->psys->flag & PSYS_GLOBAL_HAIR)) - { - return; - } + if (edit == NULL || edit->psys == NULL || (pset->flag & PE_DEFLECT_EMITTER) == 0 || + (edit->psys->flag & PSYS_GLOBAL_HAIR)) { + return; + } - psys = edit->psys; + psys = edit->psys; - if (!edit->psmd_eval->mesh_final) { - return; - } + if (!edit->psmd_eval->mesh_final) { + return; + } - DeflectEmitterIter iter_data; - iter_data.object = ob; - iter_data.psys = psys; - iter_data.edit = edit; - iter_data.dist = dist; - iter_data.emitterdist = pset->emitterdist; + DeflectEmitterIter iter_data; + iter_data.object = ob; + iter_data.psys = psys; + iter_data.edit = edit; + iter_data.dist = dist; + iter_data.emitterdist = pset->emitterdist; - ParallelRangeSettings settings; - BLI_parallel_range_settings_defaults(&settings); - settings.scheduling_mode = TASK_SCHEDULING_DYNAMIC; - BLI_task_parallel_range(0, edit->totpoint, &iter_data, deflect_emitter_iter, &settings); + ParallelRangeSettings settings; + BLI_parallel_range_settings_defaults(&settings); + settings.scheduling_mode = TASK_SCHEDULING_DYNAMIC; + BLI_task_parallel_range(0, edit->totpoint, &iter_data, deflect_emitter_iter, &settings); } typedef struct ApplyLengthsIterData { - PTCacheEdit *edit; + PTCacheEdit *edit; } ApplyLengthsIterData; -static void apply_lengths_iter( - void *__restrict iter_data_v, - const int iter, - const ParallelRangeTLS *__restrict UNUSED(tls)) -{ - ApplyLengthsIterData *iter_data = (ApplyLengthsIterData *)iter_data_v; - PTCacheEdit *edit = iter_data->edit; - PTCacheEditPoint *point = &edit->points[iter]; - if ((point->flag & PEP_EDIT_RECALC) == 0) { - return; - } - PTCacheEditKey *key; - int k; - LOOP_KEYS { - if (k) { - float dv1[3]; - sub_v3_v3v3(dv1, key->co, (key - 1)->co); - normalize_v3(dv1); - mul_v3_fl(dv1, (key - 1)->length); - add_v3_v3v3(key->co, (key - 1)->co, dv1); - } - } +static void apply_lengths_iter(void *__restrict iter_data_v, + const int iter, + const ParallelRangeTLS *__restrict UNUSED(tls)) +{ + ApplyLengthsIterData *iter_data = (ApplyLengthsIterData *)iter_data_v; + PTCacheEdit *edit = iter_data->edit; + PTCacheEditPoint *point = &edit->points[iter]; + if ((point->flag & PEP_EDIT_RECALC) == 0) { + return; + } + PTCacheEditKey *key; + int k; + LOOP_KEYS + { + if (k) { + float dv1[3]; + sub_v3_v3v3(dv1, key->co, (key - 1)->co); + normalize_v3(dv1); + mul_v3_fl(dv1, (key - 1)->length); + add_v3_v3v3(key->co, (key - 1)->co, dv1); + } + } } /* force set distances between neighboring keys */ static void PE_apply_lengths(Scene *scene, PTCacheEdit *edit) { - ParticleEditSettings *pset = PE_settings(scene); + ParticleEditSettings *pset = PE_settings(scene); - if (edit == 0 || (pset->flag & PE_KEEP_LENGTHS) == 0) - return; + if (edit == 0 || (pset->flag & PE_KEEP_LENGTHS) == 0) + return; - if (edit->psys && edit->psys->flag & PSYS_GLOBAL_HAIR) - return; + if (edit->psys && edit->psys->flag & PSYS_GLOBAL_HAIR) + return; - ApplyLengthsIterData iter_data; - iter_data.edit = edit; + ApplyLengthsIterData iter_data; + iter_data.edit = edit; - ParallelRangeSettings settings; - BLI_parallel_range_settings_defaults(&settings); - settings.scheduling_mode = TASK_SCHEDULING_DYNAMIC; - BLI_task_parallel_range(0, edit->totpoint, &iter_data, apply_lengths_iter, &settings); + ParallelRangeSettings settings; + BLI_parallel_range_settings_defaults(&settings); + settings.scheduling_mode = TASK_SCHEDULING_DYNAMIC; + BLI_task_parallel_range(0, edit->totpoint, &iter_data, apply_lengths_iter, &settings); } typedef struct IterateLengthsIterData { - PTCacheEdit *edit; - ParticleEditSettings *pset; + PTCacheEdit *edit; + ParticleEditSettings *pset; } IterateLengthsIterData; -static void iterate_lengths_iter( - void *__restrict iter_data_v, - const int iter, - const ParallelRangeTLS *__restrict UNUSED(tls)) -{ - IterateLengthsIterData *iter_data = (IterateLengthsIterData *)iter_data_v; - PTCacheEdit *edit = iter_data->edit; - PTCacheEditPoint *point = &edit->points[iter]; - if ((point->flag & PEP_EDIT_RECALC) == 0) { - return; - } - ParticleEditSettings *pset = iter_data->pset; - float tlen; - float dv0[3] = {0.0f, 0.0f, 0.0f}; - float dv1[3] = {0.0f, 0.0f, 0.0f}; - float dv2[3] = {0.0f, 0.0f, 0.0f}; - for (int j = 1; j < point->totkey; j++) { - PTCacheEditKey *key; - int k; - float mul = 1.0f / (float)point->totkey; - if (pset->flag & PE_LOCK_FIRST) { - key = point->keys + 1; - k = 1; - dv1[0] = dv1[1] = dv1[2] = 0.0; - } - else { - key = point->keys; - k = 0; - dv0[0] = dv0[1] = dv0[2] = 0.0; - } - - for (; k < point->totkey; k++, key++) { - if (k) { - sub_v3_v3v3(dv0, (key - 1)->co, key->co); - tlen = normalize_v3(dv0); - mul_v3_fl(dv0, (mul * (tlen - (key - 1)->length))); - } - if (k < point->totkey - 1) { - sub_v3_v3v3(dv2, (key + 1)->co, key->co); - tlen = normalize_v3(dv2); - mul_v3_fl(dv2, mul * (tlen - key->length)); - } - if (k) { - add_v3_v3((key - 1)->co, dv1); - } - add_v3_v3v3(dv1, dv0, dv2); - } - } +static void iterate_lengths_iter(void *__restrict iter_data_v, + const int iter, + const ParallelRangeTLS *__restrict UNUSED(tls)) +{ + IterateLengthsIterData *iter_data = (IterateLengthsIterData *)iter_data_v; + PTCacheEdit *edit = iter_data->edit; + PTCacheEditPoint *point = &edit->points[iter]; + if ((point->flag & PEP_EDIT_RECALC) == 0) { + return; + } + ParticleEditSettings *pset = iter_data->pset; + float tlen; + float dv0[3] = {0.0f, 0.0f, 0.0f}; + float dv1[3] = {0.0f, 0.0f, 0.0f}; + float dv2[3] = {0.0f, 0.0f, 0.0f}; + for (int j = 1; j < point->totkey; j++) { + PTCacheEditKey *key; + int k; + float mul = 1.0f / (float)point->totkey; + if (pset->flag & PE_LOCK_FIRST) { + key = point->keys + 1; + k = 1; + dv1[0] = dv1[1] = dv1[2] = 0.0; + } + else { + key = point->keys; + k = 0; + dv0[0] = dv0[1] = dv0[2] = 0.0; + } + + for (; k < point->totkey; k++, key++) { + if (k) { + sub_v3_v3v3(dv0, (key - 1)->co, key->co); + tlen = normalize_v3(dv0); + mul_v3_fl(dv0, (mul * (tlen - (key - 1)->length))); + } + if (k < point->totkey - 1) { + sub_v3_v3v3(dv2, (key + 1)->co, key->co); + tlen = normalize_v3(dv2); + mul_v3_fl(dv2, mul * (tlen - key->length)); + } + if (k) { + add_v3_v3((key - 1)->co, dv1); + } + add_v3_v3v3(dv1, dv0, dv2); + } + } } /* try to find a nice solution to keep distances between neighboring keys */ static void pe_iterate_lengths(Scene *scene, PTCacheEdit *edit) { - ParticleEditSettings *pset = PE_settings(scene); - if (edit == 0 || (pset->flag & PE_KEEP_LENGTHS) == 0) { - return; - } - if (edit->psys && edit->psys->flag & PSYS_GLOBAL_HAIR) { - return; - } + ParticleEditSettings *pset = PE_settings(scene); + if (edit == 0 || (pset->flag & PE_KEEP_LENGTHS) == 0) { + return; + } + if (edit->psys && edit->psys->flag & PSYS_GLOBAL_HAIR) { + return; + } - IterateLengthsIterData iter_data; - iter_data.edit = edit; - iter_data.pset = pset; + IterateLengthsIterData iter_data; + iter_data.edit = edit; + iter_data.pset = pset; - ParallelRangeSettings settings; - BLI_parallel_range_settings_defaults(&settings); - settings.scheduling_mode = TASK_SCHEDULING_DYNAMIC; - BLI_task_parallel_range(0, edit->totpoint, &iter_data, iterate_lengths_iter, &settings); + ParallelRangeSettings settings; + BLI_parallel_range_settings_defaults(&settings); + settings.scheduling_mode = TASK_SCHEDULING_DYNAMIC; + BLI_task_parallel_range(0, edit->totpoint, &iter_data, iterate_lengths_iter, &settings); } /* set current distances to be kept between neighbouting keys */ void recalc_lengths(PTCacheEdit *edit) { - POINT_P; KEY_K; + POINT_P; + KEY_K; - if (edit == 0) - return; + if (edit == 0) + return; - LOOP_EDITED_POINTS { - key = point->keys; - for (k = 0; k < point->totkey - 1; k++, key++) { - key->length = len_v3v3(key->co, (key + 1)->co); - } - } + LOOP_EDITED_POINTS + { + key = point->keys; + for (k = 0; k < point->totkey - 1; k++, key++) { + key->length = len_v3v3(key->co, (key + 1)->co); + } + } } /* calculate a tree for finding nearest emitter's vertice */ void recalc_emitter_field(Depsgraph *UNUSED(depsgraph), Object *UNUSED(ob), ParticleSystem *psys) { - PTCacheEdit *edit = psys->edit; - Mesh *mesh = edit->psmd_eval->mesh_final; - float *vec, *nor; - int i, totface /*, totvert*/; + PTCacheEdit *edit = psys->edit; + Mesh *mesh = edit->psmd_eval->mesh_final; + float *vec, *nor; + int i, totface /*, totvert*/; - if (!mesh) - return; + if (!mesh) + return; - if (edit->emitter_cosnos) - MEM_freeN(edit->emitter_cosnos); + if (edit->emitter_cosnos) + MEM_freeN(edit->emitter_cosnos); - BLI_kdtree_3d_free(edit->emitter_field); + BLI_kdtree_3d_free(edit->emitter_field); - totface = mesh->totface; - /*totvert=dm->getNumVerts(dm);*/ /*UNUSED*/ + totface = mesh->totface; + /*totvert=dm->getNumVerts(dm);*/ /*UNUSED*/ - edit->emitter_cosnos = MEM_callocN(totface * 6 * sizeof(float), "emitter cosnos"); + edit->emitter_cosnos = MEM_callocN(totface * 6 * sizeof(float), "emitter cosnos"); - edit->emitter_field = BLI_kdtree_3d_new(totface); + edit->emitter_field = BLI_kdtree_3d_new(totface); - vec = edit->emitter_cosnos; - nor = vec + 3; + vec = edit->emitter_cosnos; + nor = vec + 3; - for (i = 0; i < totface; i++, vec += 6, nor += 6) { - MFace *mface = &mesh->mface[i]; - MVert *mvert; + for (i = 0; i < totface; i++, vec += 6, nor += 6) { + MFace *mface = &mesh->mface[i]; + MVert *mvert; - mvert = &mesh->mvert[mface->v1]; - copy_v3_v3(vec, mvert->co); - copy_v3fl_v3s(nor, mvert->no); + mvert = &mesh->mvert[mface->v1]; + copy_v3_v3(vec, mvert->co); + copy_v3fl_v3s(nor, mvert->no); - mvert = &mesh->mvert[mface->v2]; - add_v3_v3v3(vec, vec, mvert->co); - add_v3fl_v3fl_v3s(nor, nor, mvert->no); + mvert = &mesh->mvert[mface->v2]; + add_v3_v3v3(vec, vec, mvert->co); + add_v3fl_v3fl_v3s(nor, nor, mvert->no); - mvert = &mesh->mvert[mface->v3]; - add_v3_v3v3(vec, vec, mvert->co); - add_v3fl_v3fl_v3s(nor, nor, mvert->no); + mvert = &mesh->mvert[mface->v3]; + add_v3_v3v3(vec, vec, mvert->co); + add_v3fl_v3fl_v3s(nor, nor, mvert->no); - if (mface->v4) { - mvert = &mesh->mvert[mface->v4]; - add_v3_v3v3(vec, vec, mvert->co); - add_v3fl_v3fl_v3s(nor, nor, mvert->no); + if (mface->v4) { + mvert = &mesh->mvert[mface->v4]; + add_v3_v3v3(vec, vec, mvert->co); + add_v3fl_v3fl_v3s(nor, nor, mvert->no); - mul_v3_fl(vec, 0.25); - } - else { - mul_v3_fl(vec, 1.0f / 3.0f); - } + mul_v3_fl(vec, 0.25); + } + else { + mul_v3_fl(vec, 1.0f / 3.0f); + } - normalize_v3(nor); + normalize_v3(nor); - BLI_kdtree_3d_insert(edit->emitter_field, i, vec); - } + BLI_kdtree_3d_insert(edit->emitter_field, i, vec); + } - BLI_kdtree_3d_balance(edit->emitter_field); + BLI_kdtree_3d_balance(edit->emitter_field); } static void PE_update_selection(Depsgraph *depsgraph, Scene *scene, Object *ob, int useflag) { - PTCacheEdit *edit = PE_get_current(scene, ob); - HairKey *hkey; - POINT_P; KEY_K; - - /* flag all particles to be updated if not using flag */ - if (!useflag) - LOOP_POINTS { - point->flag |= PEP_EDIT_RECALC; - } - - /* flush edit key flag to hair key flag to preserve selection - * on save */ - if (edit->psys) { - LOOP_POINTS { - hkey = edit->psys->particles[p].hair; - LOOP_KEYS { - hkey->editflag = key->flag; - hkey++; - } - } - } - - psys_cache_edit_paths(depsgraph, scene, ob, edit, CFRA, G.is_rendering); - - - /* disable update flag */ - LOOP_POINTS { - point->flag &= ~PEP_EDIT_RECALC; - } - - DEG_id_tag_update(&ob->id, ID_RECALC_SELECT); + PTCacheEdit *edit = PE_get_current(scene, ob); + HairKey *hkey; + POINT_P; + KEY_K; + + /* flag all particles to be updated if not using flag */ + if (!useflag) + LOOP_POINTS + { + point->flag |= PEP_EDIT_RECALC; + } + + /* flush edit key flag to hair key flag to preserve selection + * on save */ + if (edit->psys) { + LOOP_POINTS + { + hkey = edit->psys->particles[p].hair; + LOOP_KEYS + { + hkey->editflag = key->flag; + hkey++; + } + } + } + + psys_cache_edit_paths(depsgraph, scene, ob, edit, CFRA, G.is_rendering); + + /* disable update flag */ + LOOP_POINTS + { + point->flag &= ~PEP_EDIT_RECALC; + } + + DEG_id_tag_update(&ob->id, ID_RECALC_SELECT); } void update_world_cos(Depsgraph *UNUSED(depsgraph), Object *ob, PTCacheEdit *edit) { - ParticleSystem *psys = edit->psys; - ParticleSystemModifierData *psmd_eval = edit->psmd_eval; - POINT_P; KEY_K; - float hairmat[4][4]; - - if (psys == 0 || psys->edit == 0 || psmd_eval->mesh_final == NULL) - return; - - LOOP_POINTS { - if (!(psys->flag & PSYS_GLOBAL_HAIR)) - psys_mat_hair_to_global(ob, psmd_eval->mesh_final, psys->part->from, psys->particles + p, hairmat); - - LOOP_KEYS { - copy_v3_v3(key->world_co, key->co); - if (!(psys->flag & PSYS_GLOBAL_HAIR)) - mul_m4_v3(hairmat, key->world_co); - } - } + ParticleSystem *psys = edit->psys; + ParticleSystemModifierData *psmd_eval = edit->psmd_eval; + POINT_P; + KEY_K; + float hairmat[4][4]; + + if (psys == 0 || psys->edit == 0 || psmd_eval->mesh_final == NULL) + return; + + LOOP_POINTS + { + if (!(psys->flag & PSYS_GLOBAL_HAIR)) + psys_mat_hair_to_global( + ob, psmd_eval->mesh_final, psys->part->from, psys->particles + p, hairmat); + + LOOP_KEYS + { + copy_v3_v3(key->world_co, key->co); + if (!(psys->flag & PSYS_GLOBAL_HAIR)) + mul_m4_v3(hairmat, key->world_co); + } + } } static void update_velocities(PTCacheEdit *edit) { - /*TODO: get frs_sec properly */ - float vec1[3], vec2[3], frs_sec, dfra; - POINT_P; KEY_K; + /*TODO: get frs_sec properly */ + float vec1[3], vec2[3], frs_sec, dfra; + POINT_P; + KEY_K; - /* hair doesn't use velocities */ - if (edit->psys || !edit->points || !edit->points->keys->vel) - return; + /* hair doesn't use velocities */ + if (edit->psys || !edit->points || !edit->points->keys->vel) + return; - frs_sec = edit->pid.flag & PTCACHE_VEL_PER_SEC ? 25.0f : 1.0f; + frs_sec = edit->pid.flag & PTCACHE_VEL_PER_SEC ? 25.0f : 1.0f; - LOOP_EDITED_POINTS { - LOOP_KEYS { - if (k == 0) { - dfra = *(key + 1)->time - *key->time; + LOOP_EDITED_POINTS + { + LOOP_KEYS + { + if (k == 0) { + dfra = *(key + 1)->time - *key->time; - if (dfra <= 0.0f) - continue; + if (dfra <= 0.0f) + continue; - sub_v3_v3v3(key->vel, (key + 1)->co, key->co); + sub_v3_v3v3(key->vel, (key + 1)->co, key->co); - if (point->totkey > 2) { - sub_v3_v3v3(vec1, (key + 1)->co, (key + 2)->co); - project_v3_v3v3(vec2, vec1, key->vel); - sub_v3_v3v3(vec2, vec1, vec2); - madd_v3_v3fl(key->vel, vec2, 0.5f); - } - } - else if (k == point->totkey - 1) { - dfra = *key->time - *(key - 1)->time; + if (point->totkey > 2) { + sub_v3_v3v3(vec1, (key + 1)->co, (key + 2)->co); + project_v3_v3v3(vec2, vec1, key->vel); + sub_v3_v3v3(vec2, vec1, vec2); + madd_v3_v3fl(key->vel, vec2, 0.5f); + } + } + else if (k == point->totkey - 1) { + dfra = *key->time - *(key - 1)->time; - if (dfra <= 0.0f) - continue; + if (dfra <= 0.0f) + continue; - sub_v3_v3v3(key->vel, key->co, (key - 1)->co); + sub_v3_v3v3(key->vel, key->co, (key - 1)->co); - if (point->totkey > 2) { - sub_v3_v3v3(vec1, (key - 2)->co, (key - 1)->co); - project_v3_v3v3(vec2, vec1, key->vel); - sub_v3_v3v3(vec2, vec1, vec2); - madd_v3_v3fl(key->vel, vec2, 0.5f); - } - } - else { - dfra = *(key + 1)->time - *(key - 1)->time; + if (point->totkey > 2) { + sub_v3_v3v3(vec1, (key - 2)->co, (key - 1)->co); + project_v3_v3v3(vec2, vec1, key->vel); + sub_v3_v3v3(vec2, vec1, vec2); + madd_v3_v3fl(key->vel, vec2, 0.5f); + } + } + else { + dfra = *(key + 1)->time - *(key - 1)->time; - if (dfra <= 0.0f) - continue; + if (dfra <= 0.0f) + continue; - sub_v3_v3v3(key->vel, (key + 1)->co, (key - 1)->co); - } - mul_v3_fl(key->vel, frs_sec / dfra); - } - } + sub_v3_v3v3(key->vel, (key + 1)->co, (key - 1)->co); + } + mul_v3_fl(key->vel, frs_sec / dfra); + } + } } void PE_update_object(Depsgraph *depsgraph, Scene *scene, Object *ob, int useflag) { - /* use this to do partial particle updates, not usable when adding or - * removing, then a full redo is necessary and calling this may crash */ - ParticleEditSettings *pset = PE_settings(scene); - PTCacheEdit *edit = PE_get_current(scene, ob); - POINT_P; - - if (!edit) - return; - - /* flag all particles to be updated if not using flag */ - if (!useflag) - LOOP_POINTS { - point->flag |= PEP_EDIT_RECALC; - } - - /* do post process on particle edit keys */ - pe_iterate_lengths(scene, edit); - pe_deflect_emitter(scene, ob, edit); - PE_apply_lengths(scene, edit); - if (pe_x_mirror(ob)) - PE_apply_mirror(ob, edit->psys); - if (edit->psys) - update_world_cos(depsgraph, ob, edit); - if (pset->flag & PE_AUTO_VELOCITY) - update_velocities(edit); - PE_hide_keys_time(scene, edit, CFRA); - - /* regenerate path caches */ - psys_cache_edit_paths(depsgraph, scene, ob, edit, CFRA, G.is_rendering); - - /* disable update flag */ - LOOP_POINTS { - point->flag &= ~PEP_EDIT_RECALC; - } - - if (edit->psys) - edit->psys->flag &= ~PSYS_HAIR_UPDATED; + /* use this to do partial particle updates, not usable when adding or + * removing, then a full redo is necessary and calling this may crash */ + ParticleEditSettings *pset = PE_settings(scene); + PTCacheEdit *edit = PE_get_current(scene, ob); + POINT_P; + + if (!edit) + return; + + /* flag all particles to be updated if not using flag */ + if (!useflag) + LOOP_POINTS + { + point->flag |= PEP_EDIT_RECALC; + } + + /* do post process on particle edit keys */ + pe_iterate_lengths(scene, edit); + pe_deflect_emitter(scene, ob, edit); + PE_apply_lengths(scene, edit); + if (pe_x_mirror(ob)) + PE_apply_mirror(ob, edit->psys); + if (edit->psys) + update_world_cos(depsgraph, ob, edit); + if (pset->flag & PE_AUTO_VELOCITY) + update_velocities(edit); + PE_hide_keys_time(scene, edit, CFRA); + + /* regenerate path caches */ + psys_cache_edit_paths(depsgraph, scene, ob, edit, CFRA, G.is_rendering); + + /* disable update flag */ + LOOP_POINTS + { + point->flag &= ~PEP_EDIT_RECALC; + } + + if (edit->psys) + edit->psys->flag &= ~PSYS_HAIR_UPDATED; } /************************************************/ -/* Edit Selections */ +/* Edit Selections */ /************************************************/ /*-----selection callbacks-----*/ static void select_key(PEData *data, int point_index, int key_index, bool UNUSED(is_inside)) { - PTCacheEdit *edit = data->edit; - PTCacheEditPoint *point = edit->points + point_index; - PTCacheEditKey *key = point->keys + key_index; + PTCacheEdit *edit = data->edit; + PTCacheEditPoint *point = edit->points + point_index; + PTCacheEditKey *key = point->keys + key_index; - if (data->select) - key->flag |= PEK_SELECT; - else - key->flag &= ~PEK_SELECT; + if (data->select) + key->flag |= PEK_SELECT; + else + key->flag &= ~PEK_SELECT; - point->flag |= PEP_EDIT_RECALC; - data->is_changed = true; + point->flag |= PEP_EDIT_RECALC; + data->is_changed = true; } static void select_key_op(PEData *data, int point_index, int key_index, bool is_inside) { - PTCacheEdit *edit = data->edit; - PTCacheEditPoint *point = edit->points + point_index; - PTCacheEditKey *key = point->keys + key_index; - const bool is_select = key->flag & PEK_SELECT; - const int sel_op_result = ED_select_op_action_deselected(data->sel_op, is_select, is_inside); - if (sel_op_result != -1) { - SET_FLAG_FROM_TEST(key->flag, sel_op_result, PEK_SELECT); - point->flag |= PEP_EDIT_RECALC; - data->is_changed = true; - } + PTCacheEdit *edit = data->edit; + PTCacheEditPoint *point = edit->points + point_index; + PTCacheEditKey *key = point->keys + key_index; + const bool is_select = key->flag & PEK_SELECT; + const int sel_op_result = ED_select_op_action_deselected(data->sel_op, is_select, is_inside); + if (sel_op_result != -1) { + SET_FLAG_FROM_TEST(key->flag, sel_op_result, PEK_SELECT); + point->flag |= PEP_EDIT_RECALC; + data->is_changed = true; + } } -static void select_keys(PEData *data, int point_index, int UNUSED(key_index), bool UNUSED(is_inside)) +static void select_keys(PEData *data, + int point_index, + int UNUSED(key_index), + bool UNUSED(is_inside)) { - PTCacheEdit *edit = data->edit; - PTCacheEditPoint *point = edit->points + point_index; - KEY_K; + PTCacheEdit *edit = data->edit; + PTCacheEditPoint *point = edit->points + point_index; + KEY_K; - LOOP_KEYS { - if (data->select) - key->flag |= PEK_SELECT; - else - key->flag &= ~PEK_SELECT; - } + LOOP_KEYS + { + if (data->select) + key->flag |= PEK_SELECT; + else + key->flag &= ~PEK_SELECT; + } - point->flag |= PEP_EDIT_RECALC; + point->flag |= PEP_EDIT_RECALC; } static void extend_key_select(PEData *data, int point_index, int key_index, bool UNUSED(is_inside)) { - PTCacheEdit *edit = data->edit; - PTCacheEditPoint *point = edit->points + point_index; - PTCacheEditKey *key = point->keys + key_index; + PTCacheEdit *edit = data->edit; + PTCacheEditPoint *point = edit->points + point_index; + PTCacheEditKey *key = point->keys + key_index; - if ((key->flag & PEK_SELECT) == 0) { - key->flag |= PEK_SELECT; - point->flag |= PEP_EDIT_RECALC; - data->is_changed = true; - } + if ((key->flag & PEK_SELECT) == 0) { + key->flag |= PEK_SELECT; + point->flag |= PEP_EDIT_RECALC; + data->is_changed = true; + } } -static void deselect_key_select(PEData *data, int point_index, int key_index, bool UNUSED(is_inside)) +static void deselect_key_select(PEData *data, + int point_index, + int key_index, + bool UNUSED(is_inside)) { - PTCacheEdit *edit = data->edit; - PTCacheEditPoint *point = edit->points + point_index; - PTCacheEditKey *key = point->keys + key_index; + PTCacheEdit *edit = data->edit; + PTCacheEditPoint *point = edit->points + point_index; + PTCacheEditKey *key = point->keys + key_index; - if ((key->flag & PEK_SELECT) != 0) { - key->flag &= ~PEK_SELECT; - point->flag |= PEP_EDIT_RECALC; - data->is_changed = true; - } + if ((key->flag & PEK_SELECT) != 0) { + key->flag &= ~PEK_SELECT; + point->flag |= PEP_EDIT_RECALC; + data->is_changed = true; + } } static void toggle_key_select(PEData *data, int point_index, int key_index, bool UNUSED(is_inside)) { - PTCacheEdit *edit = data->edit; - PTCacheEditPoint *point = edit->points + point_index; - PTCacheEditKey *key = point->keys + key_index; + PTCacheEdit *edit = data->edit; + PTCacheEditPoint *point = edit->points + point_index; + PTCacheEditKey *key = point->keys + key_index; - key->flag ^= PEK_SELECT; - point->flag |= PEP_EDIT_RECALC; - data->is_changed = true; + key->flag ^= PEK_SELECT; + point->flag |= PEP_EDIT_RECALC; + data->is_changed = true; } /************************ de select all operator ************************/ static bool select_action_apply(PTCacheEditPoint *point, PTCacheEditKey *key, int action) { - bool changed = false; - switch (action) { - case SEL_SELECT: - if ((key->flag & PEK_SELECT) == 0) { - key->flag |= PEK_SELECT; - point->flag |= PEP_EDIT_RECALC; - changed = true; - } - break; - case SEL_DESELECT: - if (key->flag & PEK_SELECT) { - key->flag &= ~PEK_SELECT; - point->flag |= PEP_EDIT_RECALC; - changed = true; - } - break; - case SEL_INVERT: - if ((key->flag & PEK_SELECT) == 0) { - key->flag |= PEK_SELECT; - point->flag |= PEP_EDIT_RECALC; - changed = true; - } - else { - key->flag &= ~PEK_SELECT; - point->flag |= PEP_EDIT_RECALC; - changed = true; - } - break; - } - return changed; + bool changed = false; + switch (action) { + case SEL_SELECT: + if ((key->flag & PEK_SELECT) == 0) { + key->flag |= PEK_SELECT; + point->flag |= PEP_EDIT_RECALC; + changed = true; + } + break; + case SEL_DESELECT: + if (key->flag & PEK_SELECT) { + key->flag &= ~PEK_SELECT; + point->flag |= PEP_EDIT_RECALC; + changed = true; + } + break; + case SEL_INVERT: + if ((key->flag & PEK_SELECT) == 0) { + key->flag |= PEK_SELECT; + point->flag |= PEP_EDIT_RECALC; + changed = true; + } + else { + key->flag &= ~PEK_SELECT; + point->flag |= PEP_EDIT_RECALC; + changed = true; + } + break; + } + return changed; } static int pe_select_all_exec(bContext *C, wmOperator *op) { - Scene *scene = CTX_data_scene(C); - Depsgraph *depsgraph = CTX_data_depsgraph(C); - Object *ob = CTX_data_active_object(C); - PTCacheEdit *edit = PE_get_current(scene, ob); - POINT_P; KEY_K; - int action = RNA_enum_get(op->ptr, "action"); - - if (action == SEL_TOGGLE) { - action = SEL_SELECT; - LOOP_VISIBLE_POINTS { - LOOP_SELECTED_KEYS { - action = SEL_DESELECT; - break; - } - - if (action == SEL_DESELECT) - break; - } - } - - bool changed = false; - LOOP_VISIBLE_POINTS { - LOOP_VISIBLE_KEYS { - changed |= select_action_apply(point, key, action); - } - } - - if (changed) { - PE_update_selection(depsgraph, scene, ob, 1); - WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_SELECTED, ob); - } - return OPERATOR_FINISHED; + Scene *scene = CTX_data_scene(C); + Depsgraph *depsgraph = CTX_data_depsgraph(C); + Object *ob = CTX_data_active_object(C); + PTCacheEdit *edit = PE_get_current(scene, ob); + POINT_P; + KEY_K; + int action = RNA_enum_get(op->ptr, "action"); + + if (action == SEL_TOGGLE) { + action = SEL_SELECT; + LOOP_VISIBLE_POINTS + { + LOOP_SELECTED_KEYS + { + action = SEL_DESELECT; + break; + } + + if (action == SEL_DESELECT) + break; + } + } + + bool changed = false; + LOOP_VISIBLE_POINTS + { + LOOP_VISIBLE_KEYS + { + changed |= select_action_apply(point, key, action); + } + } + + if (changed) { + PE_update_selection(depsgraph, scene, ob, 1); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_SELECTED, ob); + } + return OPERATOR_FINISHED; } void PARTICLE_OT_select_all(wmOperatorType *ot) { - /* identifiers */ - ot->name = "(De)select All"; - ot->idname = "PARTICLE_OT_select_all"; - ot->description = "(De)select all particles' keys"; + /* identifiers */ + ot->name = "(De)select All"; + ot->idname = "PARTICLE_OT_select_all"; + ot->description = "(De)select all particles' keys"; - /* api callbacks */ - ot->exec = pe_select_all_exec; - ot->poll = PE_poll; + /* api callbacks */ + ot->exec = pe_select_all_exec; + ot->poll = PE_poll; - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; - WM_operator_properties_select_all(ot); + WM_operator_properties_select_all(ot); } /************************ pick select operator ************************/ bool PE_mouse_particles(bContext *C, const int mval[2], bool extend, bool deselect, bool toggle) { - PEData data; - Scene *scene = CTX_data_scene(C); - Object *ob = CTX_data_active_object(C); - PTCacheEdit *edit = PE_get_current(scene, ob); - POINT_P; KEY_K; - - if (!PE_start_edit(edit)) { - return false; - } - - if (!extend && !deselect && !toggle) { - LOOP_VISIBLE_POINTS { - LOOP_SELECTED_KEYS { - key->flag &= ~PEK_SELECT; - point->flag |= PEP_EDIT_RECALC; - } - } - } - - PE_set_view3d_data(C, &data); - data.mval = mval; - data.rad = ED_view3d_select_dist_px(); - - /* 1 = nearest only */ - if (extend) { - for_mouse_hit_keys(&data, extend_key_select, PSEL_NEAREST); - } - else if (deselect) { - for_mouse_hit_keys(&data, deselect_key_select, PSEL_NEAREST); - } - else { - for_mouse_hit_keys(&data, toggle_key_select, PSEL_NEAREST); - } - - if (data.is_changed) { - PE_update_selection(data.depsgraph, scene, ob, 1); - WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_SELECTED, data.ob); - } - - return true; + PEData data; + Scene *scene = CTX_data_scene(C); + Object *ob = CTX_data_active_object(C); + PTCacheEdit *edit = PE_get_current(scene, ob); + POINT_P; + KEY_K; + + if (!PE_start_edit(edit)) { + return false; + } + + if (!extend && !deselect && !toggle) { + LOOP_VISIBLE_POINTS + { + LOOP_SELECTED_KEYS + { + key->flag &= ~PEK_SELECT; + point->flag |= PEP_EDIT_RECALC; + } + } + } + + PE_set_view3d_data(C, &data); + data.mval = mval; + data.rad = ED_view3d_select_dist_px(); + + /* 1 = nearest only */ + if (extend) { + for_mouse_hit_keys(&data, extend_key_select, PSEL_NEAREST); + } + else if (deselect) { + for_mouse_hit_keys(&data, deselect_key_select, PSEL_NEAREST); + } + else { + for_mouse_hit_keys(&data, toggle_key_select, PSEL_NEAREST); + } + + if (data.is_changed) { + PE_update_selection(data.depsgraph, scene, ob, 1); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_SELECTED, data.ob); + } + + return true; } /************************ select root operator ************************/ static void select_root(PEData *data, int point_index) { - PTCacheEditPoint *point = data->edit->points + point_index; - PTCacheEditKey *key = point->keys; + PTCacheEditPoint *point = data->edit->points + point_index; + PTCacheEditKey *key = point->keys; - if (point->flag & PEP_HIDE) - return; + if (point->flag & PEP_HIDE) + return; - if (data->select_action != SEL_TOGGLE) { - data->is_changed = select_action_apply(point, key, data->select_action); - } - else if (key->flag & PEK_SELECT) { - data->select_toggle_action = SEL_DESELECT; - } + if (data->select_action != SEL_TOGGLE) { + data->is_changed = select_action_apply(point, key, data->select_action); + } + else if (key->flag & PEK_SELECT) { + data->select_toggle_action = SEL_DESELECT; + } } static int select_roots_exec(bContext *C, wmOperator *op) { - PEData data; - int action = RNA_enum_get(op->ptr, "action"); + PEData data; + int action = RNA_enum_get(op->ptr, "action"); - PE_set_data(C, &data); + PE_set_data(C, &data); - if (action == SEL_TOGGLE) { - data.select_action = SEL_TOGGLE; - data.select_toggle_action = SEL_SELECT; + if (action == SEL_TOGGLE) { + data.select_action = SEL_TOGGLE; + data.select_toggle_action = SEL_SELECT; - foreach_point(&data, select_root); + foreach_point(&data, select_root); - action = data.select_toggle_action; - } + action = data.select_toggle_action; + } - data.select_action = action; - foreach_point(&data, select_root); + data.select_action = action; + foreach_point(&data, select_root); - if (data.is_changed) { - PE_update_selection(data.depsgraph, data.scene, data.ob, 1); - WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_SELECTED, data.ob); - } - return OPERATOR_FINISHED; + if (data.is_changed) { + PE_update_selection(data.depsgraph, data.scene, data.ob, 1); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_SELECTED, data.ob); + } + return OPERATOR_FINISHED; } void PARTICLE_OT_select_roots(wmOperatorType *ot) { - /* identifiers */ - ot->name = "Select Roots"; - ot->idname = "PARTICLE_OT_select_roots"; - ot->description = "Select roots of all visible particles"; + /* identifiers */ + ot->name = "Select Roots"; + ot->idname = "PARTICLE_OT_select_roots"; + ot->description = "Select roots of all visible particles"; - /* api callbacks */ - ot->exec = select_roots_exec; - ot->poll = PE_poll; + /* api callbacks */ + ot->exec = select_roots_exec; + ot->poll = PE_poll; - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; - /* properties */ - WM_operator_properties_select_action(ot, SEL_SELECT, true); + /* properties */ + WM_operator_properties_select_action(ot, SEL_SELECT, true); } /************************ select tip operator ************************/ static void select_tip(PEData *data, int point_index) { - PTCacheEditPoint *point = data->edit->points + point_index; - PTCacheEditKey *key; + PTCacheEditPoint *point = data->edit->points + point_index; + PTCacheEditKey *key; - if (point->totkey == 0) { - return; - } + if (point->totkey == 0) { + return; + } - key = &point->keys[point->totkey - 1]; + key = &point->keys[point->totkey - 1]; - if (point->flag & PEP_HIDE) - return; + if (point->flag & PEP_HIDE) + return; - if (data->select_action != SEL_TOGGLE) { - data->is_changed = select_action_apply(point, key, data->select_action); - } - else if (key->flag & PEK_SELECT) { - data->select_toggle_action = SEL_DESELECT; - } + if (data->select_action != SEL_TOGGLE) { + data->is_changed = select_action_apply(point, key, data->select_action); + } + else if (key->flag & PEK_SELECT) { + data->select_toggle_action = SEL_DESELECT; + } } static int select_tips_exec(bContext *C, wmOperator *op) { - PEData data; - int action = RNA_enum_get(op->ptr, "action"); + PEData data; + int action = RNA_enum_get(op->ptr, "action"); - PE_set_data(C, &data); + PE_set_data(C, &data); - if (action == SEL_TOGGLE) { - data.select_action = SEL_TOGGLE; - data.select_toggle_action = SEL_SELECT; + if (action == SEL_TOGGLE) { + data.select_action = SEL_TOGGLE; + data.select_toggle_action = SEL_SELECT; - foreach_point(&data, select_tip); + foreach_point(&data, select_tip); - action = data.select_toggle_action; - } + action = data.select_toggle_action; + } - data.select_action = action; - foreach_point(&data, select_tip); + data.select_action = action; + foreach_point(&data, select_tip); - if (data.is_changed) { - PE_update_selection(data.depsgraph, data.scene, data.ob, 1); - WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_SELECTED, data.ob); + if (data.is_changed) { + PE_update_selection(data.depsgraph, data.scene, data.ob, 1); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_SELECTED, data.ob); - return OPERATOR_FINISHED; - } - return OPERATOR_CANCELLED; + return OPERATOR_FINISHED; + } + return OPERATOR_CANCELLED; } void PARTICLE_OT_select_tips(wmOperatorType *ot) { - /* identifiers */ - ot->name = "Select Tips"; - ot->idname = "PARTICLE_OT_select_tips"; - ot->description = "Select tips of all visible particles"; + /* identifiers */ + ot->name = "Select Tips"; + ot->idname = "PARTICLE_OT_select_tips"; + ot->description = "Select tips of all visible particles"; - /* api callbacks */ - ot->exec = select_tips_exec; - ot->poll = PE_poll; + /* api callbacks */ + ot->exec = select_tips_exec; + ot->poll = PE_poll; - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; - /* properties */ - WM_operator_properties_select_action(ot, SEL_SELECT, true); + /* properties */ + WM_operator_properties_select_action(ot, SEL_SELECT, true); } /*********************** select random operator ************************/ @@ -1892,847 +1934,892 @@ void PARTICLE_OT_select_tips(wmOperatorType *ot) enum { RAN_HAIR, RAN_POINTS }; static const EnumPropertyItem select_random_type_items[] = { - {RAN_HAIR, "HAIR", 0, "Hair", ""}, - {RAN_POINTS, "POINTS", 0, "Points", ""}, - {0, NULL, 0, NULL, NULL}, + {RAN_HAIR, "HAIR", 0, "Hair", ""}, + {RAN_POINTS, "POINTS", 0, "Points", ""}, + {0, NULL, 0, NULL, NULL}, }; static int select_random_exec(bContext *C, wmOperator *op) { - PEData data; - int type; - - /* used by LOOP_VISIBLE_POINTS, LOOP_VISIBLE_KEYS and LOOP_KEYS */ - PTCacheEdit *edit; - PTCacheEditPoint *point; - PTCacheEditKey *key; - int p; - int k; - - const float randfac = RNA_float_get(op->ptr, "percent") / 100.0f; - const int seed = WM_operator_properties_select_random_seed_increment_get(op); - const bool select = (RNA_enum_get(op->ptr, "action") == SEL_SELECT); - RNG *rng; - - type = RNA_enum_get(op->ptr, "type"); - - PE_set_data(C, &data); - data.select_action = SEL_SELECT; - edit = PE_get_current(data.scene, data.ob); - - rng = BLI_rng_new_srandom(seed); - - switch (type) { - case RAN_HAIR: - LOOP_VISIBLE_POINTS { - int flag = ((BLI_rng_get_float(rng) < randfac) == select) ? SEL_SELECT : SEL_DESELECT; - LOOP_KEYS { - data.is_changed |= select_action_apply(point, key, flag); - } - } - break; - case RAN_POINTS: - LOOP_VISIBLE_POINTS { - LOOP_VISIBLE_KEYS { - int flag = ((BLI_rng_get_float(rng) < randfac) == select) ? SEL_SELECT : SEL_DESELECT; - data.is_changed |= select_action_apply(point, key, flag); - } - } - break; - } - - BLI_rng_free(rng); - - if (data.is_changed) { - PE_update_selection(data.depsgraph, data.scene, data.ob, 1); - WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_SELECTED, data.ob); - } - return OPERATOR_FINISHED; + PEData data; + int type; + + /* used by LOOP_VISIBLE_POINTS, LOOP_VISIBLE_KEYS and LOOP_KEYS */ + PTCacheEdit *edit; + PTCacheEditPoint *point; + PTCacheEditKey *key; + int p; + int k; + + const float randfac = RNA_float_get(op->ptr, "percent") / 100.0f; + const int seed = WM_operator_properties_select_random_seed_increment_get(op); + const bool select = (RNA_enum_get(op->ptr, "action") == SEL_SELECT); + RNG *rng; + + type = RNA_enum_get(op->ptr, "type"); + + PE_set_data(C, &data); + data.select_action = SEL_SELECT; + edit = PE_get_current(data.scene, data.ob); + + rng = BLI_rng_new_srandom(seed); + + switch (type) { + case RAN_HAIR: + LOOP_VISIBLE_POINTS + { + int flag = ((BLI_rng_get_float(rng) < randfac) == select) ? SEL_SELECT : SEL_DESELECT; + LOOP_KEYS + { + data.is_changed |= select_action_apply(point, key, flag); + } + } + break; + case RAN_POINTS: + LOOP_VISIBLE_POINTS + { + LOOP_VISIBLE_KEYS + { + int flag = ((BLI_rng_get_float(rng) < randfac) == select) ? SEL_SELECT : SEL_DESELECT; + data.is_changed |= select_action_apply(point, key, flag); + } + } + break; + } + + BLI_rng_free(rng); + + if (data.is_changed) { + PE_update_selection(data.depsgraph, data.scene, data.ob, 1); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_SELECTED, data.ob); + } + return OPERATOR_FINISHED; } void PARTICLE_OT_select_random(wmOperatorType *ot) { - /* identifiers */ - ot->name = "Select Random"; - ot->idname = "PARTICLE_OT_select_random"; - ot->description = "Select a randomly distributed set of hair or points"; + /* identifiers */ + ot->name = "Select Random"; + ot->idname = "PARTICLE_OT_select_random"; + ot->description = "Select a randomly distributed set of hair or points"; - /* api callbacks */ - ot->exec = select_random_exec; - ot->poll = PE_poll; + /* api callbacks */ + ot->exec = select_random_exec; + ot->poll = PE_poll; - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; - /* properties */ - WM_operator_properties_select_random(ot); - ot->prop = RNA_def_enum(ot->srna, "type", select_random_type_items, RAN_HAIR, - "Type", "Select either hair or points"); + /* properties */ + WM_operator_properties_select_random(ot); + ot->prop = RNA_def_enum(ot->srna, + "type", + select_random_type_items, + RAN_HAIR, + "Type", + "Select either hair or points"); } /************************ select linked operator ************************/ static int select_linked_exec(bContext *C, wmOperator *op) { - PEData data; - int mval[2]; - int location[2]; + PEData data; + int mval[2]; + int location[2]; - RNA_int_get_array(op->ptr, "location", location); - mval[0] = location[0]; - mval[1] = location[1]; + RNA_int_get_array(op->ptr, "location", location); + mval[0] = location[0]; + mval[1] = location[1]; - PE_set_view3d_data(C, &data); - data.mval = mval; - data.rad = 75.0f; - data.select = !RNA_boolean_get(op->ptr, "deselect"); + PE_set_view3d_data(C, &data); + data.mval = mval; + data.rad = 75.0f; + data.select = !RNA_boolean_get(op->ptr, "deselect"); - for_mouse_hit_keys(&data, select_keys, PSEL_NEAREST); - PE_update_selection(data.depsgraph, data.scene, data.ob, 1); - WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_SELECTED, data.ob); + for_mouse_hit_keys(&data, select_keys, PSEL_NEAREST); + PE_update_selection(data.depsgraph, data.scene, data.ob, 1); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_SELECTED, data.ob); - return OPERATOR_FINISHED; + return OPERATOR_FINISHED; } static int select_linked_invoke(bContext *C, wmOperator *op, const wmEvent *event) { - RNA_int_set_array(op->ptr, "location", event->mval); - return select_linked_exec(C, op); + RNA_int_set_array(op->ptr, "location", event->mval); + return select_linked_exec(C, op); } void PARTICLE_OT_select_linked(wmOperatorType *ot) { - /* identifiers */ - ot->name = "Select Linked"; - ot->idname = "PARTICLE_OT_select_linked"; - ot->description = "Select nearest particle from mouse pointer"; + /* identifiers */ + ot->name = "Select Linked"; + ot->idname = "PARTICLE_OT_select_linked"; + ot->description = "Select nearest particle from mouse pointer"; - /* api callbacks */ - ot->exec = select_linked_exec; - ot->invoke = select_linked_invoke; - ot->poll = PE_poll_view3d; + /* api callbacks */ + ot->exec = select_linked_exec; + ot->invoke = select_linked_invoke; + ot->poll = PE_poll_view3d; - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; - /* properties */ - RNA_def_boolean(ot->srna, "deselect", 0, "Deselect", "Deselect linked keys rather than selecting them"); - RNA_def_int_vector(ot->srna, "location", 2, NULL, 0, INT_MAX, "Location", "", 0, 16384); + /* properties */ + RNA_def_boolean( + ot->srna, "deselect", 0, "Deselect", "Deselect linked keys rather than selecting them"); + RNA_def_int_vector(ot->srna, "location", 2, NULL, 0, INT_MAX, "Location", "", 0, 16384); } /************************ box select operator ************************/ bool PE_deselect_all_visible_ex(PTCacheEdit *edit) { - bool changed = false; - POINT_P; KEY_K; + bool changed = false; + POINT_P; + KEY_K; - LOOP_VISIBLE_POINTS { - LOOP_SELECTED_KEYS { - if ((key->flag & PEK_SELECT) != 0) { - key->flag &= ~PEK_SELECT; - point->flag |= PEP_EDIT_RECALC; - changed = true; - } - } - } - return changed; + LOOP_VISIBLE_POINTS + { + LOOP_SELECTED_KEYS + { + if ((key->flag & PEK_SELECT) != 0) { + key->flag &= ~PEK_SELECT; + point->flag |= PEP_EDIT_RECALC; + changed = true; + } + } + } + return changed; } bool PE_deselect_all_visible(bContext *C) { - Scene *scene = CTX_data_scene(C); - Object *ob = CTX_data_active_object(C); - PTCacheEdit *edit = PE_get_current(scene, ob); - if (!PE_start_edit(edit)) { - return false; - } - return PE_deselect_all_visible_ex(edit); + Scene *scene = CTX_data_scene(C); + Object *ob = CTX_data_active_object(C); + PTCacheEdit *edit = PE_get_current(scene, ob); + if (!PE_start_edit(edit)) { + return false; + } + return PE_deselect_all_visible_ex(edit); } bool PE_box_select(bContext *C, const rcti *rect, const int sel_op) { - Scene *scene = CTX_data_scene(C); - Object *ob = CTX_data_active_object(C); - PTCacheEdit *edit = PE_get_current(scene, ob); - PEData data; + Scene *scene = CTX_data_scene(C); + Object *ob = CTX_data_active_object(C); + PTCacheEdit *edit = PE_get_current(scene, ob); + PEData data; - if (!PE_start_edit(edit)) { - return false; - } + if (!PE_start_edit(edit)) { + return false; + } - PE_set_view3d_data(C, &data); - data.rect = rect; - data.sel_op = sel_op; + PE_set_view3d_data(C, &data); + data.rect = rect; + data.sel_op = sel_op; - if (SEL_OP_USE_PRE_DESELECT(sel_op)) { - data.is_changed = PE_deselect_all_visible_ex(edit); - } + if (SEL_OP_USE_PRE_DESELECT(sel_op)) { + data.is_changed = PE_deselect_all_visible_ex(edit); + } - if (BLI_rcti_is_empty(rect)) { - /* pass */ - } - else { - for_mouse_hit_keys(&data, select_key_op, PSEL_ALL_KEYS); - } + if (BLI_rcti_is_empty(rect)) { + /* pass */ + } + else { + for_mouse_hit_keys(&data, select_key_op, PSEL_ALL_KEYS); + } - if (data.is_changed) { - PE_update_selection(data.depsgraph, scene, ob, 1); - WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_SELECTED, ob); - } - return data.is_changed; + if (data.is_changed) { + PE_update_selection(data.depsgraph, scene, ob, 1); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_SELECTED, ob); + } + return data.is_changed; } /************************ circle select operator ************************/ bool PE_circle_select(bContext *C, const int sel_op, const int mval[2], float rad) { - BLI_assert(ELEM(sel_op, SEL_OP_SET, SEL_OP_ADD, SEL_OP_SUB)); - Scene *scene = CTX_data_scene(C); - Object *ob = CTX_data_active_object(C); - PTCacheEdit *edit = PE_get_current(scene, ob); - PEData data; + BLI_assert(ELEM(sel_op, SEL_OP_SET, SEL_OP_ADD, SEL_OP_SUB)); + Scene *scene = CTX_data_scene(C); + Object *ob = CTX_data_active_object(C); + PTCacheEdit *edit = PE_get_current(scene, ob); + PEData data; - if (!PE_start_edit(edit)) { - return false; - } + if (!PE_start_edit(edit)) { + return false; + } - const bool select = (sel_op != SEL_OP_SUB); + const bool select = (sel_op != SEL_OP_SUB); - PE_set_view3d_data(C, &data); - data.mval = mval; - data.rad = rad; - data.select = select; + PE_set_view3d_data(C, &data); + data.mval = mval; + data.rad = rad; + data.select = select; - if (SEL_OP_USE_PRE_DESELECT(sel_op)) { - data.is_changed = PE_deselect_all_visible_ex(edit); - } - for_mouse_hit_keys(&data, select_key, 0); - if (data.is_changed) { - PE_update_selection(data.depsgraph, scene, ob, 1); - WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_SELECTED, ob); - } - return data.is_changed; + if (SEL_OP_USE_PRE_DESELECT(sel_op)) { + data.is_changed = PE_deselect_all_visible_ex(edit); + } + for_mouse_hit_keys(&data, select_key, 0); + if (data.is_changed) { + PE_update_selection(data.depsgraph, scene, ob, 1); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_SELECTED, ob); + } + return data.is_changed; } /************************ lasso select operator ************************/ int PE_lasso_select(bContext *C, const int mcords[][2], const short moves, const int sel_op) { - Scene *scene = CTX_data_scene(C); - Object *ob = CTX_data_active_object(C); - ARegion *ar = CTX_wm_region(C); - ParticleEditSettings *pset = PE_settings(scene); - PTCacheEdit *edit = PE_get_current(scene, ob); - ParticleSystem *psys = edit->psys; - ParticleSystemModifierData *psmd_eval = edit->psmd_eval; - POINT_P; KEY_K; - float co[3], mat[4][4]; - int screen_co[2]; - - PEData data; - - unit_m4(mat); - - if (!PE_start_edit(edit)) - return OPERATOR_CANCELLED; - - /* only for depths */ - PE_set_view3d_data(C, &data); - - if (SEL_OP_USE_PRE_DESELECT(sel_op)) { - data.is_changed |= PE_deselect_all_visible_ex(edit); - } - - LOOP_VISIBLE_POINTS { - if (edit->psys && !(psys->flag & PSYS_GLOBAL_HAIR)) - psys_mat_hair_to_global(ob, psmd_eval->mesh_final, psys->part->from, psys->particles + p, mat); - - if (pset->selectmode == SCE_SELECT_POINT) { - LOOP_KEYS { - copy_v3_v3(co, key->co); - mul_m4_v3(mat, co); - const bool is_select = key->flag & PEK_SELECT; - const bool is_inside = ( - (ED_view3d_project_int_global(ar, co, screen_co, V3D_PROJ_TEST_CLIP_WIN) == V3D_PROJ_RET_OK) && - BLI_lasso_is_point_inside(mcords, moves, screen_co[0], screen_co[1], IS_CLIPPED) && - key_test_depth(&data, co, screen_co)); - const int sel_op_result = ED_select_op_action_deselected(sel_op, is_select, is_inside); - if (sel_op_result != -1) { - SET_FLAG_FROM_TEST(key->flag, sel_op_result, PEK_SELECT); - point->flag |= PEP_EDIT_RECALC; - data.is_changed = true; - } - } - } - else if (pset->selectmode == SCE_SELECT_END) { - if (point->totkey) { - key = point->keys + point->totkey - 1; - copy_v3_v3(co, key->co); - mul_m4_v3(mat, co); - const bool is_select = key->flag & PEK_SELECT; - const bool is_inside = ( - (ED_view3d_project_int_global(ar, co, screen_co, V3D_PROJ_TEST_CLIP_WIN) == V3D_PROJ_RET_OK) && - BLI_lasso_is_point_inside(mcords, moves, screen_co[0], screen_co[1], IS_CLIPPED) && - key_test_depth(&data, co, screen_co)); - const int sel_op_result = ED_select_op_action_deselected(sel_op, is_select, is_inside); - if (sel_op_result != -1) { - SET_FLAG_FROM_TEST(key->flag, sel_op_result, PEK_SELECT); - point->flag |= PEP_EDIT_RECALC; - data.is_changed = true; - } - } - } - } - - if (data.is_changed) { - PE_update_selection(data.depsgraph, scene, ob, 1); - WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_SELECTED, ob); - return OPERATOR_FINISHED; - } - return OPERATOR_CANCELLED; + Scene *scene = CTX_data_scene(C); + Object *ob = CTX_data_active_object(C); + ARegion *ar = CTX_wm_region(C); + ParticleEditSettings *pset = PE_settings(scene); + PTCacheEdit *edit = PE_get_current(scene, ob); + ParticleSystem *psys = edit->psys; + ParticleSystemModifierData *psmd_eval = edit->psmd_eval; + POINT_P; + KEY_K; + float co[3], mat[4][4]; + int screen_co[2]; + + PEData data; + + unit_m4(mat); + + if (!PE_start_edit(edit)) + return OPERATOR_CANCELLED; + + /* only for depths */ + PE_set_view3d_data(C, &data); + + if (SEL_OP_USE_PRE_DESELECT(sel_op)) { + data.is_changed |= PE_deselect_all_visible_ex(edit); + } + + LOOP_VISIBLE_POINTS + { + if (edit->psys && !(psys->flag & PSYS_GLOBAL_HAIR)) + psys_mat_hair_to_global( + ob, psmd_eval->mesh_final, psys->part->from, psys->particles + p, mat); + + if (pset->selectmode == SCE_SELECT_POINT) { + LOOP_KEYS + { + copy_v3_v3(co, key->co); + mul_m4_v3(mat, co); + const bool is_select = key->flag & PEK_SELECT; + const bool is_inside = + ((ED_view3d_project_int_global(ar, co, screen_co, V3D_PROJ_TEST_CLIP_WIN) == + V3D_PROJ_RET_OK) && + BLI_lasso_is_point_inside(mcords, moves, screen_co[0], screen_co[1], IS_CLIPPED) && + key_test_depth(&data, co, screen_co)); + const int sel_op_result = ED_select_op_action_deselected(sel_op, is_select, is_inside); + if (sel_op_result != -1) { + SET_FLAG_FROM_TEST(key->flag, sel_op_result, PEK_SELECT); + point->flag |= PEP_EDIT_RECALC; + data.is_changed = true; + } + } + } + else if (pset->selectmode == SCE_SELECT_END) { + if (point->totkey) { + key = point->keys + point->totkey - 1; + copy_v3_v3(co, key->co); + mul_m4_v3(mat, co); + const bool is_select = key->flag & PEK_SELECT; + const bool is_inside = + ((ED_view3d_project_int_global(ar, co, screen_co, V3D_PROJ_TEST_CLIP_WIN) == + V3D_PROJ_RET_OK) && + BLI_lasso_is_point_inside(mcords, moves, screen_co[0], screen_co[1], IS_CLIPPED) && + key_test_depth(&data, co, screen_co)); + const int sel_op_result = ED_select_op_action_deselected(sel_op, is_select, is_inside); + if (sel_op_result != -1) { + SET_FLAG_FROM_TEST(key->flag, sel_op_result, PEK_SELECT); + point->flag |= PEP_EDIT_RECALC; + data.is_changed = true; + } + } + } + } + + if (data.is_changed) { + PE_update_selection(data.depsgraph, scene, ob, 1); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_SELECTED, ob); + return OPERATOR_FINISHED; + } + return OPERATOR_CANCELLED; } /*************************** hide operator **************************/ static int hide_exec(bContext *C, wmOperator *op) { - Object *ob = CTX_data_active_object(C); - Scene *scene = CTX_data_scene(C); - Depsgraph *depsgraph = CTX_data_depsgraph(C); - - PTCacheEdit *edit = PE_get_current(scene, ob); - POINT_P; KEY_K; - - - if (RNA_enum_get(op->ptr, "unselected")) { - LOOP_UNSELECTED_POINTS { - point->flag |= PEP_HIDE; - point->flag |= PEP_EDIT_RECALC; - - LOOP_KEYS { - key->flag &= ~PEK_SELECT; - } - } - } - else { - LOOP_SELECTED_POINTS { - point->flag |= PEP_HIDE; - point->flag |= PEP_EDIT_RECALC; - - LOOP_KEYS { - key->flag &= ~PEK_SELECT; - } - } - } - - PE_update_selection(depsgraph, scene, ob, 1); - WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_SELECTED, ob); - - return OPERATOR_FINISHED; + Object *ob = CTX_data_active_object(C); + Scene *scene = CTX_data_scene(C); + Depsgraph *depsgraph = CTX_data_depsgraph(C); + + PTCacheEdit *edit = PE_get_current(scene, ob); + POINT_P; + KEY_K; + + if (RNA_enum_get(op->ptr, "unselected")) { + LOOP_UNSELECTED_POINTS + { + point->flag |= PEP_HIDE; + point->flag |= PEP_EDIT_RECALC; + + LOOP_KEYS + { + key->flag &= ~PEK_SELECT; + } + } + } + else { + LOOP_SELECTED_POINTS + { + point->flag |= PEP_HIDE; + point->flag |= PEP_EDIT_RECALC; + + LOOP_KEYS + { + key->flag &= ~PEK_SELECT; + } + } + } + + PE_update_selection(depsgraph, scene, ob, 1); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_SELECTED, ob); + + return OPERATOR_FINISHED; } void PARTICLE_OT_hide(wmOperatorType *ot) { - /* identifiers */ - ot->name = "Hide Selected"; - ot->idname = "PARTICLE_OT_hide"; - ot->description = "Hide selected particles"; + /* identifiers */ + ot->name = "Hide Selected"; + ot->idname = "PARTICLE_OT_hide"; + ot->description = "Hide selected particles"; - /* api callbacks */ - ot->exec = hide_exec; - ot->poll = PE_poll; + /* api callbacks */ + ot->exec = hide_exec; + ot->poll = PE_poll; - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; - /* props */ - RNA_def_boolean(ot->srna, "unselected", 0, "Unselected", "Hide unselected rather than selected"); + /* props */ + RNA_def_boolean(ot->srna, "unselected", 0, "Unselected", "Hide unselected rather than selected"); } /*************************** reveal operator **************************/ static int reveal_exec(bContext *C, wmOperator *op) { - Object *ob = CTX_data_active_object(C); - Scene *scene = CTX_data_scene(C); - Depsgraph *depsgraph = CTX_data_depsgraph(C); - PTCacheEdit *edit = PE_get_current(scene, ob); - const bool select = RNA_boolean_get(op->ptr, "select"); - POINT_P; KEY_K; + Object *ob = CTX_data_active_object(C); + Scene *scene = CTX_data_scene(C); + Depsgraph *depsgraph = CTX_data_depsgraph(C); + PTCacheEdit *edit = PE_get_current(scene, ob); + const bool select = RNA_boolean_get(op->ptr, "select"); + POINT_P; + KEY_K; - LOOP_POINTS { - if (point->flag & PEP_HIDE) { - point->flag &= ~PEP_HIDE; - point->flag |= PEP_EDIT_RECALC; + LOOP_POINTS + { + if (point->flag & PEP_HIDE) { + point->flag &= ~PEP_HIDE; + point->flag |= PEP_EDIT_RECALC; - LOOP_KEYS { - SET_FLAG_FROM_TEST(key->flag, select, PEK_SELECT); - } - } - } + LOOP_KEYS + { + SET_FLAG_FROM_TEST(key->flag, select, PEK_SELECT); + } + } + } - PE_update_selection(depsgraph, scene, ob, 1); - WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_SELECTED, ob); + PE_update_selection(depsgraph, scene, ob, 1); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_SELECTED, ob); - return OPERATOR_FINISHED; + return OPERATOR_FINISHED; } void PARTICLE_OT_reveal(wmOperatorType *ot) { - /* identifiers */ - ot->name = "Reveal"; - ot->idname = "PARTICLE_OT_reveal"; - ot->description = "Show hidden particles"; + /* identifiers */ + ot->name = "Reveal"; + ot->idname = "PARTICLE_OT_reveal"; + ot->description = "Show hidden particles"; - /* api callbacks */ - ot->exec = reveal_exec; - ot->poll = PE_poll; + /* api callbacks */ + ot->exec = reveal_exec; + ot->poll = PE_poll; - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; - /* props */ - RNA_def_boolean(ot->srna, "select", true, "Select", ""); + /* props */ + RNA_def_boolean(ot->srna, "select", true, "Select", ""); } /************************ select less operator ************************/ static void select_less_keys(PEData *data, int point_index) { - PTCacheEdit *edit = data->edit; - PTCacheEditPoint *point = edit->points + point_index; - KEY_K; - - LOOP_SELECTED_KEYS { - if (k == 0) { - if (((key + 1)->flag & PEK_SELECT) == 0) - key->flag |= PEK_TAG; - } - else if (k == point->totkey - 1) { - if (((key - 1)->flag & PEK_SELECT) == 0) - key->flag |= PEK_TAG; - } - else { - if ((((key - 1)->flag & (key + 1)->flag) & PEK_SELECT) == 0) - key->flag |= PEK_TAG; - } - } - - LOOP_KEYS { - if ((key->flag & PEK_TAG) && (key->flag & PEK_SELECT)) { - key->flag &= ~(PEK_TAG | PEK_SELECT); - point->flag |= PEP_EDIT_RECALC; /* redraw selection only */ - data->is_changed = true; - } - } + PTCacheEdit *edit = data->edit; + PTCacheEditPoint *point = edit->points + point_index; + KEY_K; + + LOOP_SELECTED_KEYS + { + if (k == 0) { + if (((key + 1)->flag & PEK_SELECT) == 0) + key->flag |= PEK_TAG; + } + else if (k == point->totkey - 1) { + if (((key - 1)->flag & PEK_SELECT) == 0) + key->flag |= PEK_TAG; + } + else { + if ((((key - 1)->flag & (key + 1)->flag) & PEK_SELECT) == 0) + key->flag |= PEK_TAG; + } + } + + LOOP_KEYS + { + if ((key->flag & PEK_TAG) && (key->flag & PEK_SELECT)) { + key->flag &= ~(PEK_TAG | PEK_SELECT); + point->flag |= PEP_EDIT_RECALC; /* redraw selection only */ + data->is_changed = true; + } + } } static int select_less_exec(bContext *C, wmOperator *UNUSED(op)) { - PEData data; + PEData data; - PE_set_data(C, &data); - foreach_point(&data, select_less_keys); + PE_set_data(C, &data); + foreach_point(&data, select_less_keys); - PE_update_selection(data.depsgraph, data.scene, data.ob, 1); - WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_SELECTED, data.ob); + PE_update_selection(data.depsgraph, data.scene, data.ob, 1); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_SELECTED, data.ob); - return OPERATOR_FINISHED; + return OPERATOR_FINISHED; } void PARTICLE_OT_select_less(wmOperatorType *ot) { - /* identifiers */ - ot->name = "Select Less"; - ot->idname = "PARTICLE_OT_select_less"; - ot->description = "Deselect boundary selected keys of each particle"; + /* identifiers */ + ot->name = "Select Less"; + ot->idname = "PARTICLE_OT_select_less"; + ot->description = "Deselect boundary selected keys of each particle"; - /* api callbacks */ - ot->exec = select_less_exec; - ot->poll = PE_poll; + /* api callbacks */ + ot->exec = select_less_exec; + ot->poll = PE_poll; - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } /************************ select more operator ************************/ static void select_more_keys(PEData *data, int point_index) { - PTCacheEdit *edit = data->edit; - PTCacheEditPoint *point = edit->points + point_index; - KEY_K; - - LOOP_KEYS { - if (key->flag & PEK_SELECT) continue; - - if (k == 0) { - if ((key + 1)->flag & PEK_SELECT) - key->flag |= PEK_TAG; - } - else if (k == point->totkey - 1) { - if ((key - 1)->flag & PEK_SELECT) - key->flag |= PEK_TAG; - } - else { - if (((key - 1)->flag | (key + 1)->flag) & PEK_SELECT) - key->flag |= PEK_TAG; - } - } - - LOOP_KEYS { - if ((key->flag & PEK_TAG) && (key->flag & PEK_SELECT) == 0) { - key->flag &= ~PEK_TAG; - key->flag |= PEK_SELECT; - point->flag |= PEP_EDIT_RECALC; /* redraw selection only */ - data->is_changed = true; - } - } + PTCacheEdit *edit = data->edit; + PTCacheEditPoint *point = edit->points + point_index; + KEY_K; + + LOOP_KEYS + { + if (key->flag & PEK_SELECT) + continue; + + if (k == 0) { + if ((key + 1)->flag & PEK_SELECT) + key->flag |= PEK_TAG; + } + else if (k == point->totkey - 1) { + if ((key - 1)->flag & PEK_SELECT) + key->flag |= PEK_TAG; + } + else { + if (((key - 1)->flag | (key + 1)->flag) & PEK_SELECT) + key->flag |= PEK_TAG; + } + } + + LOOP_KEYS + { + if ((key->flag & PEK_TAG) && (key->flag & PEK_SELECT) == 0) { + key->flag &= ~PEK_TAG; + key->flag |= PEK_SELECT; + point->flag |= PEP_EDIT_RECALC; /* redraw selection only */ + data->is_changed = true; + } + } } static int select_more_exec(bContext *C, wmOperator *UNUSED(op)) { - PEData data; + PEData data; - PE_set_data(C, &data); - foreach_point(&data, select_more_keys); + PE_set_data(C, &data); + foreach_point(&data, select_more_keys); - PE_update_selection(data.depsgraph, data.scene, data.ob, 1); - WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_SELECTED, data.ob); + PE_update_selection(data.depsgraph, data.scene, data.ob, 1); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_SELECTED, data.ob); - return OPERATOR_FINISHED; + return OPERATOR_FINISHED; } void PARTICLE_OT_select_more(wmOperatorType *ot) { - /* identifiers */ - ot->name = "Select More"; - ot->idname = "PARTICLE_OT_select_more"; - ot->description = "Select keys linked to boundary selected keys of each particle"; + /* identifiers */ + ot->name = "Select More"; + ot->idname = "PARTICLE_OT_select_more"; + ot->description = "Select keys linked to boundary selected keys of each particle"; - /* api callbacks */ - ot->exec = select_more_exec; - ot->poll = PE_poll; + /* api callbacks */ + ot->exec = select_more_exec; + ot->poll = PE_poll; - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } /************************ rekey operator ************************/ static void rekey_particle(PEData *data, int pa_index) { - PTCacheEdit *edit = data->edit; - ParticleSystem *psys = edit->psys; - ParticleSimulationData sim = {0}; - ParticleData *pa = psys->particles + pa_index; - PTCacheEditPoint *point = edit->points + pa_index; - ParticleKey state; - HairKey *key, *new_keys, *okey; - PTCacheEditKey *ekey; - float dval, sta, end; - int k; - - sim.depsgraph = data->depsgraph; - sim.scene = data->scene; - sim.ob = data->ob; - sim.psys = edit->psys; - - pa->flag |= PARS_REKEY; - - key = new_keys = MEM_callocN(data->totrekey * sizeof(HairKey), "Hair re-key keys"); - - okey = pa->hair; - /* root and tip stay the same */ - copy_v3_v3(key->co, okey->co); - copy_v3_v3((key + data->totrekey - 1)->co, (okey + pa->totkey - 1)->co); - - sta = key->time = okey->time; - end = (key + data->totrekey - 1)->time = (okey + pa->totkey - 1)->time; - dval = (end - sta) / (float)(data->totrekey - 1); - - /* interpolate new keys from old ones */ - for (k = 1, key++; k < data->totrekey - 1; k++, key++) { - state.time = (float)k / (float)(data->totrekey - 1); - psys_get_particle_on_path(&sim, pa_index, &state, 0); - copy_v3_v3(key->co, state.co); - key->time = sta + k * dval; - } - - /* replace keys */ - if (pa->hair) - MEM_freeN(pa->hair); - pa->hair = new_keys; - - point->totkey = pa->totkey = data->totrekey; - - - if (point->keys) - MEM_freeN(point->keys); - ekey = point->keys = MEM_callocN(pa->totkey * sizeof(PTCacheEditKey), "Hair re-key edit keys"); - - for (k = 0, key = pa->hair; k < pa->totkey; k++, key++, ekey++) { - ekey->co = key->co; - ekey->time = &key->time; - ekey->flag |= PEK_SELECT; - if (!(psys->flag & PSYS_GLOBAL_HAIR)) - ekey->flag |= PEK_USE_WCO; - } - - pa->flag &= ~PARS_REKEY; - point->flag |= PEP_EDIT_RECALC; + PTCacheEdit *edit = data->edit; + ParticleSystem *psys = edit->psys; + ParticleSimulationData sim = {0}; + ParticleData *pa = psys->particles + pa_index; + PTCacheEditPoint *point = edit->points + pa_index; + ParticleKey state; + HairKey *key, *new_keys, *okey; + PTCacheEditKey *ekey; + float dval, sta, end; + int k; + + sim.depsgraph = data->depsgraph; + sim.scene = data->scene; + sim.ob = data->ob; + sim.psys = edit->psys; + + pa->flag |= PARS_REKEY; + + key = new_keys = MEM_callocN(data->totrekey * sizeof(HairKey), "Hair re-key keys"); + + okey = pa->hair; + /* root and tip stay the same */ + copy_v3_v3(key->co, okey->co); + copy_v3_v3((key + data->totrekey - 1)->co, (okey + pa->totkey - 1)->co); + + sta = key->time = okey->time; + end = (key + data->totrekey - 1)->time = (okey + pa->totkey - 1)->time; + dval = (end - sta) / (float)(data->totrekey - 1); + + /* interpolate new keys from old ones */ + for (k = 1, key++; k < data->totrekey - 1; k++, key++) { + state.time = (float)k / (float)(data->totrekey - 1); + psys_get_particle_on_path(&sim, pa_index, &state, 0); + copy_v3_v3(key->co, state.co); + key->time = sta + k * dval; + } + + /* replace keys */ + if (pa->hair) + MEM_freeN(pa->hair); + pa->hair = new_keys; + + point->totkey = pa->totkey = data->totrekey; + + if (point->keys) + MEM_freeN(point->keys); + ekey = point->keys = MEM_callocN(pa->totkey * sizeof(PTCacheEditKey), "Hair re-key edit keys"); + + for (k = 0, key = pa->hair; k < pa->totkey; k++, key++, ekey++) { + ekey->co = key->co; + ekey->time = &key->time; + ekey->flag |= PEK_SELECT; + if (!(psys->flag & PSYS_GLOBAL_HAIR)) + ekey->flag |= PEK_USE_WCO; + } + + pa->flag &= ~PARS_REKEY; + point->flag |= PEP_EDIT_RECALC; } static int rekey_exec(bContext *C, wmOperator *op) { - PEData data; + PEData data; - PE_set_data(C, &data); + PE_set_data(C, &data); - data.dval = 1.0f / (float)(data.totrekey - 1); - data.totrekey = RNA_int_get(op->ptr, "keys_number"); + data.dval = 1.0f / (float)(data.totrekey - 1); + data.totrekey = RNA_int_get(op->ptr, "keys_number"); - foreach_selected_point(&data, rekey_particle); + foreach_selected_point(&data, rekey_particle); - recalc_lengths(data.edit); - PE_update_object(data.depsgraph, data.scene, data.ob, 1); - WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_EDITED, data.ob); + recalc_lengths(data.edit); + PE_update_object(data.depsgraph, data.scene, data.ob, 1); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_EDITED, data.ob); - return OPERATOR_FINISHED; + return OPERATOR_FINISHED; } void PARTICLE_OT_rekey(wmOperatorType *ot) { - /* identifiers */ - ot->name = "Rekey"; - ot->idname = "PARTICLE_OT_rekey"; - ot->description = "Change the number of keys of selected particles (root and tip keys included)"; + /* identifiers */ + ot->name = "Rekey"; + ot->idname = "PARTICLE_OT_rekey"; + ot->description = "Change the number of keys of selected particles (root and tip keys included)"; - /* api callbacks */ - ot->exec = rekey_exec; - ot->invoke = WM_operator_props_popup; - ot->poll = PE_hair_poll; + /* api callbacks */ + ot->exec = rekey_exec; + ot->invoke = WM_operator_props_popup; + ot->poll = PE_hair_poll; - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; - /* properties */ - RNA_def_int(ot->srna, "keys_number", 2, 2, INT_MAX, "Number of Keys", "", 2, 100); + /* properties */ + RNA_def_int(ot->srna, "keys_number", 2, 2, INT_MAX, "Number of Keys", "", 2, 100); } -static void rekey_particle_to_time(const bContext *C, Scene *scene, Object *ob, int pa_index, float path_time) +static void rekey_particle_to_time( + const bContext *C, Scene *scene, Object *ob, int pa_index, float path_time) { - PTCacheEdit *edit = PE_get_current(scene, ob); - ParticleSystem *psys; - ParticleSimulationData sim = {0}; - ParticleData *pa; - ParticleKey state; - HairKey *new_keys, *key; - PTCacheEditKey *ekey; - int k; + PTCacheEdit *edit = PE_get_current(scene, ob); + ParticleSystem *psys; + ParticleSimulationData sim = {0}; + ParticleData *pa; + ParticleKey state; + HairKey *new_keys, *key; + PTCacheEditKey *ekey; + int k; - if (!edit || !edit->psys) return; + if (!edit || !edit->psys) + return; - psys = edit->psys; + psys = edit->psys; - sim.depsgraph = CTX_data_depsgraph(C); - sim.scene = scene; - sim.ob = ob; - sim.psys = psys; + sim.depsgraph = CTX_data_depsgraph(C); + sim.scene = scene; + sim.ob = ob; + sim.psys = psys; - pa = psys->particles + pa_index; + pa = psys->particles + pa_index; - pa->flag |= PARS_REKEY; + pa->flag |= PARS_REKEY; - key = new_keys = MEM_dupallocN(pa->hair); + key = new_keys = MEM_dupallocN(pa->hair); - /* interpolate new keys from old ones (roots stay the same) */ - for (k = 1, key++; k < pa->totkey; k++, key++) { - state.time = path_time * (float)k / (float)(pa->totkey - 1); - psys_get_particle_on_path(&sim, pa_index, &state, 0); - copy_v3_v3(key->co, state.co); - } + /* interpolate new keys from old ones (roots stay the same) */ + for (k = 1, key++; k < pa->totkey; k++, key++) { + state.time = path_time * (float)k / (float)(pa->totkey - 1); + psys_get_particle_on_path(&sim, pa_index, &state, 0); + copy_v3_v3(key->co, state.co); + } - /* replace hair keys */ - if (pa->hair) - MEM_freeN(pa->hair); - pa->hair = new_keys; + /* replace hair keys */ + if (pa->hair) + MEM_freeN(pa->hair); + pa->hair = new_keys; - /* update edit pointers */ - for (k = 0, key = pa->hair, ekey = edit->points[pa_index].keys; k < pa->totkey; k++, key++, ekey++) { - ekey->co = key->co; - ekey->time = &key->time; - } + /* update edit pointers */ + for (k = 0, key = pa->hair, ekey = edit->points[pa_index].keys; k < pa->totkey; + k++, key++, ekey++) { + ekey->co = key->co; + ekey->time = &key->time; + } - pa->flag &= ~PARS_REKEY; + pa->flag &= ~PARS_REKEY; } /************************* utilities **************************/ static int remove_tagged_particles(Object *ob, ParticleSystem *psys, int mirror) { - PTCacheEdit *edit = psys->edit; - ParticleData *pa, *npa = 0, *new_pars = 0; - POINT_P; - PTCacheEditPoint *npoint = 0, *new_points = 0; - ParticleSystemModifierData *psmd_eval; - int i, new_totpart = psys->totpart, removed = 0; - - if (mirror) { - /* mirror tags */ - psmd_eval = edit->psmd_eval; - - LOOP_TAGGED_POINTS { - PE_mirror_particle(ob, psmd_eval->mesh_final, psys, psys->particles + p, NULL); - } - } - - LOOP_TAGGED_POINTS { - new_totpart--; - removed++; - } - - if (new_totpart != psys->totpart) { - if (new_totpart) { - npa = new_pars = MEM_callocN(new_totpart * sizeof(ParticleData), "ParticleData array"); - npoint = new_points = MEM_callocN(new_totpart * sizeof(PTCacheEditPoint), "PTCacheEditKey array"); - - if (ELEM(NULL, new_pars, new_points)) { - /* allocation error! */ - if (new_pars) - MEM_freeN(new_pars); - if (new_points) - MEM_freeN(new_points); - return 0; - } - } - - pa = psys->particles; - point = edit->points; - for (i = 0; i < psys->totpart; i++, pa++, point++) { - if (point->flag & PEP_TAG) { - if (point->keys) - MEM_freeN(point->keys); - if (pa->hair) - MEM_freeN(pa->hair); - } - else { - memcpy(npa, pa, sizeof(ParticleData)); - memcpy(npoint, point, sizeof(PTCacheEditPoint)); - npa++; - npoint++; - } - } - - if (psys->particles) MEM_freeN(psys->particles); - psys->particles = new_pars; - - if (edit->points) MEM_freeN(edit->points); - edit->points = new_points; - - if (edit->mirror_cache) { - MEM_freeN(edit->mirror_cache); - edit->mirror_cache = NULL; - } - - if (psys->child) { - MEM_freeN(psys->child); - psys->child = NULL; - psys->totchild = 0; - } - - edit->totpoint = psys->totpart = new_totpart; - } - - return removed; + PTCacheEdit *edit = psys->edit; + ParticleData *pa, *npa = 0, *new_pars = 0; + POINT_P; + PTCacheEditPoint *npoint = 0, *new_points = 0; + ParticleSystemModifierData *psmd_eval; + int i, new_totpart = psys->totpart, removed = 0; + + if (mirror) { + /* mirror tags */ + psmd_eval = edit->psmd_eval; + + LOOP_TAGGED_POINTS + { + PE_mirror_particle(ob, psmd_eval->mesh_final, psys, psys->particles + p, NULL); + } + } + + LOOP_TAGGED_POINTS + { + new_totpart--; + removed++; + } + + if (new_totpart != psys->totpart) { + if (new_totpart) { + npa = new_pars = MEM_callocN(new_totpart * sizeof(ParticleData), "ParticleData array"); + npoint = new_points = MEM_callocN(new_totpart * sizeof(PTCacheEditPoint), + "PTCacheEditKey array"); + + if (ELEM(NULL, new_pars, new_points)) { + /* allocation error! */ + if (new_pars) + MEM_freeN(new_pars); + if (new_points) + MEM_freeN(new_points); + return 0; + } + } + + pa = psys->particles; + point = edit->points; + for (i = 0; i < psys->totpart; i++, pa++, point++) { + if (point->flag & PEP_TAG) { + if (point->keys) + MEM_freeN(point->keys); + if (pa->hair) + MEM_freeN(pa->hair); + } + else { + memcpy(npa, pa, sizeof(ParticleData)); + memcpy(npoint, point, sizeof(PTCacheEditPoint)); + npa++; + npoint++; + } + } + + if (psys->particles) + MEM_freeN(psys->particles); + psys->particles = new_pars; + + if (edit->points) + MEM_freeN(edit->points); + edit->points = new_points; + + if (edit->mirror_cache) { + MEM_freeN(edit->mirror_cache); + edit->mirror_cache = NULL; + } + + if (psys->child) { + MEM_freeN(psys->child); + psys->child = NULL; + psys->totchild = 0; + } + + edit->totpoint = psys->totpart = new_totpart; + } + + return removed; } static void remove_tagged_keys(Object *ob, ParticleSystem *psys) { - PTCacheEdit *edit = psys->edit; - ParticleData *pa; - HairKey *hkey, *nhkey, *new_hkeys = 0; - POINT_P; KEY_K; - PTCacheEditKey *nkey, *new_keys; - ParticleSystemModifierData *psmd_eval; - short new_totkey; - - if (pe_x_mirror(ob)) { - /* mirror key tags */ - psmd_eval = psys_get_modifier(ob, psys); - - LOOP_POINTS { - LOOP_TAGGED_KEYS { - PE_mirror_particle(ob, psmd_eval->mesh_final, psys, psys->particles + p, NULL); - break; - } - } - } - - LOOP_POINTS { - new_totkey = point->totkey; - LOOP_TAGGED_KEYS { - new_totkey--; - } - /* we can't have elements with less than two keys*/ - if (new_totkey < 2) - point->flag |= PEP_TAG; - } - remove_tagged_particles(ob, psys, pe_x_mirror(ob)); - - LOOP_POINTS { - pa = psys->particles + p; - new_totkey = pa->totkey; - - LOOP_TAGGED_KEYS { - new_totkey--; - } - - if (new_totkey != pa->totkey) { - nhkey = new_hkeys = MEM_callocN(new_totkey * sizeof(HairKey), "HairKeys"); - nkey = new_keys = MEM_callocN(new_totkey * sizeof(PTCacheEditKey), "particle edit keys"); - - hkey = pa->hair; - LOOP_KEYS { - while (key->flag & PEK_TAG && hkey < pa->hair + pa->totkey) { - key++; - hkey++; - } - - if (hkey < pa->hair + pa->totkey) { - copy_v3_v3(nhkey->co, hkey->co); - nhkey->editflag = hkey->editflag; - nhkey->time = hkey->time; - nhkey->weight = hkey->weight; - - nkey->co = nhkey->co; - nkey->time = &nhkey->time; - /* these can be copied from old edit keys */ - nkey->flag = key->flag; - nkey->ftime = key->ftime; - nkey->length = key->length; - copy_v3_v3(nkey->world_co, key->world_co); - } - nkey++; - nhkey++; - hkey++; - } - - if (pa->hair) - MEM_freeN(pa->hair); - - if (point->keys) - MEM_freeN(point->keys); - - pa->hair = new_hkeys; - point->keys = new_keys; - - point->totkey = pa->totkey = new_totkey; - - /* flag for recalculating length */ - point->flag |= PEP_EDIT_RECALC; - } - } + PTCacheEdit *edit = psys->edit; + ParticleData *pa; + HairKey *hkey, *nhkey, *new_hkeys = 0; + POINT_P; + KEY_K; + PTCacheEditKey *nkey, *new_keys; + ParticleSystemModifierData *psmd_eval; + short new_totkey; + + if (pe_x_mirror(ob)) { + /* mirror key tags */ + psmd_eval = psys_get_modifier(ob, psys); + + LOOP_POINTS + { + LOOP_TAGGED_KEYS + { + PE_mirror_particle(ob, psmd_eval->mesh_final, psys, psys->particles + p, NULL); + break; + } + } + } + + LOOP_POINTS + { + new_totkey = point->totkey; + LOOP_TAGGED_KEYS + { + new_totkey--; + } + /* we can't have elements with less than two keys*/ + if (new_totkey < 2) + point->flag |= PEP_TAG; + } + remove_tagged_particles(ob, psys, pe_x_mirror(ob)); + + LOOP_POINTS + { + pa = psys->particles + p; + new_totkey = pa->totkey; + + LOOP_TAGGED_KEYS + { + new_totkey--; + } + + if (new_totkey != pa->totkey) { + nhkey = new_hkeys = MEM_callocN(new_totkey * sizeof(HairKey), "HairKeys"); + nkey = new_keys = MEM_callocN(new_totkey * sizeof(PTCacheEditKey), "particle edit keys"); + + hkey = pa->hair; + LOOP_KEYS + { + while (key->flag & PEK_TAG && hkey < pa->hair + pa->totkey) { + key++; + hkey++; + } + + if (hkey < pa->hair + pa->totkey) { + copy_v3_v3(nhkey->co, hkey->co); + nhkey->editflag = hkey->editflag; + nhkey->time = hkey->time; + nhkey->weight = hkey->weight; + + nkey->co = nhkey->co; + nkey->time = &nhkey->time; + /* these can be copied from old edit keys */ + nkey->flag = key->flag; + nkey->ftime = key->ftime; + nkey->length = key->length; + copy_v3_v3(nkey->world_co, key->world_co); + } + nkey++; + nhkey++; + hkey++; + } + + if (pa->hair) + MEM_freeN(pa->hair); + + if (point->keys) + MEM_freeN(point->keys); + + pa->hair = new_hkeys; + point->keys = new_keys; + + point->totkey = pa->totkey = new_totkey; + + /* flag for recalculating length */ + point->flag |= PEP_EDIT_RECALC; + } + } } /************************ subdivide opertor *********************/ @@ -2740,308 +2827,326 @@ static void remove_tagged_keys(Object *ob, ParticleSystem *psys) /* works like normal edit mode subdivide, inserts keys between neighboring selected keys */ static void subdivide_particle(PEData *data, int pa_index) { - PTCacheEdit *edit = data->edit; - ParticleSystem *psys = edit->psys; - ParticleSimulationData sim = {0}; - ParticleData *pa = psys->particles + pa_index; - PTCacheEditPoint *point = edit->points + pa_index; - ParticleKey state; - HairKey *key, *nkey, *new_keys; - PTCacheEditKey *ekey, *nekey, *new_ekeys; + PTCacheEdit *edit = data->edit; + ParticleSystem *psys = edit->psys; + ParticleSimulationData sim = {0}; + ParticleData *pa = psys->particles + pa_index; + PTCacheEditPoint *point = edit->points + pa_index; + ParticleKey state; + HairKey *key, *nkey, *new_keys; + PTCacheEditKey *ekey, *nekey, *new_ekeys; - int k; - short totnewkey = 0; - float endtime; + int k; + short totnewkey = 0; + float endtime; - sim.depsgraph = data->depsgraph; - sim.scene = data->scene; - sim.ob = data->ob; - sim.psys = edit->psys; + sim.depsgraph = data->depsgraph; + sim.scene = data->scene; + sim.ob = data->ob; + sim.psys = edit->psys; - for (k = 0, ekey = point->keys; k < pa->totkey - 1; k++, ekey++) { - if (ekey->flag & PEK_SELECT && (ekey + 1)->flag & PEK_SELECT) - totnewkey++; - } + for (k = 0, ekey = point->keys; k < pa->totkey - 1; k++, ekey++) { + if (ekey->flag & PEK_SELECT && (ekey + 1)->flag & PEK_SELECT) + totnewkey++; + } - if (totnewkey == 0) return; + if (totnewkey == 0) + return; - pa->flag |= PARS_REKEY; + pa->flag |= PARS_REKEY; - nkey = new_keys = MEM_callocN((pa->totkey + totnewkey) * (sizeof(HairKey)), "Hair subdivide keys"); - nekey = new_ekeys = MEM_callocN((pa->totkey + totnewkey) * (sizeof(PTCacheEditKey)), "Hair subdivide edit keys"); + nkey = new_keys = MEM_callocN((pa->totkey + totnewkey) * (sizeof(HairKey)), + "Hair subdivide keys"); + nekey = new_ekeys = MEM_callocN((pa->totkey + totnewkey) * (sizeof(PTCacheEditKey)), + "Hair subdivide edit keys"); - key = pa->hair; - endtime = key[pa->totkey - 1].time; + key = pa->hair; + endtime = key[pa->totkey - 1].time; - for (k = 0, ekey = point->keys; k < pa->totkey - 1; k++, key++, ekey++) { + for (k = 0, ekey = point->keys; k < pa->totkey - 1; k++, key++, ekey++) { - memcpy(nkey, key, sizeof(HairKey)); - memcpy(nekey, ekey, sizeof(PTCacheEditKey)); + memcpy(nkey, key, sizeof(HairKey)); + memcpy(nekey, ekey, sizeof(PTCacheEditKey)); - nekey->co = nkey->co; - nekey->time = &nkey->time; + nekey->co = nkey->co; + nekey->time = &nkey->time; - nkey++; - nekey++; + nkey++; + nekey++; - if (ekey->flag & PEK_SELECT && (ekey + 1)->flag & PEK_SELECT) { - nkey->time = (key->time + (key + 1)->time) * 0.5f; - state.time = (endtime != 0.0f) ? nkey->time / endtime : 0.0f; - psys_get_particle_on_path(&sim, pa_index, &state, 0); - copy_v3_v3(nkey->co, state.co); + if (ekey->flag & PEK_SELECT && (ekey + 1)->flag & PEK_SELECT) { + nkey->time = (key->time + (key + 1)->time) * 0.5f; + state.time = (endtime != 0.0f) ? nkey->time / endtime : 0.0f; + psys_get_particle_on_path(&sim, pa_index, &state, 0); + copy_v3_v3(nkey->co, state.co); - nekey->co = nkey->co; - nekey->time = &nkey->time; - nekey->flag |= PEK_SELECT; - if (!(psys->flag & PSYS_GLOBAL_HAIR)) - nekey->flag |= PEK_USE_WCO; + nekey->co = nkey->co; + nekey->time = &nkey->time; + nekey->flag |= PEK_SELECT; + if (!(psys->flag & PSYS_GLOBAL_HAIR)) + nekey->flag |= PEK_USE_WCO; - nekey++; - nkey++; - } - } - /*tip still not copied*/ - memcpy(nkey, key, sizeof(HairKey)); - memcpy(nekey, ekey, sizeof(PTCacheEditKey)); + nekey++; + nkey++; + } + } + /*tip still not copied*/ + memcpy(nkey, key, sizeof(HairKey)); + memcpy(nekey, ekey, sizeof(PTCacheEditKey)); - nekey->co = nkey->co; - nekey->time = &nkey->time; + nekey->co = nkey->co; + nekey->time = &nkey->time; - if (pa->hair) - MEM_freeN(pa->hair); - pa->hair = new_keys; + if (pa->hair) + MEM_freeN(pa->hair); + pa->hair = new_keys; - if (point->keys) - MEM_freeN(point->keys); - point->keys = new_ekeys; + if (point->keys) + MEM_freeN(point->keys); + point->keys = new_ekeys; - point->totkey = pa->totkey = pa->totkey + totnewkey; - point->flag |= PEP_EDIT_RECALC; - pa->flag &= ~PARS_REKEY; + point->totkey = pa->totkey = pa->totkey + totnewkey; + point->flag |= PEP_EDIT_RECALC; + pa->flag &= ~PARS_REKEY; } static int subdivide_exec(bContext *C, wmOperator *UNUSED(op)) { - PEData data; + PEData data; - PE_set_data(C, &data); - foreach_point(&data, subdivide_particle); + PE_set_data(C, &data); + foreach_point(&data, subdivide_particle); - recalc_lengths(data.edit); - PE_update_selection(data.depsgraph, data.scene, data.ob, 1); - PE_update_object(data.depsgraph, data.scene, data.ob, 1); - DEG_id_tag_update(&data.ob->id, ID_RECALC_SELECT); - WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_EDITED, data.ob); + recalc_lengths(data.edit); + PE_update_selection(data.depsgraph, data.scene, data.ob, 1); + PE_update_object(data.depsgraph, data.scene, data.ob, 1); + DEG_id_tag_update(&data.ob->id, ID_RECALC_SELECT); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_EDITED, data.ob); - return OPERATOR_FINISHED; + return OPERATOR_FINISHED; } void PARTICLE_OT_subdivide(wmOperatorType *ot) { - /* identifiers */ - ot->name = "Subdivide"; - ot->idname = "PARTICLE_OT_subdivide"; - ot->description = "Subdivide selected particles segments (adds keys)"; + /* identifiers */ + ot->name = "Subdivide"; + ot->idname = "PARTICLE_OT_subdivide"; + ot->description = "Subdivide selected particles segments (adds keys)"; - /* api callbacks */ - ot->exec = subdivide_exec; - ot->poll = PE_hair_poll; + /* api callbacks */ + ot->exec = subdivide_exec; + ot->poll = PE_hair_poll; - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } /************************ remove doubles opertor *********************/ static int remove_doubles_exec(bContext *C, wmOperator *op) { - Scene *scene = CTX_data_scene(C); - Object *ob = CTX_data_active_object(C); - PTCacheEdit *edit = PE_get_current(scene, ob); - ParticleSystem *psys = edit->psys; - ParticleSystemModifierData *psmd_eval; - KDTree_3d *tree; - KDTreeNearest_3d nearest[10]; - POINT_P; - float mat[4][4], co[3], threshold = RNA_float_get(op->ptr, "threshold"); - int n, totn, removed, totremoved; + Scene *scene = CTX_data_scene(C); + Object *ob = CTX_data_active_object(C); + PTCacheEdit *edit = PE_get_current(scene, ob); + ParticleSystem *psys = edit->psys; + ParticleSystemModifierData *psmd_eval; + KDTree_3d *tree; + KDTreeNearest_3d nearest[10]; + POINT_P; + float mat[4][4], co[3], threshold = RNA_float_get(op->ptr, "threshold"); + int n, totn, removed, totremoved; - if (psys->flag & PSYS_GLOBAL_HAIR) - return OPERATOR_CANCELLED; + if (psys->flag & PSYS_GLOBAL_HAIR) + return OPERATOR_CANCELLED; - edit = psys->edit; - psmd_eval = edit->psmd_eval; - totremoved = 0; + edit = psys->edit; + psmd_eval = edit->psmd_eval; + totremoved = 0; - do { - removed = 0; + do { + removed = 0; - tree = BLI_kdtree_3d_new(psys->totpart); + tree = BLI_kdtree_3d_new(psys->totpart); - /* insert particles into kd tree */ - LOOP_SELECTED_POINTS { - psys_mat_hair_to_object(ob, psmd_eval->mesh_final, psys->part->from, psys->particles + p, mat); - copy_v3_v3(co, point->keys->co); - mul_m4_v3(mat, co); - BLI_kdtree_3d_insert(tree, p, co); - } + /* insert particles into kd tree */ + LOOP_SELECTED_POINTS + { + psys_mat_hair_to_object( + ob, psmd_eval->mesh_final, psys->part->from, psys->particles + p, mat); + copy_v3_v3(co, point->keys->co); + mul_m4_v3(mat, co); + BLI_kdtree_3d_insert(tree, p, co); + } - BLI_kdtree_3d_balance(tree); + BLI_kdtree_3d_balance(tree); - /* tag particles to be removed */ - LOOP_SELECTED_POINTS { - psys_mat_hair_to_object(ob, psmd_eval->mesh_final, psys->part->from, psys->particles + p, mat); - copy_v3_v3(co, point->keys->co); - mul_m4_v3(mat, co); + /* tag particles to be removed */ + LOOP_SELECTED_POINTS + { + psys_mat_hair_to_object( + ob, psmd_eval->mesh_final, psys->part->from, psys->particles + p, mat); + copy_v3_v3(co, point->keys->co); + mul_m4_v3(mat, co); - totn = BLI_kdtree_3d_find_nearest_n(tree, co, nearest, 10); + totn = BLI_kdtree_3d_find_nearest_n(tree, co, nearest, 10); - for (n = 0; n < totn; n++) { - /* this needs a custom threshold still */ - if (nearest[n].index > p && nearest[n].dist < threshold) { - if (!(point->flag & PEP_TAG)) { - point->flag |= PEP_TAG; - removed++; - } - } - } - } + for (n = 0; n < totn; n++) { + /* this needs a custom threshold still */ + if (nearest[n].index > p && nearest[n].dist < threshold) { + if (!(point->flag & PEP_TAG)) { + point->flag |= PEP_TAG; + removed++; + } + } + } + } - BLI_kdtree_3d_free(tree); + BLI_kdtree_3d_free(tree); - /* remove tagged particles - don't do mirror here! */ - remove_tagged_particles(ob, psys, 0); - totremoved += removed; - } while (removed); + /* remove tagged particles - don't do mirror here! */ + remove_tagged_particles(ob, psys, 0); + totremoved += removed; + } while (removed); - if (totremoved == 0) - return OPERATOR_CANCELLED; + if (totremoved == 0) + return OPERATOR_CANCELLED; - BKE_reportf(op->reports, RPT_INFO, "Removed %d double particles", totremoved); + BKE_reportf(op->reports, RPT_INFO, "Removed %d double particles", totremoved); - DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY); - WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_EDITED, ob); + DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_EDITED, ob); - return OPERATOR_FINISHED; + return OPERATOR_FINISHED; } void PARTICLE_OT_remove_doubles(wmOperatorType *ot) { - /* identifiers */ - ot->name = "Remove Doubles"; - ot->idname = "PARTICLE_OT_remove_doubles"; - ot->description = "Remove selected particles close enough of others"; + /* identifiers */ + ot->name = "Remove Doubles"; + ot->idname = "PARTICLE_OT_remove_doubles"; + ot->description = "Remove selected particles close enough of others"; - /* api callbacks */ - ot->exec = remove_doubles_exec; - ot->poll = PE_hair_poll; + /* api callbacks */ + ot->exec = remove_doubles_exec; + ot->poll = PE_hair_poll; - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; - /* properties */ - RNA_def_float(ot->srna, "threshold", 0.0002f, 0.0f, FLT_MAX, - "Merge Distance", "Threshold distance within which particles are removed", 0.00001f, 0.1f); + /* properties */ + RNA_def_float(ot->srna, + "threshold", + 0.0002f, + 0.0f, + FLT_MAX, + "Merge Distance", + "Threshold distance within which particles are removed", + 0.00001f, + 0.1f); } - static int weight_set_exec(bContext *C, wmOperator *op) { - Scene *scene = CTX_data_scene(C); - ParticleEditSettings *pset = PE_settings(scene); - Object *ob = CTX_data_active_object(C); - PTCacheEdit *edit = PE_get_current(scene, ob); - ParticleSystem *psys = edit->psys; - POINT_P; - KEY_K; - HairKey *hkey; - float weight; - ParticleBrushData *brush = &pset->brush[pset->brushtype]; - float factor = RNA_float_get(op->ptr, "factor"); + Scene *scene = CTX_data_scene(C); + ParticleEditSettings *pset = PE_settings(scene); + Object *ob = CTX_data_active_object(C); + PTCacheEdit *edit = PE_get_current(scene, ob); + ParticleSystem *psys = edit->psys; + POINT_P; + KEY_K; + HairKey *hkey; + float weight; + ParticleBrushData *brush = &pset->brush[pset->brushtype]; + float factor = RNA_float_get(op->ptr, "factor"); - weight = brush->strength; - edit = psys->edit; + weight = brush->strength; + edit = psys->edit; - LOOP_SELECTED_POINTS { - ParticleData *pa = psys->particles + p; + LOOP_SELECTED_POINTS + { + ParticleData *pa = psys->particles + p; - LOOP_SELECTED_KEYS { - hkey = pa->hair + k; - hkey->weight = interpf(weight, hkey->weight, factor); - } - } + LOOP_SELECTED_KEYS + { + hkey = pa->hair + k; + hkey->weight = interpf(weight, hkey->weight, factor); + } + } - DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY); - WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_EDITED, ob); + DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_EDITED, ob); - return OPERATOR_FINISHED; + return OPERATOR_FINISHED; } void PARTICLE_OT_weight_set(wmOperatorType *ot) { - /* identifiers */ - ot->name = "Weight Set"; - ot->idname = "PARTICLE_OT_weight_set"; - ot->description = "Set the weight of selected keys"; + /* identifiers */ + ot->name = "Weight Set"; + ot->idname = "PARTICLE_OT_weight_set"; + ot->description = "Set the weight of selected keys"; - /* api callbacks */ - ot->exec = weight_set_exec; - ot->poll = PE_hair_poll; + /* api callbacks */ + ot->exec = weight_set_exec; + ot->poll = PE_hair_poll; - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; - RNA_def_float(ot->srna, "factor", 1, 0, 1, "Factor", - "Interpolation factor between current brush weight, and keys' weights", 0, 1); + RNA_def_float(ot->srna, + "factor", + 1, + 0, + 1, + "Factor", + "Interpolation factor between current brush weight, and keys' weights", + 0, + 1); } /************************ cursor drawing *******************************/ static void brush_drawcursor(bContext *C, int x, int y, void *UNUSED(customdata)) { - Scene *scene = CTX_data_scene(C); - ParticleEditSettings *pset = PE_settings(scene); - ParticleBrushData *brush; + Scene *scene = CTX_data_scene(C); + ParticleEditSettings *pset = PE_settings(scene); + ParticleBrushData *brush; - if (!WM_toolsystem_active_tool_is_brush(C)) { - return; - } + if (!WM_toolsystem_active_tool_is_brush(C)) { + return; + } - brush = &pset->brush[pset->brushtype]; + brush = &pset->brush[pset->brushtype]; - if (brush) { - uint pos = GPU_vertformat_attr_add(immVertexFormat(), "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT); - immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR); + if (brush) { + uint pos = GPU_vertformat_attr_add(immVertexFormat(), "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT); + immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR); - immUniformColor4ub(255, 255, 255, 128); + immUniformColor4ub(255, 255, 255, 128); - GPU_line_smooth(true); - GPU_blend(true); + GPU_line_smooth(true); + GPU_blend(true); - imm_draw_circle_wire_2d(pos, (float)x, (float)y, pe_brush_size_get(scene, brush), 40); + imm_draw_circle_wire_2d(pos, (float)x, (float)y, pe_brush_size_get(scene, brush), 40); - GPU_blend(false); - GPU_line_smooth(false); + GPU_blend(false); + GPU_line_smooth(false); - immUnbindProgram(); - } + immUnbindProgram(); + } } static void toggle_particle_cursor(bContext *C, int enable) { - ParticleEditSettings *pset = PE_settings(CTX_data_scene(C)); + ParticleEditSettings *pset = PE_settings(CTX_data_scene(C)); - if (pset->paintcursor && !enable) { - WM_paint_cursor_end(CTX_wm_manager(C), pset->paintcursor); - pset->paintcursor = NULL; - } - else if (enable) - pset->paintcursor = WM_paint_cursor_activate( - CTX_wm_manager(C), - SPACE_VIEW3D, RGN_TYPE_WINDOW, - PE_poll_view3d, - brush_drawcursor, - NULL); + if (pset->paintcursor && !enable) { + WM_paint_cursor_end(CTX_wm_manager(C), pset->paintcursor); + pset->paintcursor = NULL; + } + else if (enable) + pset->paintcursor = WM_paint_cursor_activate( + CTX_wm_manager(C), SPACE_VIEW3D, RGN_TYPE_WINDOW, PE_poll_view3d, brush_drawcursor, NULL); } /*************************** delete operator **************************/ @@ -3049,2126 +3154,2190 @@ static void toggle_particle_cursor(bContext *C, int enable) enum { DEL_PARTICLE, DEL_KEY }; static const EnumPropertyItem delete_type_items[] = { - {DEL_PARTICLE, "PARTICLE", 0, "Particle", ""}, - {DEL_KEY, "KEY", 0, "Key", ""}, - {0, NULL, 0, NULL, NULL}, + {DEL_PARTICLE, "PARTICLE", 0, "Particle", ""}, + {DEL_KEY, "KEY", 0, "Key", ""}, + {0, NULL, 0, NULL, NULL}, }; static void set_delete_particle(PEData *data, int pa_index) { - PTCacheEdit *edit = data->edit; + PTCacheEdit *edit = data->edit; - edit->points[pa_index].flag |= PEP_TAG; + edit->points[pa_index].flag |= PEP_TAG; } -static void set_delete_particle_key(PEData *data, int pa_index, int key_index, bool UNUSED(is_inside)) +static void set_delete_particle_key(PEData *data, + int pa_index, + int key_index, + bool UNUSED(is_inside)) { - PTCacheEdit *edit = data->edit; + PTCacheEdit *edit = data->edit; - edit->points[pa_index].keys[key_index].flag |= PEK_TAG; + edit->points[pa_index].keys[key_index].flag |= PEK_TAG; } static int delete_exec(bContext *C, wmOperator *op) { - PEData data; - int type = RNA_enum_get(op->ptr, "type"); + PEData data; + int type = RNA_enum_get(op->ptr, "type"); - PE_set_data(C, &data); + PE_set_data(C, &data); - if (type == DEL_KEY) { - foreach_selected_key(&data, set_delete_particle_key); - remove_tagged_keys(data.ob, data.edit->psys); - recalc_lengths(data.edit); - } - else if (type == DEL_PARTICLE) { - foreach_selected_point(&data, set_delete_particle); - remove_tagged_particles(data.ob, data.edit->psys, pe_x_mirror(data.ob)); - recalc_lengths(data.edit); - } + if (type == DEL_KEY) { + foreach_selected_key(&data, set_delete_particle_key); + remove_tagged_keys(data.ob, data.edit->psys); + recalc_lengths(data.edit); + } + else if (type == DEL_PARTICLE) { + foreach_selected_point(&data, set_delete_particle); + remove_tagged_particles(data.ob, data.edit->psys, pe_x_mirror(data.ob)); + recalc_lengths(data.edit); + } - DEG_id_tag_update(&data.ob->id, ID_RECALC_GEOMETRY); - WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_EDITED, data.ob); + DEG_id_tag_update(&data.ob->id, ID_RECALC_GEOMETRY); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_EDITED, data.ob); - return OPERATOR_FINISHED; + return OPERATOR_FINISHED; } void PARTICLE_OT_delete(wmOperatorType *ot) { - /* identifiers */ - ot->name = "Delete"; - ot->idname = "PARTICLE_OT_delete"; - ot->description = "Delete selected particles or keys"; + /* identifiers */ + ot->name = "Delete"; + ot->idname = "PARTICLE_OT_delete"; + ot->description = "Delete selected particles or keys"; - /* api callbacks */ - ot->exec = delete_exec; - ot->invoke = WM_menu_invoke; - ot->poll = PE_hair_poll; + /* api callbacks */ + ot->exec = delete_exec; + ot->invoke = WM_menu_invoke; + ot->poll = PE_hair_poll; - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; - /* properties */ - ot->prop = RNA_def_enum(ot->srna, "type", delete_type_items, DEL_PARTICLE, "Type", "Delete a full particle or only keys"); + /* properties */ + ot->prop = RNA_def_enum(ot->srna, + "type", + delete_type_items, + DEL_PARTICLE, + "Type", + "Delete a full particle or only keys"); } /*************************** mirror operator **************************/ -static void PE_mirror_x( - Scene *scene, Object *ob, int tagged) -{ - Mesh *me = (Mesh *)(ob->data); - ParticleSystemModifierData *psmd_eval; - PTCacheEdit *edit = PE_get_current(scene, ob); - ParticleSystem *psys = edit->psys; - ParticleData *pa, *newpa, *new_pars; - PTCacheEditPoint *newpoint, *new_points; - POINT_P; KEY_K; - HairKey *hkey; - int *mirrorfaces = NULL; - int rotation, totpart, newtotpart; - - if (psys->flag & PSYS_GLOBAL_HAIR) - return; - - psmd_eval = edit->psmd_eval; - if (!psmd_eval->mesh_final) - return; - - const bool use_dm_final_indices = (psys->part->use_modifier_stack && !psmd_eval->mesh_final->runtime.deformed_only); - - /* NOTE: this is not nice to use tessfaces but hard to avoid since pa->num uses tessfaces */ - BKE_mesh_tessface_ensure(me); - - /* Note: In case psys uses Mesh tessface indices, we mirror final Mesh itself, not orig mesh. Avoids an (impossible) - * mesh -> orig -> mesh tessface indices conversion... */ - mirrorfaces = mesh_get_x_mirror_faces(ob, NULL, use_dm_final_indices ? psmd_eval->mesh_final : NULL); - - if (!edit->mirror_cache) - PE_update_mirror_cache(ob, psys); - - totpart = psys->totpart; - newtotpart = psys->totpart; - LOOP_VISIBLE_POINTS { - pa = psys->particles + p; - - if (!tagged) { - if (point_is_selected(point)) { - if (edit->mirror_cache[p] != -1) { - /* already has a mirror, don't need to duplicate */ - PE_mirror_particle(ob, psmd_eval->mesh_final, psys, pa, NULL); - continue; - } - else - point->flag |= PEP_TAG; - } - } - - if ((point->flag & PEP_TAG) && mirrorfaces[pa->num * 2] != -1) - newtotpart++; - } - - if (newtotpart != psys->totpart) { - MFace *mtessface = use_dm_final_indices ? psmd_eval->mesh_final->mface : me->mface; - - /* allocate new arrays and copy existing */ - new_pars = MEM_callocN(newtotpart * sizeof(ParticleData), "ParticleData new"); - new_points = MEM_callocN(newtotpart * sizeof(PTCacheEditPoint), "PTCacheEditPoint new"); - - if (psys->particles) { - memcpy(new_pars, psys->particles, totpart * sizeof(ParticleData)); - MEM_freeN(psys->particles); - } - psys->particles = new_pars; - - if (edit->points) { - memcpy(new_points, edit->points, totpart * sizeof(PTCacheEditPoint)); - MEM_freeN(edit->points); - } - edit->points = new_points; - - if (edit->mirror_cache) { - MEM_freeN(edit->mirror_cache); - edit->mirror_cache = NULL; - } - - edit->totpoint = psys->totpart = newtotpart; - - /* create new elements */ - newpa = psys->particles + totpart; - newpoint = edit->points + totpart; - - for (p = 0, point = edit->points; p < totpart; p++, point++) { - pa = psys->particles + p; - const int pa_num = pa->num; - - if (point->flag & PEP_HIDE) - continue; - - if (!(point->flag & PEP_TAG) || mirrorfaces[pa_num * 2] == -1) - continue; - - /* duplicate */ - *newpa = *pa; - *newpoint = *point; - if (pa->hair) newpa->hair = MEM_dupallocN(pa->hair); - if (point->keys) newpoint->keys = MEM_dupallocN(point->keys); - - /* rotate weights according to vertex index rotation */ - rotation = mirrorfaces[pa_num * 2 + 1]; - newpa->fuv[0] = pa->fuv[2]; - newpa->fuv[1] = pa->fuv[1]; - newpa->fuv[2] = pa->fuv[0]; - newpa->fuv[3] = pa->fuv[3]; - while (rotation--) { - if (mtessface[pa_num].v4) { - SHIFT4(float, newpa->fuv[0], newpa->fuv[1], newpa->fuv[2], newpa->fuv[3]); - } - else { - SHIFT3(float, newpa->fuv[0], newpa->fuv[1], newpa->fuv[2]); - } - } - - /* assign face index */ - /* NOTE: mesh_get_x_mirror_faces generates -1 for non-found mirror, same as DMCACHE_NOTFOUND... */ - newpa->num = mirrorfaces[pa_num * 2]; - - if (use_dm_final_indices) { - newpa->num_dmcache = DMCACHE_ISCHILD; - } - else { - newpa->num_dmcache = psys_particle_dm_face_lookup( - psmd_eval->mesh_final, psmd_eval->mesh_original, newpa->num, newpa->fuv, NULL); - } - - /* update edit key pointers */ - key = newpoint->keys; - for (k = 0, hkey = newpa->hair; k < newpa->totkey; k++, hkey++, key++) { - key->co = hkey->co; - key->time = &hkey->time; - } - - /* map key positions as mirror over x axis */ - PE_mirror_particle(ob, psmd_eval->mesh_final, psys, pa, newpa); - - newpa++; - newpoint++; - } - } - - LOOP_POINTS { - point->flag &= ~PEP_TAG; - } - - MEM_freeN(mirrorfaces); +static void PE_mirror_x(Scene *scene, Object *ob, int tagged) +{ + Mesh *me = (Mesh *)(ob->data); + ParticleSystemModifierData *psmd_eval; + PTCacheEdit *edit = PE_get_current(scene, ob); + ParticleSystem *psys = edit->psys; + ParticleData *pa, *newpa, *new_pars; + PTCacheEditPoint *newpoint, *new_points; + POINT_P; + KEY_K; + HairKey *hkey; + int *mirrorfaces = NULL; + int rotation, totpart, newtotpart; + + if (psys->flag & PSYS_GLOBAL_HAIR) + return; + + psmd_eval = edit->psmd_eval; + if (!psmd_eval->mesh_final) + return; + + const bool use_dm_final_indices = (psys->part->use_modifier_stack && + !psmd_eval->mesh_final->runtime.deformed_only); + + /* NOTE: this is not nice to use tessfaces but hard to avoid since pa->num uses tessfaces */ + BKE_mesh_tessface_ensure(me); + + /* Note: In case psys uses Mesh tessface indices, we mirror final Mesh itself, not orig mesh. Avoids an (impossible) + * mesh -> orig -> mesh tessface indices conversion... */ + mirrorfaces = mesh_get_x_mirror_faces( + ob, NULL, use_dm_final_indices ? psmd_eval->mesh_final : NULL); + + if (!edit->mirror_cache) + PE_update_mirror_cache(ob, psys); + + totpart = psys->totpart; + newtotpart = psys->totpart; + LOOP_VISIBLE_POINTS + { + pa = psys->particles + p; + + if (!tagged) { + if (point_is_selected(point)) { + if (edit->mirror_cache[p] != -1) { + /* already has a mirror, don't need to duplicate */ + PE_mirror_particle(ob, psmd_eval->mesh_final, psys, pa, NULL); + continue; + } + else + point->flag |= PEP_TAG; + } + } + + if ((point->flag & PEP_TAG) && mirrorfaces[pa->num * 2] != -1) + newtotpart++; + } + + if (newtotpart != psys->totpart) { + MFace *mtessface = use_dm_final_indices ? psmd_eval->mesh_final->mface : me->mface; + + /* allocate new arrays and copy existing */ + new_pars = MEM_callocN(newtotpart * sizeof(ParticleData), "ParticleData new"); + new_points = MEM_callocN(newtotpart * sizeof(PTCacheEditPoint), "PTCacheEditPoint new"); + + if (psys->particles) { + memcpy(new_pars, psys->particles, totpart * sizeof(ParticleData)); + MEM_freeN(psys->particles); + } + psys->particles = new_pars; + + if (edit->points) { + memcpy(new_points, edit->points, totpart * sizeof(PTCacheEditPoint)); + MEM_freeN(edit->points); + } + edit->points = new_points; + + if (edit->mirror_cache) { + MEM_freeN(edit->mirror_cache); + edit->mirror_cache = NULL; + } + + edit->totpoint = psys->totpart = newtotpart; + + /* create new elements */ + newpa = psys->particles + totpart; + newpoint = edit->points + totpart; + + for (p = 0, point = edit->points; p < totpart; p++, point++) { + pa = psys->particles + p; + const int pa_num = pa->num; + + if (point->flag & PEP_HIDE) + continue; + + if (!(point->flag & PEP_TAG) || mirrorfaces[pa_num * 2] == -1) + continue; + + /* duplicate */ + *newpa = *pa; + *newpoint = *point; + if (pa->hair) + newpa->hair = MEM_dupallocN(pa->hair); + if (point->keys) + newpoint->keys = MEM_dupallocN(point->keys); + + /* rotate weights according to vertex index rotation */ + rotation = mirrorfaces[pa_num * 2 + 1]; + newpa->fuv[0] = pa->fuv[2]; + newpa->fuv[1] = pa->fuv[1]; + newpa->fuv[2] = pa->fuv[0]; + newpa->fuv[3] = pa->fuv[3]; + while (rotation--) { + if (mtessface[pa_num].v4) { + SHIFT4(float, newpa->fuv[0], newpa->fuv[1], newpa->fuv[2], newpa->fuv[3]); + } + else { + SHIFT3(float, newpa->fuv[0], newpa->fuv[1], newpa->fuv[2]); + } + } + + /* assign face index */ + /* NOTE: mesh_get_x_mirror_faces generates -1 for non-found mirror, same as DMCACHE_NOTFOUND... */ + newpa->num = mirrorfaces[pa_num * 2]; + + if (use_dm_final_indices) { + newpa->num_dmcache = DMCACHE_ISCHILD; + } + else { + newpa->num_dmcache = psys_particle_dm_face_lookup( + psmd_eval->mesh_final, psmd_eval->mesh_original, newpa->num, newpa->fuv, NULL); + } + + /* update edit key pointers */ + key = newpoint->keys; + for (k = 0, hkey = newpa->hair; k < newpa->totkey; k++, hkey++, key++) { + key->co = hkey->co; + key->time = &hkey->time; + } + + /* map key positions as mirror over x axis */ + PE_mirror_particle(ob, psmd_eval->mesh_final, psys, pa, newpa); + + newpa++; + newpoint++; + } + } + + LOOP_POINTS + { + point->flag &= ~PEP_TAG; + } + + MEM_freeN(mirrorfaces); } static int mirror_exec(bContext *C, wmOperator *UNUSED(op)) { - Scene *scene = CTX_data_scene(C); - Object *ob = CTX_data_active_object(C); - PTCacheEdit *edit = PE_get_current(scene, ob); + Scene *scene = CTX_data_scene(C); + Object *ob = CTX_data_active_object(C); + PTCacheEdit *edit = PE_get_current(scene, ob); - PE_mirror_x(scene, ob, 0); + PE_mirror_x(scene, ob, 0); - update_world_cos(CTX_data_depsgraph(C), ob, edit); - WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_EDITED, ob); - DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY); + update_world_cos(CTX_data_depsgraph(C), ob, edit); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_EDITED, ob); + DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY); - return OPERATOR_FINISHED; + return OPERATOR_FINISHED; } void PARTICLE_OT_mirror(wmOperatorType *ot) { - /* identifiers */ - ot->name = "Mirror"; - ot->idname = "PARTICLE_OT_mirror"; - ot->description = "Duplicate and mirror the selected particles along the local X axis"; + /* identifiers */ + ot->name = "Mirror"; + ot->idname = "PARTICLE_OT_mirror"; + ot->description = "Duplicate and mirror the selected particles along the local X axis"; - /* api callbacks */ - ot->exec = mirror_exec; - ot->poll = PE_hair_poll; + /* api callbacks */ + ot->exec = mirror_exec; + ot->poll = PE_hair_poll; - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } /************************* brush edit callbacks ********************/ -static void brush_comb( - PEData *data, - float UNUSED(mat[4][4]), - float imat[4][4], - int point_index, - int key_index, - PTCacheEditKey *key, - float mouse_distance) +static void brush_comb(PEData *data, + float UNUSED(mat[4][4]), + float imat[4][4], + int point_index, + int key_index, + PTCacheEditKey *key, + float mouse_distance) { - ParticleEditSettings *pset = PE_settings(data->scene); - float cvec[3], fac; + ParticleEditSettings *pset = PE_settings(data->scene); + float cvec[3], fac; - if (pset->flag & PE_LOCK_FIRST && key_index == 0) return; + if (pset->flag & PE_LOCK_FIRST && key_index == 0) + return; - fac = (float)pow((double)(1.0f - mouse_distance / data->rad), (double)data->combfac); + fac = (float)pow((double)(1.0f - mouse_distance / data->rad), (double)data->combfac); - copy_v3_v3(cvec, data->dvec); - mul_mat3_m4_v3(imat, cvec); - mul_v3_fl(cvec, fac); - add_v3_v3(key->co, cvec); + copy_v3_v3(cvec, data->dvec); + mul_mat3_m4_v3(imat, cvec); + mul_v3_fl(cvec, fac); + add_v3_v3(key->co, cvec); - (data->edit->points + point_index)->flag |= PEP_EDIT_RECALC; + (data->edit->points + point_index)->flag |= PEP_EDIT_RECALC; } static void brush_cut(PEData *data, int pa_index) { - PTCacheEdit *edit = data->edit; - ARegion *ar = data->vc.ar; - Object *ob = data->ob; - ParticleEditSettings *pset = PE_settings(data->scene); - ParticleCacheKey *key = edit->pathcache[pa_index]; - float rad2, cut_time = 1.0; - float x0, x1, v0, v1, o0, o1, xo0, xo1, d, dv; - int k, cut, keys = (int)pow(2.0, (double)pset->draw_step); - int screen_co[2]; + PTCacheEdit *edit = data->edit; + ARegion *ar = data->vc.ar; + Object *ob = data->ob; + ParticleEditSettings *pset = PE_settings(data->scene); + ParticleCacheKey *key = edit->pathcache[pa_index]; + float rad2, cut_time = 1.0; + float x0, x1, v0, v1, o0, o1, xo0, xo1, d, dv; + int k, cut, keys = (int)pow(2.0, (double)pset->draw_step); + int screen_co[2]; - BLI_assert(data->rng != NULL); - /* blunt scissors */ - if (BLI_rng_get_float(data->rng) > data->cutfac) { - return; - } + BLI_assert(data->rng != NULL); + /* blunt scissors */ + if (BLI_rng_get_float(data->rng) > data->cutfac) { + return; + } - /* don't cut hidden */ - if (edit->points[pa_index].flag & PEP_HIDE) - return; + /* don't cut hidden */ + if (edit->points[pa_index].flag & PEP_HIDE) + return; - if (ED_view3d_project_int_global(ar, key->co, screen_co, V3D_PROJ_TEST_CLIP_NEAR) != V3D_PROJ_RET_OK) - return; + if (ED_view3d_project_int_global(ar, key->co, screen_co, V3D_PROJ_TEST_CLIP_NEAR) != + V3D_PROJ_RET_OK) + return; - rad2 = data->rad * data->rad; + rad2 = data->rad * data->rad; - cut = 0; + cut = 0; - x0 = (float)screen_co[0]; - x1 = (float)screen_co[1]; + x0 = (float)screen_co[0]; + x1 = (float)screen_co[1]; - o0 = (float)data->mval[0]; - o1 = (float)data->mval[1]; + o0 = (float)data->mval[0]; + o1 = (float)data->mval[1]; - xo0 = x0 - o0; - xo1 = x1 - o1; + xo0 = x0 - o0; + xo1 = x1 - o1; - /* check if root is inside circle */ - if (xo0 * xo0 + xo1 * xo1 < rad2 && key_test_depth(data, key->co, screen_co)) { - cut_time = -1.0f; - cut = 1; - } - else { - /* calculate path time closest to root that was inside the circle */ - for (k = 1, key++; k <= keys; k++, key++) { + /* check if root is inside circle */ + if (xo0 * xo0 + xo1 * xo1 < rad2 && key_test_depth(data, key->co, screen_co)) { + cut_time = -1.0f; + cut = 1; + } + else { + /* calculate path time closest to root that was inside the circle */ + for (k = 1, key++; k <= keys; k++, key++) { - if ((ED_view3d_project_int_global(ar, key->co, screen_co, V3D_PROJ_TEST_CLIP_NEAR) != V3D_PROJ_RET_OK) || - key_test_depth(data, key->co, screen_co) == 0) - { - x0 = (float)screen_co[0]; - x1 = (float)screen_co[1]; + if ((ED_view3d_project_int_global(ar, key->co, screen_co, V3D_PROJ_TEST_CLIP_NEAR) != + V3D_PROJ_RET_OK) || + key_test_depth(data, key->co, screen_co) == 0) { + x0 = (float)screen_co[0]; + x1 = (float)screen_co[1]; - xo0 = x0 - o0; - xo1 = x1 - o1; - continue; - } + xo0 = x0 - o0; + xo1 = x1 - o1; + continue; + } - v0 = (float)screen_co[0] - x0; - v1 = (float)screen_co[1] - x1; + v0 = (float)screen_co[0] - x0; + v1 = (float)screen_co[1] - x1; - dv = v0 * v0 + v1 * v1; + dv = v0 * v0 + v1 * v1; - d = (v0 * xo1 - v1 * xo0); + d = (v0 * xo1 - v1 * xo0); - d = dv * rad2 - d * d; + d = dv * rad2 - d * d; - if (d > 0.0f) { - d = sqrtf(d); + if (d > 0.0f) { + d = sqrtf(d); - cut_time = -(v0 * xo0 + v1 * xo1 + d); + cut_time = -(v0 * xo0 + v1 * xo1 + d); - if (cut_time > 0.0f) { - cut_time /= dv; + if (cut_time > 0.0f) { + cut_time /= dv; - if (cut_time < 1.0f) { - cut_time += (float)(k - 1); - cut_time /= (float)keys; - cut = 1; - break; - } - } - } + if (cut_time < 1.0f) { + cut_time += (float)(k - 1); + cut_time /= (float)keys; + cut = 1; + break; + } + } + } - x0 = (float)screen_co[0]; - x1 = (float)screen_co[1]; + x0 = (float)screen_co[0]; + x1 = (float)screen_co[1]; - xo0 = x0 - o0; - xo1 = x1 - o1; - } - } + xo0 = x0 - o0; + xo1 = x1 - o1; + } + } - if (cut) { - if (cut_time < 0.0f) { - edit->points[pa_index].flag |= PEP_TAG; - } - else { - rekey_particle_to_time(data->context, data->scene, ob, pa_index, cut_time); - edit->points[pa_index].flag |= PEP_EDIT_RECALC; - } - } + if (cut) { + if (cut_time < 0.0f) { + edit->points[pa_index].flag |= PEP_TAG; + } + else { + rekey_particle_to_time(data->context, data->scene, ob, pa_index, cut_time); + edit->points[pa_index].flag |= PEP_EDIT_RECALC; + } + } } static void brush_length(PEData *data, int point_index, float UNUSED(mouse_distance)) { - PTCacheEdit *edit = data->edit; - PTCacheEditPoint *point = edit->points + point_index; - KEY_K; - float dvec[3], pvec[3] = {0.0f, 0.0f, 0.0f}; + PTCacheEdit *edit = data->edit; + PTCacheEditPoint *point = edit->points + point_index; + KEY_K; + float dvec[3], pvec[3] = {0.0f, 0.0f, 0.0f}; - LOOP_KEYS { - if (k == 0) { - copy_v3_v3(pvec, key->co); - } - else { - sub_v3_v3v3(dvec, key->co, pvec); - copy_v3_v3(pvec, key->co); - mul_v3_fl(dvec, data->growfac); - add_v3_v3v3(key->co, (key - 1)->co, dvec); - } - } + LOOP_KEYS + { + if (k == 0) { + copy_v3_v3(pvec, key->co); + } + else { + sub_v3_v3v3(dvec, key->co, pvec); + copy_v3_v3(pvec, key->co); + mul_v3_fl(dvec, data->growfac); + add_v3_v3v3(key->co, (key - 1)->co, dvec); + } + } - point->flag |= PEP_EDIT_RECALC; + point->flag |= PEP_EDIT_RECALC; } static void brush_puff(PEData *data, int point_index, float mouse_distance) { - PTCacheEdit *edit = data->edit; - ParticleSystem *psys = edit->psys; - PTCacheEditPoint *point = edit->points + point_index; - KEY_K; - float mat[4][4], imat[4][4]; - - float onor_prev[3]; /* previous normal (particle-space) */ - float ofs_prev[3]; /* accumulate offset for puff_volume (particle-space) */ - float co_root[3], no_root[3]; /* root location and normal (global-space) */ - float co_prev[3], co[3]; /* track key coords as we loop (global-space) */ - float fac = 0.0f, length_accum = 0.0f; - bool puff_volume = false; - bool changed = false; - - zero_v3(ofs_prev); - - { - ParticleEditSettings *pset = PE_settings(data->scene); - ParticleBrushData *brush = &pset->brush[pset->brushtype]; - puff_volume = (brush->flag & PE_BRUSH_DATA_PUFF_VOLUME) != 0; - } - - if (psys && !(psys->flag & PSYS_GLOBAL_HAIR)) { - psys_mat_hair_to_global(data->ob, data->mesh, psys->part->from, psys->particles + point_index, mat); - invert_m4_m4(imat, mat); - } - else { - unit_m4(mat); - unit_m4(imat); - } - - LOOP_KEYS { - float kco[3]; - - if (k == 0) { - /* find root coordinate and normal on emitter */ - copy_v3_v3(co, key->co); - mul_m4_v3(mat, co); - - /* use 'kco' as the object space version of worldspace 'co', - * ob->imat is set before calling */ - mul_v3_m4v3(kco, data->ob->imat, co); - - point_index = BLI_kdtree_3d_find_nearest(edit->emitter_field, kco, NULL); - if (point_index == -1) return; - - copy_v3_v3(co_root, co); - copy_v3_v3(no_root, &edit->emitter_cosnos[point_index * 6 + 3]); - mul_mat3_m4_v3(data->ob->obmat, no_root); /* normal into global-space */ - normalize_v3(no_root); - - if (puff_volume) { - copy_v3_v3(onor_prev, no_root); - mul_mat3_m4_v3(imat, onor_prev); /* global-space into particle space */ - normalize_v3(onor_prev); - } - - fac = (float)pow((double)(1.0f - mouse_distance / data->rad), (double)data->pufffac); - fac *= 0.025f; - if (data->invert) - fac = -fac; - } - else { - /* compute position as if hair was standing up straight. - * */ - float length; - copy_v3_v3(co_prev, co); - copy_v3_v3(co, key->co); - mul_m4_v3(mat, co); - length = len_v3v3(co_prev, co); - length_accum += length; - - if ((data->select == 0 || (key->flag & PEK_SELECT)) && !(key->flag & PEK_HIDE)) { - float dco[3]; /* delta temp var */ - - madd_v3_v3v3fl(kco, co_root, no_root, length_accum); - - /* blend between the current and straight position */ - sub_v3_v3v3(dco, kco, co); - madd_v3_v3fl(co, dco, fac); - /* keep the same distance from the root or we get glitches [#35406] */ - dist_ensure_v3_v3fl(co, co_root, length_accum); - - /* re-use dco to compare before and after translation and add to the offset */ - copy_v3_v3(dco, key->co); - - mul_v3_m4v3(key->co, imat, co); - - if (puff_volume) { - /* accumulate the total distance moved to apply to unselected - * keys that come after */ - sub_v3_v3v3(ofs_prev, key->co, dco); - } - changed = true; - } - else { - - if (puff_volume) { + PTCacheEdit *edit = data->edit; + ParticleSystem *psys = edit->psys; + PTCacheEditPoint *point = edit->points + point_index; + KEY_K; + float mat[4][4], imat[4][4]; + + float onor_prev[3]; /* previous normal (particle-space) */ + float ofs_prev[3]; /* accumulate offset for puff_volume (particle-space) */ + float co_root[3], no_root[3]; /* root location and normal (global-space) */ + float co_prev[3], co[3]; /* track key coords as we loop (global-space) */ + float fac = 0.0f, length_accum = 0.0f; + bool puff_volume = false; + bool changed = false; + + zero_v3(ofs_prev); + + { + ParticleEditSettings *pset = PE_settings(data->scene); + ParticleBrushData *brush = &pset->brush[pset->brushtype]; + puff_volume = (brush->flag & PE_BRUSH_DATA_PUFF_VOLUME) != 0; + } + + if (psys && !(psys->flag & PSYS_GLOBAL_HAIR)) { + psys_mat_hair_to_global( + data->ob, data->mesh, psys->part->from, psys->particles + point_index, mat); + invert_m4_m4(imat, mat); + } + else { + unit_m4(mat); + unit_m4(imat); + } + + LOOP_KEYS + { + float kco[3]; + + if (k == 0) { + /* find root coordinate and normal on emitter */ + copy_v3_v3(co, key->co); + mul_m4_v3(mat, co); + + /* use 'kco' as the object space version of worldspace 'co', + * ob->imat is set before calling */ + mul_v3_m4v3(kco, data->ob->imat, co); + + point_index = BLI_kdtree_3d_find_nearest(edit->emitter_field, kco, NULL); + if (point_index == -1) + return; + + copy_v3_v3(co_root, co); + copy_v3_v3(no_root, &edit->emitter_cosnos[point_index * 6 + 3]); + mul_mat3_m4_v3(data->ob->obmat, no_root); /* normal into global-space */ + normalize_v3(no_root); + + if (puff_volume) { + copy_v3_v3(onor_prev, no_root); + mul_mat3_m4_v3(imat, onor_prev); /* global-space into particle space */ + normalize_v3(onor_prev); + } + + fac = (float)pow((double)(1.0f - mouse_distance / data->rad), (double)data->pufffac); + fac *= 0.025f; + if (data->invert) + fac = -fac; + } + else { + /* compute position as if hair was standing up straight. + * */ + float length; + copy_v3_v3(co_prev, co); + copy_v3_v3(co, key->co); + mul_m4_v3(mat, co); + length = len_v3v3(co_prev, co); + length_accum += length; + + if ((data->select == 0 || (key->flag & PEK_SELECT)) && !(key->flag & PEK_HIDE)) { + float dco[3]; /* delta temp var */ + + madd_v3_v3v3fl(kco, co_root, no_root, length_accum); + + /* blend between the current and straight position */ + sub_v3_v3v3(dco, kco, co); + madd_v3_v3fl(co, dco, fac); + /* keep the same distance from the root or we get glitches [#35406] */ + dist_ensure_v3_v3fl(co, co_root, length_accum); + + /* re-use dco to compare before and after translation and add to the offset */ + copy_v3_v3(dco, key->co); + + mul_v3_m4v3(key->co, imat, co); + + if (puff_volume) { + /* accumulate the total distance moved to apply to unselected + * keys that come after */ + sub_v3_v3v3(ofs_prev, key->co, dco); + } + changed = true; + } + else { + + if (puff_volume) { #if 0 - /* this is simple but looks bad, adds annoying kinks */ - add_v3_v3(key->co, ofs); + /* this is simple but looks bad, adds annoying kinks */ + add_v3_v3(key->co, ofs); #else - /* translate (not rotate) the rest of the hair if its not selected */ - { -#if 0 /* kindof works but looks worse then what's below */ - - /* Move the unselected point on a vector based on the - * hair direction and the offset */ - float c1[3], c2[3]; - sub_v3_v3v3(dco, lastco, co); - mul_mat3_m4_v3(imat, dco); /* into particle space */ - - /* move the point along a vector perpendicular to the - * hairs direction, reduces odd kinks, */ - cross_v3_v3v3(c1, ofs, dco); - cross_v3_v3v3(c2, c1, dco); - normalize_v3(c2); - mul_v3_fl(c2, len_v3(ofs)); - add_v3_v3(key->co, c2); -#else - /* Move the unselected point on a vector based on the - * the normal of the closest geometry */ - float oco[3], onor[3]; - copy_v3_v3(oco, key->co); - mul_m4_v3(mat, oco); - - /* use 'kco' as the object space version of worldspace 'co', - * ob->imat is set before calling */ - mul_v3_m4v3(kco, data->ob->imat, oco); - - point_index = BLI_kdtree_3d_find_nearest(edit->emitter_field, kco, NULL); - if (point_index != -1) { - copy_v3_v3(onor, &edit->emitter_cosnos[point_index * 6 + 3]); - mul_mat3_m4_v3(data->ob->obmat, onor); /* normal into worldspace */ - mul_mat3_m4_v3(imat, onor); /* worldspace into particle space */ - normalize_v3(onor); - } - else { - copy_v3_v3(onor, onor_prev); - } - - if (!is_zero_v3(ofs_prev)) { - mul_v3_fl(onor, len_v3(ofs_prev)); - - add_v3_v3(key->co, onor); - } - - copy_v3_v3(onor_prev, onor); -#endif - } + /* translate (not rotate) the rest of the hair if its not selected */ + { +# if 0 /* kindof works but looks worse then what's below */ + + /* Move the unselected point on a vector based on the + * hair direction and the offset */ + float c1[3], c2[3]; + sub_v3_v3v3(dco, lastco, co); + mul_mat3_m4_v3(imat, dco); /* into particle space */ + + /* move the point along a vector perpendicular to the + * hairs direction, reduces odd kinks, */ + cross_v3_v3v3(c1, ofs, dco); + cross_v3_v3v3(c2, c1, dco); + normalize_v3(c2); + mul_v3_fl(c2, len_v3(ofs)); + add_v3_v3(key->co, c2); +# else + /* Move the unselected point on a vector based on the + * the normal of the closest geometry */ + float oco[3], onor[3]; + copy_v3_v3(oco, key->co); + mul_m4_v3(mat, oco); + + /* use 'kco' as the object space version of worldspace 'co', + * ob->imat is set before calling */ + mul_v3_m4v3(kco, data->ob->imat, oco); + + point_index = BLI_kdtree_3d_find_nearest(edit->emitter_field, kco, NULL); + if (point_index != -1) { + copy_v3_v3(onor, &edit->emitter_cosnos[point_index * 6 + 3]); + mul_mat3_m4_v3(data->ob->obmat, onor); /* normal into worldspace */ + mul_mat3_m4_v3(imat, onor); /* worldspace into particle space */ + normalize_v3(onor); + } + else { + copy_v3_v3(onor, onor_prev); + } + + if (!is_zero_v3(ofs_prev)) { + mul_v3_fl(onor, len_v3(ofs_prev)); + + add_v3_v3(key->co, onor); + } + + copy_v3_v3(onor_prev, onor); +# endif + } #endif - } - } - } - } + } + } + } + } - if (changed) - point->flag |= PEP_EDIT_RECALC; + if (changed) + point->flag |= PEP_EDIT_RECALC; } - -static void BKE_brush_weight_get( - PEData *data, - float UNUSED(mat[4][4]), - float UNUSED(imat[4][4]), - int point_index, - int key_index, - PTCacheEditKey *UNUSED(key), - float UNUSED(mouse_distance)) +static void BKE_brush_weight_get(PEData *data, + float UNUSED(mat[4][4]), + float UNUSED(imat[4][4]), + int point_index, + int key_index, + PTCacheEditKey *UNUSED(key), + float UNUSED(mouse_distance)) { - /* roots have full weight always */ - if (key_index) { - PTCacheEdit *edit = data->edit; - ParticleSystem *psys = edit->psys; + /* roots have full weight always */ + if (key_index) { + PTCacheEdit *edit = data->edit; + ParticleSystem *psys = edit->psys; - ParticleData *pa = psys->particles + point_index; - pa->hair[key_index].weight = data->weightfac; + ParticleData *pa = psys->particles + point_index; + pa->hair[key_index].weight = data->weightfac; - (data->edit->points + point_index)->flag |= PEP_EDIT_RECALC; - } + (data->edit->points + point_index)->flag |= PEP_EDIT_RECALC; + } } -static void brush_smooth_get( - PEData *data, - float mat[4][4], - float UNUSED(imat[4][4]), - int UNUSED(point_index), - int key_index, - PTCacheEditKey *key, - float UNUSED(mouse_distance)) +static void brush_smooth_get(PEData *data, + float mat[4][4], + float UNUSED(imat[4][4]), + int UNUSED(point_index), + int key_index, + PTCacheEditKey *key, + float UNUSED(mouse_distance)) { - if (key_index) { - float dvec[3]; + if (key_index) { + float dvec[3]; - sub_v3_v3v3(dvec, key->co, (key - 1)->co); - mul_mat3_m4_v3(mat, dvec); - add_v3_v3(data->vec, dvec); - data->tot++; - } + sub_v3_v3v3(dvec, key->co, (key - 1)->co); + mul_mat3_m4_v3(mat, dvec); + add_v3_v3(data->vec, dvec); + data->tot++; + } } -static void brush_smooth_do( - PEData *data, - float UNUSED(mat[4][4]), - float imat[4][4], - int point_index, - int key_index, - PTCacheEditKey *key, - float UNUSED(mouse_distance)) +static void brush_smooth_do(PEData *data, + float UNUSED(mat[4][4]), + float imat[4][4], + int point_index, + int key_index, + PTCacheEditKey *key, + float UNUSED(mouse_distance)) { - float vec[3], dvec[3]; + float vec[3], dvec[3]; - if (key_index) { - copy_v3_v3(vec, data->vec); - mul_mat3_m4_v3(imat, vec); + if (key_index) { + copy_v3_v3(vec, data->vec); + mul_mat3_m4_v3(imat, vec); - sub_v3_v3v3(dvec, key->co, (key - 1)->co); + sub_v3_v3v3(dvec, key->co, (key - 1)->co); - sub_v3_v3v3(dvec, vec, dvec); - mul_v3_fl(dvec, data->smoothfac); + sub_v3_v3v3(dvec, vec, dvec); + mul_v3_fl(dvec, data->smoothfac); - add_v3_v3(key->co, dvec); - } + add_v3_v3(key->co, dvec); + } - (data->edit->points + point_index)->flag |= PEP_EDIT_RECALC; + (data->edit->points + point_index)->flag |= PEP_EDIT_RECALC; } /* convert from triangle barycentric weights to quad mean value weights */ -static void intersect_dm_quad_weights(const float v1[3], const float v2[3], const float v3[3], const float v4[3], float w[4]) +static void intersect_dm_quad_weights( + const float v1[3], const float v2[3], const float v3[3], const float v4[3], float w[4]) { - float co[3], vert[4][3]; + float co[3], vert[4][3]; - copy_v3_v3(vert[0], v1); - copy_v3_v3(vert[1], v2); - copy_v3_v3(vert[2], v3); - copy_v3_v3(vert[3], v4); + copy_v3_v3(vert[0], v1); + copy_v3_v3(vert[1], v2); + copy_v3_v3(vert[2], v3); + copy_v3_v3(vert[3], v4); - co[0] = v1[0] * w[0] + v2[0] * w[1] + v3[0] * w[2] + v4[0] * w[3]; - co[1] = v1[1] * w[0] + v2[1] * w[1] + v3[1] * w[2] + v4[1] * w[3]; - co[2] = v1[2] * w[0] + v2[2] * w[1] + v3[2] * w[2] + v4[2] * w[3]; + co[0] = v1[0] * w[0] + v2[0] * w[1] + v3[0] * w[2] + v4[0] * w[3]; + co[1] = v1[1] * w[0] + v2[1] * w[1] + v3[1] * w[2] + v4[1] * w[3]; + co[2] = v1[2] * w[0] + v2[2] * w[1] + v3[2] * w[2] + v4[2] * w[3]; - interp_weights_poly_v3(w, vert, 4, co); + interp_weights_poly_v3(w, vert, 4, co); } /** Check intersection with an evaluated mesh. */ -static int particle_intersect_mesh(Depsgraph *depsgraph, Scene *UNUSED(scene), Object *ob, Mesh *mesh, +static int particle_intersect_mesh(Depsgraph *depsgraph, + Scene *UNUSED(scene), + Object *ob, + Mesh *mesh, float *vert_cos, - const float co1[3], const float co2[3], - float *min_d, int *min_face, float *min_w, - float *face_minmax, float *pa_minmax, - float radius, float *ipoint) -{ - MFace *mface = NULL; - MVert *mvert = NULL; - int i, totface, intersect = 0; - float cur_d, cur_uv[2], v1[3], v2[3], v3[3], v4[3], min[3], max[3], p_min[3], p_max[3]; - float cur_ipoint[3]; - - if (mesh == NULL) { - psys_disable_all(ob); - - Scene *scene_eval = DEG_get_evaluated_scene(depsgraph); - Object *ob_eval = DEG_get_evaluated_object(depsgraph, ob); - - mesh = mesh_get_eval_final(depsgraph, scene_eval, ob_eval, &CD_MASK_BAREMESH); - if (mesh == NULL) { - mesh = mesh_get_eval_deform(depsgraph, scene_eval, ob_eval, &CD_MASK_BAREMESH); - } - - psys_enable_all(ob); - - if (mesh == NULL) { - return 0; - } - } - - /* BMESH_ONLY, deform dm may not have tessface */ - BKE_mesh_tessface_ensure(mesh); - - - if (pa_minmax == 0) { - INIT_MINMAX(p_min, p_max); - minmax_v3v3_v3(p_min, p_max, co1); - minmax_v3v3_v3(p_min, p_max, co2); - } - else { - copy_v3_v3(p_min, pa_minmax); - copy_v3_v3(p_max, pa_minmax + 3); - } - - totface = mesh->totface; - mface = mesh->mface; - mvert = mesh->mvert; - - /* lets intersect the faces */ - for (i = 0; i < totface; i++, mface++) { - if (vert_cos) { - copy_v3_v3(v1, vert_cos + 3 * mface->v1); - copy_v3_v3(v2, vert_cos + 3 * mface->v2); - copy_v3_v3(v3, vert_cos + 3 * mface->v3); - if (mface->v4) - copy_v3_v3(v4, vert_cos + 3 * mface->v4); - } - else { - copy_v3_v3(v1, mvert[mface->v1].co); - copy_v3_v3(v2, mvert[mface->v2].co); - copy_v3_v3(v3, mvert[mface->v3].co); - if (mface->v4) - copy_v3_v3(v4, mvert[mface->v4].co); - } - - if (face_minmax == 0) { - INIT_MINMAX(min, max); - DO_MINMAX(v1, min, max); - DO_MINMAX(v2, min, max); - DO_MINMAX(v3, min, max); - if (mface->v4) - DO_MINMAX(v4, min, max); - if (isect_aabb_aabb_v3(min, max, p_min, p_max) == 0) - continue; - } - else { - copy_v3_v3(min, face_minmax + 6 * i); - copy_v3_v3(max, face_minmax + 6 * i + 3); - if (isect_aabb_aabb_v3(min, max, p_min, p_max) == 0) - continue; - } - - if (radius > 0.0f) { - if (isect_sweeping_sphere_tri_v3(co1, co2, radius, v2, v3, v1, &cur_d, cur_ipoint)) { - if (cur_d < *min_d) { - *min_d = cur_d; - copy_v3_v3(ipoint, cur_ipoint); - *min_face = i; - intersect = 1; - } - } - if (mface->v4) { - if (isect_sweeping_sphere_tri_v3(co1, co2, radius, v4, v1, v3, &cur_d, cur_ipoint)) { - if (cur_d < *min_d) { - *min_d = cur_d; - copy_v3_v3(ipoint, cur_ipoint); - *min_face = i; - intersect = 1; - } - } - } - } - else { - if (isect_line_segment_tri_v3(co1, co2, v1, v2, v3, &cur_d, cur_uv)) { - if (cur_d < *min_d) { - *min_d = cur_d; - min_w[0] = 1.0f - cur_uv[0] - cur_uv[1]; - min_w[1] = cur_uv[0]; - min_w[2] = cur_uv[1]; - min_w[3] = 0.0f; - if (mface->v4) - intersect_dm_quad_weights(v1, v2, v3, v4, min_w); - *min_face = i; - intersect = 1; - } - } - if (mface->v4) { - if (isect_line_segment_tri_v3(co1, co2, v1, v3, v4, &cur_d, cur_uv)) { - if (cur_d < *min_d) { - *min_d = cur_d; - min_w[0] = 1.0f - cur_uv[0] - cur_uv[1]; - min_w[1] = 0.0f; - min_w[2] = cur_uv[0]; - min_w[3] = cur_uv[1]; - intersect_dm_quad_weights(v1, v2, v3, v4, min_w); - *min_face = i; - intersect = 1; - } - } - } - } - } - return intersect; + const float co1[3], + const float co2[3], + float *min_d, + int *min_face, + float *min_w, + float *face_minmax, + float *pa_minmax, + float radius, + float *ipoint) +{ + MFace *mface = NULL; + MVert *mvert = NULL; + int i, totface, intersect = 0; + float cur_d, cur_uv[2], v1[3], v2[3], v3[3], v4[3], min[3], max[3], p_min[3], p_max[3]; + float cur_ipoint[3]; + + if (mesh == NULL) { + psys_disable_all(ob); + + Scene *scene_eval = DEG_get_evaluated_scene(depsgraph); + Object *ob_eval = DEG_get_evaluated_object(depsgraph, ob); + + mesh = mesh_get_eval_final(depsgraph, scene_eval, ob_eval, &CD_MASK_BAREMESH); + if (mesh == NULL) { + mesh = mesh_get_eval_deform(depsgraph, scene_eval, ob_eval, &CD_MASK_BAREMESH); + } + + psys_enable_all(ob); + + if (mesh == NULL) { + return 0; + } + } + + /* BMESH_ONLY, deform dm may not have tessface */ + BKE_mesh_tessface_ensure(mesh); + + if (pa_minmax == 0) { + INIT_MINMAX(p_min, p_max); + minmax_v3v3_v3(p_min, p_max, co1); + minmax_v3v3_v3(p_min, p_max, co2); + } + else { + copy_v3_v3(p_min, pa_minmax); + copy_v3_v3(p_max, pa_minmax + 3); + } + + totface = mesh->totface; + mface = mesh->mface; + mvert = mesh->mvert; + + /* lets intersect the faces */ + for (i = 0; i < totface; i++, mface++) { + if (vert_cos) { + copy_v3_v3(v1, vert_cos + 3 * mface->v1); + copy_v3_v3(v2, vert_cos + 3 * mface->v2); + copy_v3_v3(v3, vert_cos + 3 * mface->v3); + if (mface->v4) + copy_v3_v3(v4, vert_cos + 3 * mface->v4); + } + else { + copy_v3_v3(v1, mvert[mface->v1].co); + copy_v3_v3(v2, mvert[mface->v2].co); + copy_v3_v3(v3, mvert[mface->v3].co); + if (mface->v4) + copy_v3_v3(v4, mvert[mface->v4].co); + } + + if (face_minmax == 0) { + INIT_MINMAX(min, max); + DO_MINMAX(v1, min, max); + DO_MINMAX(v2, min, max); + DO_MINMAX(v3, min, max); + if (mface->v4) + DO_MINMAX(v4, min, max); + if (isect_aabb_aabb_v3(min, max, p_min, p_max) == 0) + continue; + } + else { + copy_v3_v3(min, face_minmax + 6 * i); + copy_v3_v3(max, face_minmax + 6 * i + 3); + if (isect_aabb_aabb_v3(min, max, p_min, p_max) == 0) + continue; + } + + if (radius > 0.0f) { + if (isect_sweeping_sphere_tri_v3(co1, co2, radius, v2, v3, v1, &cur_d, cur_ipoint)) { + if (cur_d < *min_d) { + *min_d = cur_d; + copy_v3_v3(ipoint, cur_ipoint); + *min_face = i; + intersect = 1; + } + } + if (mface->v4) { + if (isect_sweeping_sphere_tri_v3(co1, co2, radius, v4, v1, v3, &cur_d, cur_ipoint)) { + if (cur_d < *min_d) { + *min_d = cur_d; + copy_v3_v3(ipoint, cur_ipoint); + *min_face = i; + intersect = 1; + } + } + } + } + else { + if (isect_line_segment_tri_v3(co1, co2, v1, v2, v3, &cur_d, cur_uv)) { + if (cur_d < *min_d) { + *min_d = cur_d; + min_w[0] = 1.0f - cur_uv[0] - cur_uv[1]; + min_w[1] = cur_uv[0]; + min_w[2] = cur_uv[1]; + min_w[3] = 0.0f; + if (mface->v4) + intersect_dm_quad_weights(v1, v2, v3, v4, min_w); + *min_face = i; + intersect = 1; + } + } + if (mface->v4) { + if (isect_line_segment_tri_v3(co1, co2, v1, v3, v4, &cur_d, cur_uv)) { + if (cur_d < *min_d) { + *min_d = cur_d; + min_w[0] = 1.0f - cur_uv[0] - cur_uv[1]; + min_w[1] = 0.0f; + min_w[2] = cur_uv[0]; + min_w[3] = cur_uv[1]; + intersect_dm_quad_weights(v1, v2, v3, v4, min_w); + *min_face = i; + intersect = 1; + } + } + } + } + } + return intersect; } typedef struct BrushAddCountIterData { - Depsgraph *depsgraph; - Scene *scene; - Object *object; - Mesh *mesh; - PEData *data; - int number; - short size; - float imat[4][4]; - ParticleData *add_pars; - int num_added; + Depsgraph *depsgraph; + Scene *scene; + Object *object; + Mesh *mesh; + PEData *data; + int number; + short size; + float imat[4][4]; + ParticleData *add_pars; + int num_added; } BrushAddCountIterData; typedef struct BrushAddCountIterTLSData { - RNG *rng; - int num_added; + RNG *rng; + int num_added; } BrushAddCountIterTLSData; -static void brush_add_count_iter( - void *__restrict iter_data_v, - const int iter, - const ParallelRangeTLS *__restrict tls_v) -{ - BrushAddCountIterData *iter_data = (BrushAddCountIterData *)iter_data_v; - Depsgraph *depsgraph = iter_data->depsgraph; - PEData *data = iter_data->data; - PTCacheEdit *edit = data->edit; - ParticleSystem *psys = edit->psys; - ParticleSystemModifierData *psmd_eval = edit->psmd_eval; - ParticleData *add_pars = iter_data->add_pars; - BrushAddCountIterTLSData *tls = tls_v->userdata_chunk; - const int number = iter_data->number; - const short size = iter_data->size; - const short size2 = size * size; - float dmx, dmy; - if (number > 1) { - dmx = size; - dmy = size; - if (tls->rng == NULL) { - tls->rng = BLI_rng_new_srandom( - psys->seed + data->mval[0] + data->mval[1] + tls_v->thread_id); - } - /* rejection sampling to get points in circle */ - while (dmx * dmx + dmy * dmy > size2) { - dmx = (2.0f * BLI_rng_get_float(tls->rng) - 1.0f) * size; - dmy = (2.0f * BLI_rng_get_float(tls->rng) - 1.0f) * size; - } - } - else { - dmx = 0.0f; - dmy = 0.0f; - } - - float mco[2]; - mco[0] = data->mval[0] + dmx; - mco[1] = data->mval[1] + dmy; - - float co1[3], co2[3]; - ED_view3d_win_to_segment_clipped(depsgraph, data->vc.ar, data->vc.v3d, mco, co1, co2, true); - - mul_m4_v3(iter_data->imat, co1); - mul_m4_v3(iter_data->imat, co2); - float min_d = 2.0; - - /* warning, returns the derived mesh face */ - BLI_assert(iter_data->mesh != NULL); - if (particle_intersect_mesh(depsgraph, iter_data->scene, iter_data->object, iter_data->mesh, - 0, co1, co2, - &min_d, - &add_pars[iter].num_dmcache, - add_pars[iter].fuv, - 0, 0, 0, 0)) - { - if (psys->part->use_modifier_stack && !psmd_eval->mesh_final->runtime.deformed_only) { - add_pars[iter].num = add_pars[iter].num_dmcache; - add_pars[iter].num_dmcache = DMCACHE_ISCHILD; - } - else if (iter_data->mesh == psmd_eval->mesh_original) { - /* Final DM is not same topology as orig mesh, we have to map num_dmcache to real final dm. */ - add_pars[iter].num = add_pars[iter].num_dmcache; - add_pars[iter].num_dmcache = psys_particle_dm_face_lookup( - psmd_eval->mesh_final, psmd_eval->mesh_original, - add_pars[iter].num, add_pars[iter].fuv, NULL); - } - else { - add_pars[iter].num = add_pars[iter].num_dmcache; - } - if (add_pars[iter].num != DMCACHE_NOTFOUND) { - tls->num_added++; - } - } +static void brush_add_count_iter(void *__restrict iter_data_v, + const int iter, + const ParallelRangeTLS *__restrict tls_v) +{ + BrushAddCountIterData *iter_data = (BrushAddCountIterData *)iter_data_v; + Depsgraph *depsgraph = iter_data->depsgraph; + PEData *data = iter_data->data; + PTCacheEdit *edit = data->edit; + ParticleSystem *psys = edit->psys; + ParticleSystemModifierData *psmd_eval = edit->psmd_eval; + ParticleData *add_pars = iter_data->add_pars; + BrushAddCountIterTLSData *tls = tls_v->userdata_chunk; + const int number = iter_data->number; + const short size = iter_data->size; + const short size2 = size * size; + float dmx, dmy; + if (number > 1) { + dmx = size; + dmy = size; + if (tls->rng == NULL) { + tls->rng = BLI_rng_new_srandom(psys->seed + data->mval[0] + data->mval[1] + + tls_v->thread_id); + } + /* rejection sampling to get points in circle */ + while (dmx * dmx + dmy * dmy > size2) { + dmx = (2.0f * BLI_rng_get_float(tls->rng) - 1.0f) * size; + dmy = (2.0f * BLI_rng_get_float(tls->rng) - 1.0f) * size; + } + } + else { + dmx = 0.0f; + dmy = 0.0f; + } + + float mco[2]; + mco[0] = data->mval[0] + dmx; + mco[1] = data->mval[1] + dmy; + + float co1[3], co2[3]; + ED_view3d_win_to_segment_clipped(depsgraph, data->vc.ar, data->vc.v3d, mco, co1, co2, true); + + mul_m4_v3(iter_data->imat, co1); + mul_m4_v3(iter_data->imat, co2); + float min_d = 2.0; + + /* warning, returns the derived mesh face */ + BLI_assert(iter_data->mesh != NULL); + if (particle_intersect_mesh(depsgraph, + iter_data->scene, + iter_data->object, + iter_data->mesh, + 0, + co1, + co2, + &min_d, + &add_pars[iter].num_dmcache, + add_pars[iter].fuv, + 0, + 0, + 0, + 0)) { + if (psys->part->use_modifier_stack && !psmd_eval->mesh_final->runtime.deformed_only) { + add_pars[iter].num = add_pars[iter].num_dmcache; + add_pars[iter].num_dmcache = DMCACHE_ISCHILD; + } + else if (iter_data->mesh == psmd_eval->mesh_original) { + /* Final DM is not same topology as orig mesh, we have to map num_dmcache to real final dm. */ + add_pars[iter].num = add_pars[iter].num_dmcache; + add_pars[iter].num_dmcache = psys_particle_dm_face_lookup(psmd_eval->mesh_final, + psmd_eval->mesh_original, + add_pars[iter].num, + add_pars[iter].fuv, + NULL); + } + else { + add_pars[iter].num = add_pars[iter].num_dmcache; + } + if (add_pars[iter].num != DMCACHE_NOTFOUND) { + tls->num_added++; + } + } } static void brush_add_count_iter_finalize(void *__restrict userdata_v, void *__restrict userdata_chunk_v) { - BrushAddCountIterData *iter_data = (BrushAddCountIterData *)userdata_v; - BrushAddCountIterTLSData *tls = (BrushAddCountIterTLSData *)userdata_chunk_v; - iter_data->num_added += tls->num_added; - if (tls->rng != NULL) { - BLI_rng_free(tls->rng); - } + BrushAddCountIterData *iter_data = (BrushAddCountIterData *)userdata_v; + BrushAddCountIterTLSData *tls = (BrushAddCountIterTLSData *)userdata_chunk_v; + iter_data->num_added += tls->num_added; + if (tls->rng != NULL) { + BLI_rng_free(tls->rng); + } } static int brush_add(const bContext *C, PEData *data, short number) { - Depsgraph *depsgraph = CTX_data_depsgraph(C); - Scene *scene = data->scene; - Object *ob = data->ob; - Mesh *mesh; - PTCacheEdit *edit = data->edit; - ParticleSystem *psys = edit->psys; - ParticleData *add_pars; - ParticleSystemModifierData *psmd_eval = edit->psmd_eval; - ParticleSimulationData sim = {0}; - ParticleEditSettings *pset = PE_settings(scene); - int i, k, n = 0, totpart = psys->totpart; - float co1[3], imat[4][4]; - float framestep, timestep; - short size = pset->brush[PE_BRUSH_ADD].size; - RNG *rng; - - invert_m4_m4(imat, ob->obmat); - - if (psys->flag & PSYS_GLOBAL_HAIR) - return 0; - - add_pars = MEM_callocN(number * sizeof(ParticleData), "ParticleData add"); - - rng = BLI_rng_new_srandom(psys->seed + data->mval[0] + data->mval[1]); - - sim.depsgraph = depsgraph; - sim.scene = scene; - sim.ob = ob; - sim.psys = psys; - sim.psmd = psmd_eval; - - timestep = psys_get_timestep(&sim); - - if (psys->part->use_modifier_stack || psmd_eval->mesh_final->runtime.deformed_only) { - mesh = psmd_eval->mesh_final; - } - else { - mesh = psmd_eval->mesh_original; - } - BLI_assert(mesh); - - /* Calculate positions of new particles to add, based on brush intersection - * with object. New particle data is assigned to a corresponding to check - * index element of add_pars array. This means, that add_pars is a sparse - * array. - */ - BrushAddCountIterData iter_data; - iter_data.depsgraph = depsgraph; - iter_data.scene = scene; - iter_data.object = ob; - iter_data.mesh = mesh; - iter_data.data = data; - iter_data.number = number; - iter_data.size = size; - iter_data.add_pars = add_pars; - iter_data.num_added = 0; - copy_m4_m4(iter_data.imat, imat); - - BrushAddCountIterTLSData tls = {NULL}; - - ParallelRangeSettings settings; - BLI_parallel_range_settings_defaults(&settings); - settings.scheduling_mode = TASK_SCHEDULING_DYNAMIC; - settings.userdata_chunk = &tls; - settings.userdata_chunk_size = sizeof(BrushAddCountIterTLSData); - settings.func_finalize = brush_add_count_iter_finalize; - BLI_task_parallel_range(0, number, &iter_data, brush_add_count_iter, &settings); - - /* Convert add_parse to a dense array, where all new particles are in the - * beginning of the array. - */ - n = iter_data.num_added; - for (int current_iter = 0, new_index = 0; current_iter < number; current_iter++) { - if (add_pars[current_iter].num == DMCACHE_NOTFOUND) { - continue; - } - if (new_index != current_iter) { - new_index++; - continue; - } - memcpy(add_pars + new_index, add_pars + current_iter, sizeof(ParticleData)); - new_index++; - } - - /* TODO(sergey): Consider multi-threading this part as well. */ - if (n) { - int newtotpart = totpart + n; - float hairmat[4][4], cur_co[3]; - KDTree_3d *tree = 0; - ParticleData *pa, *new_pars = MEM_callocN(newtotpart * sizeof(ParticleData), "ParticleData new"); - PTCacheEditPoint *point, *new_points = MEM_callocN(newtotpart * sizeof(PTCacheEditPoint), "PTCacheEditPoint array new"); - PTCacheEditKey *key; - HairKey *hkey; - - /* save existing elements */ - memcpy(new_pars, psys->particles, totpart * sizeof(ParticleData)); - memcpy(new_points, edit->points, totpart * sizeof(PTCacheEditPoint)); - - /* change old arrays to new ones */ - if (psys->particles) MEM_freeN(psys->particles); - psys->particles = new_pars; - - if (edit->points) MEM_freeN(edit->points); - edit->points = new_points; - - if (edit->mirror_cache) { - MEM_freeN(edit->mirror_cache); - edit->mirror_cache = NULL; - } - - /* create tree for interpolation */ - if (pset->flag & PE_INTERPOLATE_ADDED && psys->totpart) { - tree = BLI_kdtree_3d_new(psys->totpart); - - for (i = 0, pa = psys->particles; i < totpart; i++, pa++) { - psys_particle_on_dm(psmd_eval->mesh_final, psys->part->from, pa->num, pa->num_dmcache, pa->fuv, pa->foffset, cur_co, 0, 0, 0, 0); - BLI_kdtree_3d_insert(tree, i, cur_co); - } - - BLI_kdtree_3d_balance(tree); - } - - edit->totpoint = psys->totpart = newtotpart; - - /* create new elements */ - pa = psys->particles + totpart; - point = edit->points + totpart; - - for (i = totpart; i < newtotpart; i++, pa++, point++) { - memcpy(pa, add_pars + i - totpart, sizeof(ParticleData)); - pa->hair = MEM_callocN(pset->totaddkey * sizeof(HairKey), "BakeKey key add"); - key = point->keys = MEM_callocN(pset->totaddkey * sizeof(PTCacheEditKey), "PTCacheEditKey add"); - point->totkey = pa->totkey = pset->totaddkey; - - for (k = 0, hkey = pa->hair; k < pa->totkey; k++, hkey++, key++) { - key->co = hkey->co; - key->time = &hkey->time; - - if (!(psys->flag & PSYS_GLOBAL_HAIR)) - key->flag |= PEK_USE_WCO; - } - - pa->size = 1.0f; - initialize_particle(&sim, pa); - reset_particle(&sim, pa, 0.0, 1.0); - point->flag |= PEP_EDIT_RECALC; - if (pe_x_mirror(ob)) - point->flag |= PEP_TAG; /* signal for duplicate */ - - framestep = pa->lifetime / (float)(pset->totaddkey - 1); - - if (tree) { - ParticleData *ppa; - HairKey *thkey; - ParticleKey key3[3]; - KDTreeNearest_3d ptn[3]; - int w, maxw; - float maxd, totw = 0.0, weight[3]; - - psys_particle_on_dm(psmd_eval->mesh_final, psys->part->from, pa->num, pa->num_dmcache, pa->fuv, pa->foffset, co1, 0, 0, 0, 0); - maxw = BLI_kdtree_3d_find_nearest_n(tree, co1, ptn, 3); - - maxd = ptn[maxw - 1].dist; - - for (w = 0; w < maxw; w++) { - weight[w] = (float)pow(2.0, (double)(-6.0f * ptn[w].dist / maxd)); - totw += weight[w]; - } - for (; w < 3; w++) { - weight[w] = 0.0f; - } - - if (totw > 0.0f) { - for (w = 0; w < maxw; w++) - weight[w] /= totw; - } - else { - for (w = 0; w < maxw; w++) - weight[w] = 1.0f / maxw; - } - - ppa = psys->particles + ptn[0].index; - - for (k = 0; k < pset->totaddkey; k++) { - thkey = (HairKey *)pa->hair + k; - thkey->time = pa->time + k * framestep; - - key3[0].time = thkey->time / 100.0f; - psys_get_particle_on_path(&sim, ptn[0].index, key3, 0); - mul_v3_fl(key3[0].co, weight[0]); - - /* TODO: interpolating the weight would be nicer */ - thkey->weight = (ppa->hair + MIN2(k, ppa->totkey - 1))->weight; - - if (maxw > 1) { - key3[1].time = key3[0].time; - psys_get_particle_on_path(&sim, ptn[1].index, &key3[1], 0); - mul_v3_fl(key3[1].co, weight[1]); - add_v3_v3(key3[0].co, key3[1].co); - - if (maxw > 2) { - key3[2].time = key3[0].time; - psys_get_particle_on_path(&sim, ptn[2].index, &key3[2], 0); - mul_v3_fl(key3[2].co, weight[2]); - add_v3_v3(key3[0].co, key3[2].co); - } - } - - if (k == 0) - sub_v3_v3v3(co1, pa->state.co, key3[0].co); - - add_v3_v3v3(thkey->co, key3[0].co, co1); - - thkey->time = key3[0].time; - } - } - else { - for (k = 0, hkey = pa->hair; k < pset->totaddkey; k++, hkey++) { - madd_v3_v3v3fl(hkey->co, pa->state.co, pa->state.vel, k * framestep * timestep); - hkey->time += k * framestep; - hkey->weight = 1.f - (float)k / (float)(pset->totaddkey - 1); - } - } - for (k = 0, hkey = pa->hair; k < pset->totaddkey; k++, hkey++) { - psys_mat_hair_to_global(ob, psmd_eval->mesh_final, psys->part->from, pa, hairmat); - invert_m4_m4(imat, hairmat); - mul_m4_v3(imat, hkey->co); - } - } - - if (tree) - BLI_kdtree_3d_free(tree); - } - - MEM_freeN(add_pars); - - BLI_rng_free(rng); - - return n; + Depsgraph *depsgraph = CTX_data_depsgraph(C); + Scene *scene = data->scene; + Object *ob = data->ob; + Mesh *mesh; + PTCacheEdit *edit = data->edit; + ParticleSystem *psys = edit->psys; + ParticleData *add_pars; + ParticleSystemModifierData *psmd_eval = edit->psmd_eval; + ParticleSimulationData sim = {0}; + ParticleEditSettings *pset = PE_settings(scene); + int i, k, n = 0, totpart = psys->totpart; + float co1[3], imat[4][4]; + float framestep, timestep; + short size = pset->brush[PE_BRUSH_ADD].size; + RNG *rng; + + invert_m4_m4(imat, ob->obmat); + + if (psys->flag & PSYS_GLOBAL_HAIR) + return 0; + + add_pars = MEM_callocN(number * sizeof(ParticleData), "ParticleData add"); + + rng = BLI_rng_new_srandom(psys->seed + data->mval[0] + data->mval[1]); + + sim.depsgraph = depsgraph; + sim.scene = scene; + sim.ob = ob; + sim.psys = psys; + sim.psmd = psmd_eval; + + timestep = psys_get_timestep(&sim); + + if (psys->part->use_modifier_stack || psmd_eval->mesh_final->runtime.deformed_only) { + mesh = psmd_eval->mesh_final; + } + else { + mesh = psmd_eval->mesh_original; + } + BLI_assert(mesh); + + /* Calculate positions of new particles to add, based on brush intersection + * with object. New particle data is assigned to a corresponding to check + * index element of add_pars array. This means, that add_pars is a sparse + * array. + */ + BrushAddCountIterData iter_data; + iter_data.depsgraph = depsgraph; + iter_data.scene = scene; + iter_data.object = ob; + iter_data.mesh = mesh; + iter_data.data = data; + iter_data.number = number; + iter_data.size = size; + iter_data.add_pars = add_pars; + iter_data.num_added = 0; + copy_m4_m4(iter_data.imat, imat); + + BrushAddCountIterTLSData tls = {NULL}; + + ParallelRangeSettings settings; + BLI_parallel_range_settings_defaults(&settings); + settings.scheduling_mode = TASK_SCHEDULING_DYNAMIC; + settings.userdata_chunk = &tls; + settings.userdata_chunk_size = sizeof(BrushAddCountIterTLSData); + settings.func_finalize = brush_add_count_iter_finalize; + BLI_task_parallel_range(0, number, &iter_data, brush_add_count_iter, &settings); + + /* Convert add_parse to a dense array, where all new particles are in the + * beginning of the array. + */ + n = iter_data.num_added; + for (int current_iter = 0, new_index = 0; current_iter < number; current_iter++) { + if (add_pars[current_iter].num == DMCACHE_NOTFOUND) { + continue; + } + if (new_index != current_iter) { + new_index++; + continue; + } + memcpy(add_pars + new_index, add_pars + current_iter, sizeof(ParticleData)); + new_index++; + } + + /* TODO(sergey): Consider multi-threading this part as well. */ + if (n) { + int newtotpart = totpart + n; + float hairmat[4][4], cur_co[3]; + KDTree_3d *tree = 0; + ParticleData *pa, + *new_pars = MEM_callocN(newtotpart * sizeof(ParticleData), "ParticleData new"); + PTCacheEditPoint *point, *new_points = MEM_callocN(newtotpart * sizeof(PTCacheEditPoint), + "PTCacheEditPoint array new"); + PTCacheEditKey *key; + HairKey *hkey; + + /* save existing elements */ + memcpy(new_pars, psys->particles, totpart * sizeof(ParticleData)); + memcpy(new_points, edit->points, totpart * sizeof(PTCacheEditPoint)); + + /* change old arrays to new ones */ + if (psys->particles) + MEM_freeN(psys->particles); + psys->particles = new_pars; + + if (edit->points) + MEM_freeN(edit->points); + edit->points = new_points; + + if (edit->mirror_cache) { + MEM_freeN(edit->mirror_cache); + edit->mirror_cache = NULL; + } + + /* create tree for interpolation */ + if (pset->flag & PE_INTERPOLATE_ADDED && psys->totpart) { + tree = BLI_kdtree_3d_new(psys->totpart); + + for (i = 0, pa = psys->particles; i < totpart; i++, pa++) { + psys_particle_on_dm(psmd_eval->mesh_final, + psys->part->from, + pa->num, + pa->num_dmcache, + pa->fuv, + pa->foffset, + cur_co, + 0, + 0, + 0, + 0); + BLI_kdtree_3d_insert(tree, i, cur_co); + } + + BLI_kdtree_3d_balance(tree); + } + + edit->totpoint = psys->totpart = newtotpart; + + /* create new elements */ + pa = psys->particles + totpart; + point = edit->points + totpart; + + for (i = totpart; i < newtotpart; i++, pa++, point++) { + memcpy(pa, add_pars + i - totpart, sizeof(ParticleData)); + pa->hair = MEM_callocN(pset->totaddkey * sizeof(HairKey), "BakeKey key add"); + key = point->keys = MEM_callocN(pset->totaddkey * sizeof(PTCacheEditKey), + "PTCacheEditKey add"); + point->totkey = pa->totkey = pset->totaddkey; + + for (k = 0, hkey = pa->hair; k < pa->totkey; k++, hkey++, key++) { + key->co = hkey->co; + key->time = &hkey->time; + + if (!(psys->flag & PSYS_GLOBAL_HAIR)) + key->flag |= PEK_USE_WCO; + } + + pa->size = 1.0f; + initialize_particle(&sim, pa); + reset_particle(&sim, pa, 0.0, 1.0); + point->flag |= PEP_EDIT_RECALC; + if (pe_x_mirror(ob)) + point->flag |= PEP_TAG; /* signal for duplicate */ + + framestep = pa->lifetime / (float)(pset->totaddkey - 1); + + if (tree) { + ParticleData *ppa; + HairKey *thkey; + ParticleKey key3[3]; + KDTreeNearest_3d ptn[3]; + int w, maxw; + float maxd, totw = 0.0, weight[3]; + + psys_particle_on_dm(psmd_eval->mesh_final, + psys->part->from, + pa->num, + pa->num_dmcache, + pa->fuv, + pa->foffset, + co1, + 0, + 0, + 0, + 0); + maxw = BLI_kdtree_3d_find_nearest_n(tree, co1, ptn, 3); + + maxd = ptn[maxw - 1].dist; + + for (w = 0; w < maxw; w++) { + weight[w] = (float)pow(2.0, (double)(-6.0f * ptn[w].dist / maxd)); + totw += weight[w]; + } + for (; w < 3; w++) { + weight[w] = 0.0f; + } + + if (totw > 0.0f) { + for (w = 0; w < maxw; w++) + weight[w] /= totw; + } + else { + for (w = 0; w < maxw; w++) + weight[w] = 1.0f / maxw; + } + + ppa = psys->particles + ptn[0].index; + + for (k = 0; k < pset->totaddkey; k++) { + thkey = (HairKey *)pa->hair + k; + thkey->time = pa->time + k * framestep; + + key3[0].time = thkey->time / 100.0f; + psys_get_particle_on_path(&sim, ptn[0].index, key3, 0); + mul_v3_fl(key3[0].co, weight[0]); + + /* TODO: interpolating the weight would be nicer */ + thkey->weight = (ppa->hair + MIN2(k, ppa->totkey - 1))->weight; + + if (maxw > 1) { + key3[1].time = key3[0].time; + psys_get_particle_on_path(&sim, ptn[1].index, &key3[1], 0); + mul_v3_fl(key3[1].co, weight[1]); + add_v3_v3(key3[0].co, key3[1].co); + + if (maxw > 2) { + key3[2].time = key3[0].time; + psys_get_particle_on_path(&sim, ptn[2].index, &key3[2], 0); + mul_v3_fl(key3[2].co, weight[2]); + add_v3_v3(key3[0].co, key3[2].co); + } + } + + if (k == 0) + sub_v3_v3v3(co1, pa->state.co, key3[0].co); + + add_v3_v3v3(thkey->co, key3[0].co, co1); + + thkey->time = key3[0].time; + } + } + else { + for (k = 0, hkey = pa->hair; k < pset->totaddkey; k++, hkey++) { + madd_v3_v3v3fl(hkey->co, pa->state.co, pa->state.vel, k * framestep * timestep); + hkey->time += k * framestep; + hkey->weight = 1.f - (float)k / (float)(pset->totaddkey - 1); + } + } + for (k = 0, hkey = pa->hair; k < pset->totaddkey; k++, hkey++) { + psys_mat_hair_to_global(ob, psmd_eval->mesh_final, psys->part->from, pa, hairmat); + invert_m4_m4(imat, hairmat); + mul_m4_v3(imat, hkey->co); + } + } + + if (tree) + BLI_kdtree_3d_free(tree); + } + + MEM_freeN(add_pars); + + BLI_rng_free(rng); + + return n; } /************************* brush edit operator ********************/ typedef struct BrushEdit { - Scene *scene; - ViewLayer *view_layer; - Object *ob; - PTCacheEdit *edit; + Scene *scene; + ViewLayer *view_layer; + Object *ob; + PTCacheEdit *edit; - int first; - int lastmouse[2]; - float zfac; + int first; + int lastmouse[2]; + float zfac; - /* optional cached view settings to avoid setting on every mousemove */ - PEData data; + /* optional cached view settings to avoid setting on every mousemove */ + PEData data; } BrushEdit; static int brush_edit_init(bContext *C, wmOperator *op) { - Scene *scene = CTX_data_scene(C); - ViewLayer *view_layer = CTX_data_view_layer(C); - Object *ob = CTX_data_active_object(C); - PTCacheEdit *edit = PE_get_current(scene, ob); - ARegion *ar = CTX_wm_region(C); - BrushEdit *bedit; - float min[3], max[3]; + Scene *scene = CTX_data_scene(C); + ViewLayer *view_layer = CTX_data_view_layer(C); + Object *ob = CTX_data_active_object(C); + PTCacheEdit *edit = PE_get_current(scene, ob); + ARegion *ar = CTX_wm_region(C); + BrushEdit *bedit; + float min[3], max[3]; - if (!WM_toolsystem_active_tool_is_brush(C)) { - return 0; - } + if (!WM_toolsystem_active_tool_is_brush(C)) { + return 0; + } - /* set the 'distance factor' for grabbing (used in comb etc) */ - INIT_MINMAX(min, max); - PE_minmax(scene, view_layer, min, max); - mid_v3_v3v3(min, min, max); + /* set the 'distance factor' for grabbing (used in comb etc) */ + INIT_MINMAX(min, max); + PE_minmax(scene, view_layer, min, max); + mid_v3_v3v3(min, min, max); - bedit = MEM_callocN(sizeof(BrushEdit), "BrushEdit"); - bedit->first = 1; - op->customdata = bedit; + bedit = MEM_callocN(sizeof(BrushEdit), "BrushEdit"); + bedit->first = 1; + op->customdata = bedit; - bedit->scene = scene; - bedit->view_layer = view_layer; - bedit->ob = ob; - bedit->edit = edit; + bedit->scene = scene; + bedit->view_layer = view_layer; + bedit->ob = ob; + bedit->edit = edit; - bedit->zfac = ED_view3d_calc_zfac(ar->regiondata, min, NULL); + bedit->zfac = ED_view3d_calc_zfac(ar->regiondata, min, NULL); - /* cache view depths and settings for re-use */ - PE_set_view3d_data(C, &bedit->data); - PE_create_random_generator(&bedit->data); + /* cache view depths and settings for re-use */ + PE_set_view3d_data(C, &bedit->data); + PE_create_random_generator(&bedit->data); - return 1; + return 1; } static void brush_edit_apply(bContext *C, wmOperator *op, PointerRNA *itemptr) { - BrushEdit *bedit = op->customdata; - Depsgraph *depsgraph = CTX_data_depsgraph(C); - Scene *scene = bedit->scene; - Object *ob = bedit->ob; - PTCacheEdit *edit = bedit->edit; - ParticleEditSettings *pset = PE_settings(scene); - ParticleSystemModifierData *psmd_eval = edit->psmd_eval; - ParticleBrushData *brush = &pset->brush[pset->brushtype]; - ARegion *ar = CTX_wm_region(C); - float vec[3], mousef[2]; - int mval[2]; - int flip, mouse[2], removed = 0, added = 0, selected = 0, tot_steps = 1, step = 1; - float dx, dy, dmax; - int lock_root = pset->flag & PE_LOCK_FIRST; - - if (!PE_start_edit(edit)) - return; - - RNA_float_get_array(itemptr, "mouse", mousef); - mouse[0] = mousef[0]; - mouse[1] = mousef[1]; - flip = RNA_boolean_get(itemptr, "pen_flip"); - - if (bedit->first) { - bedit->lastmouse[0] = mouse[0]; - bedit->lastmouse[1] = mouse[1]; - } - - dx = mouse[0] - bedit->lastmouse[0]; - dy = mouse[1] - bedit->lastmouse[1]; - - mval[0] = mouse[0]; - mval[1] = mouse[1]; - - - /* disable locking temporatily for disconnected hair */ - if (edit->psys && edit->psys->flag & PSYS_GLOBAL_HAIR) - pset->flag &= ~PE_LOCK_FIRST; - - if (((pset->brushtype == PE_BRUSH_ADD) ? - (sqrtf(dx * dx + dy * dy) > pset->brush[PE_BRUSH_ADD].step) : (dx != 0 || dy != 0)) || bedit->first) - { - PEData data = bedit->data; - data.context = C; // TODO(mai): why isnt this set in bedit->data? - - view3d_operator_needs_opengl(C); - selected = (short)count_selected_keys(scene, edit); - - dmax = max_ff(fabsf(dx), fabsf(dy)); - tot_steps = dmax / (0.2f * pe_brush_size_get(scene, brush)) + 1; - - dx /= (float)tot_steps; - dy /= (float)tot_steps; - - for (step = 1; step <= tot_steps; step++) { - mval[0] = bedit->lastmouse[0] + step * dx; - mval[1] = bedit->lastmouse[1] + step * dy; - - switch (pset->brushtype) { - case PE_BRUSH_COMB: - { - const float mval_f[2] = {dx, dy}; - data.mval = mval; - data.rad = pe_brush_size_get(scene, brush); - - data.combfac = (brush->strength - 0.5f) * 2.0f; - if (data.combfac < 0.0f) - data.combfac = 1.0f - 9.0f * data.combfac; - else - data.combfac = 1.0f - data.combfac; - - invert_m4_m4(ob->imat, ob->obmat); - - ED_view3d_win_to_delta(ar, mval_f, vec, bedit->zfac); - data.dvec = vec; - - foreach_mouse_hit_key(&data, brush_comb, selected); - break; - } - case PE_BRUSH_CUT: - { - if (edit->psys && edit->pathcache) { - data.mval = mval; - data.rad = pe_brush_size_get(scene, brush); - data.cutfac = brush->strength; - - if (selected) - foreach_selected_point(&data, brush_cut); - else - foreach_point(&data, brush_cut); - - removed = remove_tagged_particles(ob, edit->psys, pe_x_mirror(ob)); - if (pset->flag & PE_KEEP_LENGTHS) - recalc_lengths(edit); - } - else - removed = 0; - - break; - } - case PE_BRUSH_LENGTH: - { - data.mval = mval; - - data.rad = pe_brush_size_get(scene, brush); - data.growfac = brush->strength / 50.0f; - - if (brush->invert ^ flip) - data.growfac = 1.0f - data.growfac; - else - data.growfac = 1.0f + data.growfac; - - foreach_mouse_hit_point(&data, brush_length, selected); - - if (pset->flag & PE_KEEP_LENGTHS) - recalc_lengths(edit); - break; - } - case PE_BRUSH_PUFF: - { - if (edit->psys) { - data.mesh = psmd_eval->mesh_final; - data.mval = mval; - data.rad = pe_brush_size_get(scene, brush); - data.select = selected; - - data.pufffac = (brush->strength - 0.5f) * 2.0f; - if (data.pufffac < 0.0f) - data.pufffac = 1.0f - 9.0f * data.pufffac; - else - data.pufffac = 1.0f - data.pufffac; - - data.invert = (brush->invert ^ flip); - invert_m4_m4(ob->imat, ob->obmat); - - foreach_mouse_hit_point(&data, brush_puff, selected); - } - break; - } - case PE_BRUSH_ADD: - { - if (edit->psys && edit->psys->part->from == PART_FROM_FACE) { - data.mval = mval; - - added = brush_add(C, &data, brush->count); - - if (pset->flag & PE_KEEP_LENGTHS) - recalc_lengths(edit); - } - else - added = 0; - break; - } - case PE_BRUSH_SMOOTH: - { - data.mval = mval; - data.rad = pe_brush_size_get(scene, brush); - - data.vec[0] = data.vec[1] = data.vec[2] = 0.0f; - data.tot = 0; - - data.smoothfac = brush->strength; - - invert_m4_m4(ob->imat, ob->obmat); - - foreach_mouse_hit_key(&data, brush_smooth_get, selected); - - if (data.tot) { - mul_v3_fl(data.vec, 1.0f / (float)data.tot); - foreach_mouse_hit_key(&data, brush_smooth_do, selected); - } - - break; - } - case PE_BRUSH_WEIGHT: - { - if (edit->psys) { - data.mesh = psmd_eval->mesh_final; - data.mval = mval; - data.rad = pe_brush_size_get(scene, brush); - - data.weightfac = brush->strength; /* note that this will never be zero */ - - foreach_mouse_hit_key(&data, BKE_brush_weight_get, selected); - } - - break; - } - } - if ((pset->flag & PE_KEEP_LENGTHS) == 0) - recalc_lengths(edit); - - if (ELEM(pset->brushtype, PE_BRUSH_ADD, PE_BRUSH_CUT) && (added || removed)) { - if (pset->brushtype == PE_BRUSH_ADD && pe_x_mirror(ob)) - PE_mirror_x(scene, ob, 1); - - update_world_cos(depsgraph, ob, edit); - psys_free_path_cache(NULL, edit); - DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY); - } - else { - PE_update_object(depsgraph, scene, ob, 1); - } - } - - if (edit->psys) { - WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_EDITED, ob); - BKE_particle_batch_cache_dirty_tag(edit->psys, BKE_PARTICLE_BATCH_DIRTY_ALL); - DEG_id_tag_update(&ob->id, ID_RECALC_PSYS_REDO); - } - else { - DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY); - WM_event_add_notifier(C, NC_OBJECT | ND_MODIFIER, ob); - } - - bedit->lastmouse[0] = mouse[0]; - bedit->lastmouse[1] = mouse[1]; - bedit->first = 0; - } - - pset->flag |= lock_root; + BrushEdit *bedit = op->customdata; + Depsgraph *depsgraph = CTX_data_depsgraph(C); + Scene *scene = bedit->scene; + Object *ob = bedit->ob; + PTCacheEdit *edit = bedit->edit; + ParticleEditSettings *pset = PE_settings(scene); + ParticleSystemModifierData *psmd_eval = edit->psmd_eval; + ParticleBrushData *brush = &pset->brush[pset->brushtype]; + ARegion *ar = CTX_wm_region(C); + float vec[3], mousef[2]; + int mval[2]; + int flip, mouse[2], removed = 0, added = 0, selected = 0, tot_steps = 1, step = 1; + float dx, dy, dmax; + int lock_root = pset->flag & PE_LOCK_FIRST; + + if (!PE_start_edit(edit)) + return; + + RNA_float_get_array(itemptr, "mouse", mousef); + mouse[0] = mousef[0]; + mouse[1] = mousef[1]; + flip = RNA_boolean_get(itemptr, "pen_flip"); + + if (bedit->first) { + bedit->lastmouse[0] = mouse[0]; + bedit->lastmouse[1] = mouse[1]; + } + + dx = mouse[0] - bedit->lastmouse[0]; + dy = mouse[1] - bedit->lastmouse[1]; + + mval[0] = mouse[0]; + mval[1] = mouse[1]; + + /* disable locking temporatily for disconnected hair */ + if (edit->psys && edit->psys->flag & PSYS_GLOBAL_HAIR) + pset->flag &= ~PE_LOCK_FIRST; + + if (((pset->brushtype == PE_BRUSH_ADD) ? + (sqrtf(dx * dx + dy * dy) > pset->brush[PE_BRUSH_ADD].step) : + (dx != 0 || dy != 0)) || + bedit->first) { + PEData data = bedit->data; + data.context = C; // TODO(mai): why isnt this set in bedit->data? + + view3d_operator_needs_opengl(C); + selected = (short)count_selected_keys(scene, edit); + + dmax = max_ff(fabsf(dx), fabsf(dy)); + tot_steps = dmax / (0.2f * pe_brush_size_get(scene, brush)) + 1; + + dx /= (float)tot_steps; + dy /= (float)tot_steps; + + for (step = 1; step <= tot_steps; step++) { + mval[0] = bedit->lastmouse[0] + step * dx; + mval[1] = bedit->lastmouse[1] + step * dy; + + switch (pset->brushtype) { + case PE_BRUSH_COMB: { + const float mval_f[2] = {dx, dy}; + data.mval = mval; + data.rad = pe_brush_size_get(scene, brush); + + data.combfac = (brush->strength - 0.5f) * 2.0f; + if (data.combfac < 0.0f) + data.combfac = 1.0f - 9.0f * data.combfac; + else + data.combfac = 1.0f - data.combfac; + + invert_m4_m4(ob->imat, ob->obmat); + + ED_view3d_win_to_delta(ar, mval_f, vec, bedit->zfac); + data.dvec = vec; + + foreach_mouse_hit_key(&data, brush_comb, selected); + break; + } + case PE_BRUSH_CUT: { + if (edit->psys && edit->pathcache) { + data.mval = mval; + data.rad = pe_brush_size_get(scene, brush); + data.cutfac = brush->strength; + + if (selected) + foreach_selected_point(&data, brush_cut); + else + foreach_point(&data, brush_cut); + + removed = remove_tagged_particles(ob, edit->psys, pe_x_mirror(ob)); + if (pset->flag & PE_KEEP_LENGTHS) + recalc_lengths(edit); + } + else + removed = 0; + + break; + } + case PE_BRUSH_LENGTH: { + data.mval = mval; + + data.rad = pe_brush_size_get(scene, brush); + data.growfac = brush->strength / 50.0f; + + if (brush->invert ^ flip) + data.growfac = 1.0f - data.growfac; + else + data.growfac = 1.0f + data.growfac; + + foreach_mouse_hit_point(&data, brush_length, selected); + + if (pset->flag & PE_KEEP_LENGTHS) + recalc_lengths(edit); + break; + } + case PE_BRUSH_PUFF: { + if (edit->psys) { + data.mesh = psmd_eval->mesh_final; + data.mval = mval; + data.rad = pe_brush_size_get(scene, brush); + data.select = selected; + + data.pufffac = (brush->strength - 0.5f) * 2.0f; + if (data.pufffac < 0.0f) + data.pufffac = 1.0f - 9.0f * data.pufffac; + else + data.pufffac = 1.0f - data.pufffac; + + data.invert = (brush->invert ^ flip); + invert_m4_m4(ob->imat, ob->obmat); + + foreach_mouse_hit_point(&data, brush_puff, selected); + } + break; + } + case PE_BRUSH_ADD: { + if (edit->psys && edit->psys->part->from == PART_FROM_FACE) { + data.mval = mval; + + added = brush_add(C, &data, brush->count); + + if (pset->flag & PE_KEEP_LENGTHS) + recalc_lengths(edit); + } + else + added = 0; + break; + } + case PE_BRUSH_SMOOTH: { + data.mval = mval; + data.rad = pe_brush_size_get(scene, brush); + + data.vec[0] = data.vec[1] = data.vec[2] = 0.0f; + data.tot = 0; + + data.smoothfac = brush->strength; + + invert_m4_m4(ob->imat, ob->obmat); + + foreach_mouse_hit_key(&data, brush_smooth_get, selected); + + if (data.tot) { + mul_v3_fl(data.vec, 1.0f / (float)data.tot); + foreach_mouse_hit_key(&data, brush_smooth_do, selected); + } + + break; + } + case PE_BRUSH_WEIGHT: { + if (edit->psys) { + data.mesh = psmd_eval->mesh_final; + data.mval = mval; + data.rad = pe_brush_size_get(scene, brush); + + data.weightfac = brush->strength; /* note that this will never be zero */ + + foreach_mouse_hit_key(&data, BKE_brush_weight_get, selected); + } + + break; + } + } + if ((pset->flag & PE_KEEP_LENGTHS) == 0) + recalc_lengths(edit); + + if (ELEM(pset->brushtype, PE_BRUSH_ADD, PE_BRUSH_CUT) && (added || removed)) { + if (pset->brushtype == PE_BRUSH_ADD && pe_x_mirror(ob)) + PE_mirror_x(scene, ob, 1); + + update_world_cos(depsgraph, ob, edit); + psys_free_path_cache(NULL, edit); + DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY); + } + else { + PE_update_object(depsgraph, scene, ob, 1); + } + } + + if (edit->psys) { + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_EDITED, ob); + BKE_particle_batch_cache_dirty_tag(edit->psys, BKE_PARTICLE_BATCH_DIRTY_ALL); + DEG_id_tag_update(&ob->id, ID_RECALC_PSYS_REDO); + } + else { + DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY); + WM_event_add_notifier(C, NC_OBJECT | ND_MODIFIER, ob); + } + + bedit->lastmouse[0] = mouse[0]; + bedit->lastmouse[1] = mouse[1]; + bedit->first = 0; + } + + pset->flag |= lock_root; } static void brush_edit_exit(wmOperator *op) { - BrushEdit *bedit = op->customdata; + BrushEdit *bedit = op->customdata; - PE_free_random_generator(&bedit->data); - MEM_freeN(bedit); + PE_free_random_generator(&bedit->data); + MEM_freeN(bedit); } static int brush_edit_exec(bContext *C, wmOperator *op) { - if (!brush_edit_init(C, op)) - return OPERATOR_CANCELLED; + if (!brush_edit_init(C, op)) + return OPERATOR_CANCELLED; - RNA_BEGIN(op->ptr, itemptr, "stroke") - { - brush_edit_apply(C, op, &itemptr); - } - RNA_END; + RNA_BEGIN (op->ptr, itemptr, "stroke") { + brush_edit_apply(C, op, &itemptr); + } + RNA_END; - brush_edit_exit(op); + brush_edit_exit(op); - return OPERATOR_FINISHED; + return OPERATOR_FINISHED; } static void brush_edit_apply_event(bContext *C, wmOperator *op, const wmEvent *event) { - PointerRNA itemptr; - float mouse[2]; + PointerRNA itemptr; + float mouse[2]; - copy_v2fl_v2i(mouse, event->mval); + copy_v2fl_v2i(mouse, event->mval); - /* fill in stroke */ - RNA_collection_add(op->ptr, "stroke", &itemptr); + /* fill in stroke */ + RNA_collection_add(op->ptr, "stroke", &itemptr); - RNA_float_set_array(&itemptr, "mouse", mouse); - RNA_boolean_set(&itemptr, "pen_flip", event->shift != false); // XXX hardcoded + RNA_float_set_array(&itemptr, "mouse", mouse); + RNA_boolean_set(&itemptr, "pen_flip", event->shift != false); // XXX hardcoded - /* apply */ - brush_edit_apply(C, op, &itemptr); + /* apply */ + brush_edit_apply(C, op, &itemptr); } static int brush_edit_invoke(bContext *C, wmOperator *op, const wmEvent *event) { - if (!brush_edit_init(C, op)) - return OPERATOR_CANCELLED; + if (!brush_edit_init(C, op)) + return OPERATOR_CANCELLED; - brush_edit_apply_event(C, op, event); + brush_edit_apply_event(C, op, event); - WM_event_add_modal_handler(C, op); + WM_event_add_modal_handler(C, op); - return OPERATOR_RUNNING_MODAL; + return OPERATOR_RUNNING_MODAL; } static int brush_edit_modal(bContext *C, wmOperator *op, const wmEvent *event) { - switch (event->type) { - case LEFTMOUSE: - case MIDDLEMOUSE: - case RIGHTMOUSE: // XXX hardcoded - if (event->val == KM_RELEASE) { - brush_edit_exit(op); - return OPERATOR_FINISHED; - } - break; - case MOUSEMOVE: - brush_edit_apply_event(C, op, event); - break; - } + switch (event->type) { + case LEFTMOUSE: + case MIDDLEMOUSE: + case RIGHTMOUSE: // XXX hardcoded + if (event->val == KM_RELEASE) { + brush_edit_exit(op); + return OPERATOR_FINISHED; + } + break; + case MOUSEMOVE: + brush_edit_apply_event(C, op, event); + break; + } - return OPERATOR_RUNNING_MODAL; + return OPERATOR_RUNNING_MODAL; } static void brush_edit_cancel(bContext *UNUSED(C), wmOperator *op) { - brush_edit_exit(op); + brush_edit_exit(op); } void PARTICLE_OT_brush_edit(wmOperatorType *ot) { - /* identifiers */ - ot->name = "Brush Edit"; - ot->idname = "PARTICLE_OT_brush_edit"; - ot->description = "Apply a stroke of brush to the particles"; + /* identifiers */ + ot->name = "Brush Edit"; + ot->idname = "PARTICLE_OT_brush_edit"; + ot->description = "Apply a stroke of brush to the particles"; - /* api callbacks */ - ot->exec = brush_edit_exec; - ot->invoke = brush_edit_invoke; - ot->modal = brush_edit_modal; - ot->cancel = brush_edit_cancel; - ot->poll = PE_poll_view3d; + /* api callbacks */ + ot->exec = brush_edit_exec; + ot->invoke = brush_edit_invoke; + ot->modal = brush_edit_modal; + ot->cancel = brush_edit_cancel; + ot->poll = PE_poll_view3d; - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_BLOCKING; + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_BLOCKING; - /* properties */ - PropertyRNA *prop; - prop = RNA_def_collection_runtime(ot->srna, "stroke", &RNA_OperatorStrokeElement, "Stroke", ""); - RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE); + /* properties */ + PropertyRNA *prop; + prop = RNA_def_collection_runtime(ot->srna, "stroke", &RNA_OperatorStrokeElement, "Stroke", ""); + RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE); } /*********************** cut shape ***************************/ static bool shape_cut_poll(bContext *C) { - if (PE_hair_poll(C)) { - Scene *scene = CTX_data_scene(C); - ParticleEditSettings *pset = PE_settings(scene); + if (PE_hair_poll(C)) { + Scene *scene = CTX_data_scene(C); + ParticleEditSettings *pset = PE_settings(scene); - if (pset->shape_object && (pset->shape_object->type == OB_MESH)) { - return true; - } - } + if (pset->shape_object && (pset->shape_object->type == OB_MESH)) { + return true; + } + } - return false; + return false; } typedef struct PointInsideBVH { - BVHTreeFromMesh bvhdata; - int num_hits; + BVHTreeFromMesh bvhdata; + int num_hits; } PointInsideBVH; -static void point_inside_bvh_cb(void *userdata, int index, const BVHTreeRay *ray, BVHTreeRayHit *hit) +static void point_inside_bvh_cb(void *userdata, + int index, + const BVHTreeRay *ray, + BVHTreeRayHit *hit) { - PointInsideBVH *data = userdata; + PointInsideBVH *data = userdata; - data->bvhdata.raycast_callback(&data->bvhdata, index, ray, hit); + data->bvhdata.raycast_callback(&data->bvhdata, index, ray, hit); - if (hit->index != -1) - ++data->num_hits; + if (hit->index != -1) + ++data->num_hits; } /* true if the point is inside the shape mesh */ static bool shape_cut_test_point(PEData *data, ParticleCacheKey *key) { - BVHTreeFromMesh *shape_bvh = &data->shape_bvh; - const float dir[3] = {1.0f, 0.0f, 0.0f}; - PointInsideBVH userdata; + BVHTreeFromMesh *shape_bvh = &data->shape_bvh; + const float dir[3] = {1.0f, 0.0f, 0.0f}; + PointInsideBVH userdata; - userdata.bvhdata = data->shape_bvh; - userdata.num_hits = 0; + userdata.bvhdata = data->shape_bvh; + userdata.num_hits = 0; - BLI_bvhtree_ray_cast_all( - shape_bvh->tree, key->co, dir, 0.0f, BVH_RAYCAST_DIST_MAX, - point_inside_bvh_cb, &userdata); + BLI_bvhtree_ray_cast_all( + shape_bvh->tree, key->co, dir, 0.0f, BVH_RAYCAST_DIST_MAX, point_inside_bvh_cb, &userdata); - /* for any point inside a watertight mesh the number of hits is uneven */ - return (userdata.num_hits % 2) == 1; + /* for any point inside a watertight mesh the number of hits is uneven */ + return (userdata.num_hits % 2) == 1; } static void shape_cut(PEData *data, int pa_index) { - PTCacheEdit *edit = data->edit; - Object *ob = data->ob; - ParticleEditSettings *pset = PE_settings(data->scene); - ParticleCacheKey *key; - - bool cut; - float cut_time = 1.0; - int k, totkeys = 1 << pset->draw_step; - - /* don't cut hidden */ - if (edit->points[pa_index].flag & PEP_HIDE) - return; - - cut = false; - - /* check if root is inside the cut shape */ - key = edit->pathcache[pa_index]; - if (!shape_cut_test_point(data, key)) { - cut_time = -1.0f; - cut = true; - } - else { - for (k = 0; k < totkeys; k++, key++) { - BVHTreeRayHit hit; - float dir[3]; - float len; - - sub_v3_v3v3(dir, (key + 1)->co, key->co); - len = normalize_v3(dir); - - memset(&hit, 0, sizeof(hit)); - hit.index = -1; - hit.dist = len; - BLI_bvhtree_ray_cast(data->shape_bvh.tree, key->co, dir, 0.0f, &hit, data->shape_bvh.raycast_callback, &data->shape_bvh); - if (hit.index >= 0) { - if (hit.dist < len) { - cut_time = (hit.dist / len + (float)k) / (float)totkeys; - cut = true; - break; - } - } - } - } - - if (cut) { - if (cut_time < 0.0f) { - edit->points[pa_index].flag |= PEP_TAG; - } - else { - rekey_particle_to_time(data->context, data->scene, ob, pa_index, cut_time); - edit->points[pa_index].flag |= PEP_EDIT_RECALC; - } - } + PTCacheEdit *edit = data->edit; + Object *ob = data->ob; + ParticleEditSettings *pset = PE_settings(data->scene); + ParticleCacheKey *key; + + bool cut; + float cut_time = 1.0; + int k, totkeys = 1 << pset->draw_step; + + /* don't cut hidden */ + if (edit->points[pa_index].flag & PEP_HIDE) + return; + + cut = false; + + /* check if root is inside the cut shape */ + key = edit->pathcache[pa_index]; + if (!shape_cut_test_point(data, key)) { + cut_time = -1.0f; + cut = true; + } + else { + for (k = 0; k < totkeys; k++, key++) { + BVHTreeRayHit hit; + float dir[3]; + float len; + + sub_v3_v3v3(dir, (key + 1)->co, key->co); + len = normalize_v3(dir); + + memset(&hit, 0, sizeof(hit)); + hit.index = -1; + hit.dist = len; + BLI_bvhtree_ray_cast(data->shape_bvh.tree, + key->co, + dir, + 0.0f, + &hit, + data->shape_bvh.raycast_callback, + &data->shape_bvh); + if (hit.index >= 0) { + if (hit.dist < len) { + cut_time = (hit.dist / len + (float)k) / (float)totkeys; + cut = true; + break; + } + } + } + } + + if (cut) { + if (cut_time < 0.0f) { + edit->points[pa_index].flag |= PEP_TAG; + } + else { + rekey_particle_to_time(data->context, data->scene, ob, pa_index, cut_time); + edit->points[pa_index].flag |= PEP_EDIT_RECALC; + } + } } static int shape_cut_exec(bContext *C, wmOperator *UNUSED(op)) { - Depsgraph *depsgraph = CTX_data_depsgraph(C); - Scene *scene = CTX_data_scene(C); - Object *ob = CTX_data_active_object(C); - ParticleEditSettings *pset = PE_settings(scene); - PTCacheEdit *edit = PE_get_current(scene, ob); - Object *shapeob = pset->shape_object; - int selected = count_selected_keys(scene, edit); - int lock_root = pset->flag & PE_LOCK_FIRST; - - if (!PE_start_edit(edit)) - return OPERATOR_CANCELLED; - - /* disable locking temporatily for disconnected hair */ - if (edit->psys && edit->psys->flag & PSYS_GLOBAL_HAIR) - pset->flag &= ~PE_LOCK_FIRST; - - if (edit->psys && edit->pathcache) { - PEData data; - int removed; - - PE_set_data(C, &data); - if (!PE_create_shape_tree(&data, shapeob)) { - /* shapeob may not have faces... */ - return OPERATOR_CANCELLED; - } - - if (selected) - foreach_selected_point(&data, shape_cut); - else - foreach_point(&data, shape_cut); - - removed = remove_tagged_particles(ob, edit->psys, pe_x_mirror(ob)); - recalc_lengths(edit); - - if (removed) { - update_world_cos(depsgraph, ob, edit); - psys_free_path_cache(NULL, edit); - DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY); - } - else { - PE_update_object(data.depsgraph, scene, ob, 1); - } - - if (edit->psys) { - WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_EDITED, ob); - BKE_particle_batch_cache_dirty_tag(edit->psys, BKE_PARTICLE_BATCH_DIRTY_ALL); - DEG_id_tag_update(&ob->id, ID_RECALC_PSYS_REDO); - } - else { - DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY); - WM_event_add_notifier(C, NC_OBJECT | ND_MODIFIER, ob); - } - - PE_free_shape_tree(&data); - } - - pset->flag |= lock_root; - - return OPERATOR_FINISHED; + Depsgraph *depsgraph = CTX_data_depsgraph(C); + Scene *scene = CTX_data_scene(C); + Object *ob = CTX_data_active_object(C); + ParticleEditSettings *pset = PE_settings(scene); + PTCacheEdit *edit = PE_get_current(scene, ob); + Object *shapeob = pset->shape_object; + int selected = count_selected_keys(scene, edit); + int lock_root = pset->flag & PE_LOCK_FIRST; + + if (!PE_start_edit(edit)) + return OPERATOR_CANCELLED; + + /* disable locking temporatily for disconnected hair */ + if (edit->psys && edit->psys->flag & PSYS_GLOBAL_HAIR) + pset->flag &= ~PE_LOCK_FIRST; + + if (edit->psys && edit->pathcache) { + PEData data; + int removed; + + PE_set_data(C, &data); + if (!PE_create_shape_tree(&data, shapeob)) { + /* shapeob may not have faces... */ + return OPERATOR_CANCELLED; + } + + if (selected) + foreach_selected_point(&data, shape_cut); + else + foreach_point(&data, shape_cut); + + removed = remove_tagged_particles(ob, edit->psys, pe_x_mirror(ob)); + recalc_lengths(edit); + + if (removed) { + update_world_cos(depsgraph, ob, edit); + psys_free_path_cache(NULL, edit); + DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY); + } + else { + PE_update_object(data.depsgraph, scene, ob, 1); + } + + if (edit->psys) { + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_EDITED, ob); + BKE_particle_batch_cache_dirty_tag(edit->psys, BKE_PARTICLE_BATCH_DIRTY_ALL); + DEG_id_tag_update(&ob->id, ID_RECALC_PSYS_REDO); + } + else { + DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY); + WM_event_add_notifier(C, NC_OBJECT | ND_MODIFIER, ob); + } + + PE_free_shape_tree(&data); + } + + pset->flag |= lock_root; + + return OPERATOR_FINISHED; } void PARTICLE_OT_shape_cut(wmOperatorType *ot) { - /* identifiers */ - ot->name = "Shape Cut"; - ot->idname = "PARTICLE_OT_shape_cut"; - ot->description = "Cut hair to conform to the set shape object"; + /* identifiers */ + ot->name = "Shape Cut"; + ot->idname = "PARTICLE_OT_shape_cut"; + ot->description = "Cut hair to conform to the set shape object"; - /* api callbacks */ - ot->exec = shape_cut_exec; - ot->poll = shape_cut_poll; + /* api callbacks */ + ot->exec = shape_cut_exec; + ot->poll = shape_cut_poll; - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } /************************ utilities ******************************/ int PE_minmax(Scene *scene, ViewLayer *view_layer, float min[3], float max[3]) { - Object *ob = OBACT(view_layer); - PTCacheEdit *edit = PE_get_current(scene, ob); - ParticleSystem *psys; - ParticleSystemModifierData *psmd_eval = NULL; - POINT_P; KEY_K; - float co[3], mat[4][4]; - int ok = 0; - - if (!edit) return ok; - - if ((psys = edit->psys)) - psmd_eval = edit->psmd_eval; - else - unit_m4(mat); - - LOOP_VISIBLE_POINTS { - if (psys) - psys_mat_hair_to_global(ob, psmd_eval->mesh_final, psys->part->from, psys->particles + p, mat); - - LOOP_SELECTED_KEYS { - copy_v3_v3(co, key->co); - mul_m4_v3(mat, co); - DO_MINMAX(co, min, max); - ok = 1; - } - } - - if (!ok) { - BKE_object_minmax(ob, min, max, true); - ok = 1; - } - - return ok; + Object *ob = OBACT(view_layer); + PTCacheEdit *edit = PE_get_current(scene, ob); + ParticleSystem *psys; + ParticleSystemModifierData *psmd_eval = NULL; + POINT_P; + KEY_K; + float co[3], mat[4][4]; + int ok = 0; + + if (!edit) + return ok; + + if ((psys = edit->psys)) + psmd_eval = edit->psmd_eval; + else + unit_m4(mat); + + LOOP_VISIBLE_POINTS + { + if (psys) + psys_mat_hair_to_global( + ob, psmd_eval->mesh_final, psys->part->from, psys->particles + p, mat); + + LOOP_SELECTED_KEYS + { + copy_v3_v3(co, key->co); + mul_m4_v3(mat, co); + DO_MINMAX(co, min, max); + ok = 1; + } + } + + if (!ok) { + BKE_object_minmax(ob, min, max, true); + ok = 1; + } + + return ok; } /************************ particle edit toggle operator ************************/ /* initialize needed data for bake edit */ void PE_create_particle_edit( - Depsgraph *depsgraph, Scene *scene, Object *ob, PointCache *cache, ParticleSystem *psys) -{ - Object *ob_eval = DEG_get_evaluated_object(depsgraph, ob); - PTCacheEdit *edit; - ParticleSystemModifierData *psmd = (psys) ? psys_get_modifier(ob, psys) : NULL; - ParticleSystemModifierData *psmd_eval = NULL; - POINT_P; KEY_K; - ParticleData *pa = NULL; - HairKey *hkey; - int totpoint; - - if (psmd != NULL) { - psmd_eval = (ParticleSystemModifierData *)modifiers_findByName(ob_eval, psmd->modifier.name); - } - - /* no psmd->dm happens in case particle system modifier is not enabled */ - if (!(psys && psmd && psmd_eval->mesh_final) && !cache) - return; - - if (cache && cache->flag & PTCACHE_DISK_CACHE) - return; - - if (psys == NULL && (cache && BLI_listbase_is_empty(&cache->mem_cache))) - return; - - edit = (psys) ? psys->edit : cache->edit; - - if (!edit) { - ParticleSystem *psys_eval = NULL; - if (psys) { - psys_eval = psys_eval_get(depsgraph, ob, psys); - psys_copy_particles(psys, psys_eval); - } - - totpoint = psys ? psys->totpart : (int)((PTCacheMem *)cache->mem_cache.first)->totpoint; - - edit = MEM_callocN(sizeof(PTCacheEdit), "PE_create_particle_edit"); - edit->points = MEM_callocN(totpoint * sizeof(PTCacheEditPoint), "PTCacheEditPoints"); - edit->totpoint = totpoint; - - if (psys && !cache) { - edit->psmd = psmd; - edit->psmd_eval = psmd_eval; - psys->edit = edit; - edit->psys = psys; - edit->psys_eval = psys_eval; - - psys->free_edit = PE_free_ptcache_edit; - - edit->pathcache = NULL; - BLI_listbase_clear(&edit->pathcachebufs); - - pa = psys->particles; - LOOP_POINTS { - point->totkey = pa->totkey; - point->keys = MEM_callocN(point->totkey * sizeof(PTCacheEditKey), "ParticleEditKeys"); - point->flag |= PEP_EDIT_RECALC; - - hkey = pa->hair; - LOOP_KEYS { - key->co = hkey->co; - key->time = &hkey->time; - key->flag = hkey->editflag; - if (!(psys->flag & PSYS_GLOBAL_HAIR)) { - key->flag |= PEK_USE_WCO; - hkey->editflag |= PEK_USE_WCO; - } - - hkey++; - } - pa++; - } - update_world_cos(depsgraph, ob, edit); - } - else { - PTCacheMem *pm; - int totframe = 0; - - cache->edit = edit; - cache->free_edit = PE_free_ptcache_edit; - edit->psys = NULL; - - for (pm = cache->mem_cache.first; pm; pm = pm->next) - totframe++; - - for (pm = cache->mem_cache.first; pm; pm = pm->next) { - LOOP_POINTS { - if (BKE_ptcache_mem_pointers_seek(p, pm) == 0) - continue; - - if (!point->totkey) { - key = point->keys = MEM_callocN(totframe * sizeof(PTCacheEditKey), "ParticleEditKeys"); - point->flag |= PEP_EDIT_RECALC; - } - else - key = point->keys + point->totkey; - - key->co = pm->cur[BPHYS_DATA_LOCATION]; - key->vel = pm->cur[BPHYS_DATA_VELOCITY]; - key->rot = pm->cur[BPHYS_DATA_ROTATION]; - key->ftime = (float)pm->frame; - key->time = &key->ftime; - BKE_ptcache_mem_pointers_incr(pm); - - point->totkey++; - } - } - psys = NULL; - } - - /* Causes assert on startup. */ + Depsgraph *depsgraph, Scene *scene, Object *ob, PointCache *cache, ParticleSystem *psys) +{ + Object *ob_eval = DEG_get_evaluated_object(depsgraph, ob); + PTCacheEdit *edit; + ParticleSystemModifierData *psmd = (psys) ? psys_get_modifier(ob, psys) : NULL; + ParticleSystemModifierData *psmd_eval = NULL; + POINT_P; + KEY_K; + ParticleData *pa = NULL; + HairKey *hkey; + int totpoint; + + if (psmd != NULL) { + psmd_eval = (ParticleSystemModifierData *)modifiers_findByName(ob_eval, psmd->modifier.name); + } + + /* no psmd->dm happens in case particle system modifier is not enabled */ + if (!(psys && psmd && psmd_eval->mesh_final) && !cache) + return; + + if (cache && cache->flag & PTCACHE_DISK_CACHE) + return; + + if (psys == NULL && (cache && BLI_listbase_is_empty(&cache->mem_cache))) + return; + + edit = (psys) ? psys->edit : cache->edit; + + if (!edit) { + ParticleSystem *psys_eval = NULL; + if (psys) { + psys_eval = psys_eval_get(depsgraph, ob, psys); + psys_copy_particles(psys, psys_eval); + } + + totpoint = psys ? psys->totpart : (int)((PTCacheMem *)cache->mem_cache.first)->totpoint; + + edit = MEM_callocN(sizeof(PTCacheEdit), "PE_create_particle_edit"); + edit->points = MEM_callocN(totpoint * sizeof(PTCacheEditPoint), "PTCacheEditPoints"); + edit->totpoint = totpoint; + + if (psys && !cache) { + edit->psmd = psmd; + edit->psmd_eval = psmd_eval; + psys->edit = edit; + edit->psys = psys; + edit->psys_eval = psys_eval; + + psys->free_edit = PE_free_ptcache_edit; + + edit->pathcache = NULL; + BLI_listbase_clear(&edit->pathcachebufs); + + pa = psys->particles; + LOOP_POINTS + { + point->totkey = pa->totkey; + point->keys = MEM_callocN(point->totkey * sizeof(PTCacheEditKey), "ParticleEditKeys"); + point->flag |= PEP_EDIT_RECALC; + + hkey = pa->hair; + LOOP_KEYS + { + key->co = hkey->co; + key->time = &hkey->time; + key->flag = hkey->editflag; + if (!(psys->flag & PSYS_GLOBAL_HAIR)) { + key->flag |= PEK_USE_WCO; + hkey->editflag |= PEK_USE_WCO; + } + + hkey++; + } + pa++; + } + update_world_cos(depsgraph, ob, edit); + } + else { + PTCacheMem *pm; + int totframe = 0; + + cache->edit = edit; + cache->free_edit = PE_free_ptcache_edit; + edit->psys = NULL; + + for (pm = cache->mem_cache.first; pm; pm = pm->next) + totframe++; + + for (pm = cache->mem_cache.first; pm; pm = pm->next) { + LOOP_POINTS + { + if (BKE_ptcache_mem_pointers_seek(p, pm) == 0) + continue; + + if (!point->totkey) { + key = point->keys = MEM_callocN(totframe * sizeof(PTCacheEditKey), "ParticleEditKeys"); + point->flag |= PEP_EDIT_RECALC; + } + else + key = point->keys + point->totkey; + + key->co = pm->cur[BPHYS_DATA_LOCATION]; + key->vel = pm->cur[BPHYS_DATA_VELOCITY]; + key->rot = pm->cur[BPHYS_DATA_ROTATION]; + key->ftime = (float)pm->frame; + key->time = &key->ftime; + BKE_ptcache_mem_pointers_incr(pm); + + point->totkey++; + } + } + psys = NULL; + } + + /* Causes assert on startup. */ #if 0 - UI_GetThemeColor3ubv(TH_EDGE_SELECT, edit->sel_col); - UI_GetThemeColor3ubv(TH_WIRE, edit->nosel_col); + UI_GetThemeColor3ubv(TH_EDGE_SELECT, edit->sel_col); + UI_GetThemeColor3ubv(TH_WIRE, edit->nosel_col); #else - memset(edit->sel_col, 0xff, sizeof(edit->sel_col)); - memset(edit->nosel_col, 0x00, sizeof(edit->nosel_col)); + memset(edit->sel_col, 0xff, sizeof(edit->sel_col)); + memset(edit->nosel_col, 0x00, sizeof(edit->nosel_col)); #endif - recalc_lengths(edit); - if (psys && !cache) - recalc_emitter_field(depsgraph, ob, psys); + recalc_lengths(edit); + if (psys && !cache) + recalc_emitter_field(depsgraph, ob, psys); - PE_update_object(depsgraph, scene, ob, 1); - } + PE_update_object(depsgraph, scene, ob, 1); + } } static bool particle_edit_toggle_poll(bContext *C) { - Object *ob = CTX_data_active_object(C); + Object *ob = CTX_data_active_object(C); - if (ob == NULL || ob->type != OB_MESH) - return 0; - if (!ob->data || ID_IS_LINKED(ob->data)) - return 0; - if (CTX_data_edit_object(C)) - return 0; + if (ob == NULL || ob->type != OB_MESH) + return 0; + if (!ob->data || ID_IS_LINKED(ob->data)) + return 0; + if (CTX_data_edit_object(C)) + return 0; - return (ob->particlesystem.first || - modifiers_findByType(ob, eModifierType_Cloth) || - modifiers_findByType(ob, eModifierType_Softbody)); + return (ob->particlesystem.first || modifiers_findByType(ob, eModifierType_Cloth) || + modifiers_findByType(ob, eModifierType_Softbody)); } static void free_all_psys_edit(Object *object) { - for (ParticleSystem *psys = object->particlesystem.first; - psys != NULL; - psys = psys->next) - { - if (psys->edit != NULL) { - BLI_assert(psys->free_edit != NULL); - psys->free_edit(psys->edit); - psys->free_edit = NULL; - psys->edit = NULL; - } - } + for (ParticleSystem *psys = object->particlesystem.first; psys != NULL; psys = psys->next) { + if (psys->edit != NULL) { + BLI_assert(psys->free_edit != NULL); + psys->free_edit(psys->edit); + psys->free_edit = NULL; + psys->edit = NULL; + } + } } static int particle_edit_toggle_exec(bContext *C, wmOperator *op) { - struct wmMsgBus *mbus = CTX_wm_message_bus(C); - Depsgraph *depsgraph = CTX_data_depsgraph(C); - Scene *scene = CTX_data_scene(C); - Object *ob = CTX_data_active_object(C); - const int mode_flag = OB_MODE_PARTICLE_EDIT; - const bool is_mode_set = (ob->mode & mode_flag) != 0; + struct wmMsgBus *mbus = CTX_wm_message_bus(C); + Depsgraph *depsgraph = CTX_data_depsgraph(C); + Scene *scene = CTX_data_scene(C); + Object *ob = CTX_data_active_object(C); + const int mode_flag = OB_MODE_PARTICLE_EDIT; + const bool is_mode_set = (ob->mode & mode_flag) != 0; - if (!is_mode_set) { - if (!ED_object_mode_compat_set(C, ob, mode_flag, op->reports)) { - return OPERATOR_CANCELLED; - } - } + if (!is_mode_set) { + if (!ED_object_mode_compat_set(C, ob, mode_flag, op->reports)) { + return OPERATOR_CANCELLED; + } + } - if (!is_mode_set) { - PTCacheEdit *edit; + if (!is_mode_set) { + PTCacheEdit *edit; - ob->mode |= mode_flag; + ob->mode |= mode_flag; - edit = PE_create_current(depsgraph, scene, ob); + edit = PE_create_current(depsgraph, scene, ob); - /* Mesh may have changed since last entering editmode. - * note, this may have run before if the edit data was just created, - * so could avoid this and speed up a little. */ - if (edit && edit->psys) { - /* Make sure pointer to the evaluated modifier data is up to date, - * with possible changes applied when object was outside of the - * edit mode. */ - Object *object_eval = DEG_get_evaluated_object(depsgraph, ob); - edit->psmd_eval = (ParticleSystemModifierData *)modifiers_findByName( - object_eval, edit->psmd->modifier.name); - recalc_emitter_field(depsgraph, ob, edit->psys); - } + /* Mesh may have changed since last entering editmode. + * note, this may have run before if the edit data was just created, + * so could avoid this and speed up a little. */ + if (edit && edit->psys) { + /* Make sure pointer to the evaluated modifier data is up to date, + * with possible changes applied when object was outside of the + * edit mode. */ + Object *object_eval = DEG_get_evaluated_object(depsgraph, ob); + edit->psmd_eval = (ParticleSystemModifierData *)modifiers_findByName( + object_eval, edit->psmd->modifier.name); + recalc_emitter_field(depsgraph, ob, edit->psys); + } - toggle_particle_cursor(C, 1); - WM_event_add_notifier(C, NC_SCENE | ND_MODE | NS_MODE_PARTICLE, NULL); - } - else { - ob->mode &= ~mode_flag; - toggle_particle_cursor(C, 0); - free_all_psys_edit(ob); - WM_event_add_notifier(C, NC_SCENE | ND_MODE | NS_MODE_OBJECT, NULL); - } + toggle_particle_cursor(C, 1); + WM_event_add_notifier(C, NC_SCENE | ND_MODE | NS_MODE_PARTICLE, NULL); + } + else { + ob->mode &= ~mode_flag; + toggle_particle_cursor(C, 0); + free_all_psys_edit(ob); + WM_event_add_notifier(C, NC_SCENE | ND_MODE | NS_MODE_OBJECT, NULL); + } - DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY | ID_RECALC_COPY_ON_WRITE); + DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY | ID_RECALC_COPY_ON_WRITE); - WM_msg_publish_rna_prop(mbus, &ob->id, ob, Object, mode); + WM_msg_publish_rna_prop(mbus, &ob->id, ob, Object, mode); - WM_toolsystem_update_from_context_view3d(C); + WM_toolsystem_update_from_context_view3d(C); - return OPERATOR_FINISHED; + return OPERATOR_FINISHED; } void PARTICLE_OT_particle_edit_toggle(wmOperatorType *ot) { - /* identifiers */ - ot->name = "Particle Edit Toggle"; - ot->idname = "PARTICLE_OT_particle_edit_toggle"; - ot->description = "Toggle particle edit mode"; + /* identifiers */ + ot->name = "Particle Edit Toggle"; + ot->idname = "PARTICLE_OT_particle_edit_toggle"; + ot->description = "Toggle particle edit mode"; - /* api callbacks */ - ot->exec = particle_edit_toggle_exec; - ot->poll = particle_edit_toggle_poll; + /* api callbacks */ + ot->exec = particle_edit_toggle_exec; + ot->poll = particle_edit_toggle_poll; - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } - /************************ set editable operator ************************/ static int clear_edited_exec(bContext *C, wmOperator *UNUSED(op)) { - Object *ob = CTX_data_active_object(C); - ParticleSystem *psys = psys_get_current(ob); + Object *ob = CTX_data_active_object(C); + ParticleSystem *psys = psys_get_current(ob); - if (psys->edit) { - if (psys->edit->edited || 1) { - PE_free_ptcache_edit(psys->edit); + if (psys->edit) { + if (psys->edit->edited || 1) { + PE_free_ptcache_edit(psys->edit); - psys->edit = NULL; - psys->free_edit = NULL; + psys->edit = NULL; + psys->free_edit = NULL; - psys->recalc |= ID_RECALC_PSYS_RESET; - psys->flag &= ~PSYS_GLOBAL_HAIR; - psys->flag &= ~PSYS_EDITED; + psys->recalc |= ID_RECALC_PSYS_RESET; + psys->flag &= ~PSYS_GLOBAL_HAIR; + psys->flag &= ~PSYS_EDITED; - psys_reset(psys, PSYS_RESET_DEPSGRAPH); - WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_EDITED, ob); - DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY); - } - } - else { /* some operation might have protected hair from editing so let's clear the flag */ - psys->recalc |= ID_RECALC_PSYS_RESET; - psys->flag &= ~PSYS_GLOBAL_HAIR; - psys->flag &= ~PSYS_EDITED; - WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_EDITED, ob); - DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY); - } + psys_reset(psys, PSYS_RESET_DEPSGRAPH); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_EDITED, ob); + DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY); + } + } + else { /* some operation might have protected hair from editing so let's clear the flag */ + psys->recalc |= ID_RECALC_PSYS_RESET; + psys->flag &= ~PSYS_GLOBAL_HAIR; + psys->flag &= ~PSYS_EDITED; + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_EDITED, ob); + DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY); + } - return OPERATOR_FINISHED; + return OPERATOR_FINISHED; } static int clear_edited_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event)) { - return WM_operator_confirm_message(C, op, "Lose changes done in particle mode? (no undo)"); + return WM_operator_confirm_message(C, op, "Lose changes done in particle mode? (no undo)"); } void PARTICLE_OT_edited_clear(wmOperatorType *ot) { - /* identifiers */ - ot->name = "Clear Edited"; - ot->idname = "PARTICLE_OT_edited_clear"; - ot->description = "Undo all edition performed on the particle system"; + /* identifiers */ + ot->name = "Clear Edited"; + ot->idname = "PARTICLE_OT_edited_clear"; + ot->description = "Undo all edition performed on the particle system"; - /* api callbacks */ - ot->exec = clear_edited_exec; - ot->poll = particle_edit_toggle_poll; - ot->invoke = clear_edited_invoke; + /* api callbacks */ + ot->exec = clear_edited_exec; + ot->poll = particle_edit_toggle_poll; + ot->invoke = clear_edited_invoke; - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } /************************ Unify length operator ************************/ static float calculate_point_length(PTCacheEditPoint *point) { - float length = 0.0f; - KEY_K; - LOOP_KEYS { - if (k > 0) { - length += len_v3v3((key - 1)->co, key->co); - } - } - return length; + float length = 0.0f; + KEY_K; + LOOP_KEYS + { + if (k > 0) { + length += len_v3v3((key - 1)->co, key->co); + } + } + return length; } static float calculate_average_length(PTCacheEdit *edit) { - int num_selected = 0; - float total_length = 0; - POINT_P; - LOOP_SELECTED_POINTS { - total_length += calculate_point_length(point); - ++num_selected; - } - if (num_selected == 0) { - return 0.0f; - } - return total_length / num_selected; + int num_selected = 0; + float total_length = 0; + POINT_P; + LOOP_SELECTED_POINTS + { + total_length += calculate_point_length(point); + ++num_selected; + } + if (num_selected == 0) { + return 0.0f; + } + return total_length / num_selected; } static void scale_point_factor(PTCacheEditPoint *point, float factor) { - float orig_prev_co[3], prev_co[3]; - KEY_K; - LOOP_KEYS { - if (k == 0) { - copy_v3_v3(orig_prev_co, key->co); - copy_v3_v3(prev_co, key->co); - } - else { - float new_co[3]; - float delta[3]; - - sub_v3_v3v3(delta, key->co, orig_prev_co); - mul_v3_fl(delta, factor); - add_v3_v3v3(new_co, prev_co, delta); - - copy_v3_v3(orig_prev_co, key->co); - copy_v3_v3(key->co, new_co); - copy_v3_v3(prev_co, key->co); - } - } - point->flag |= PEP_EDIT_RECALC; + float orig_prev_co[3], prev_co[3]; + KEY_K; + LOOP_KEYS + { + if (k == 0) { + copy_v3_v3(orig_prev_co, key->co); + copy_v3_v3(prev_co, key->co); + } + else { + float new_co[3]; + float delta[3]; + + sub_v3_v3v3(delta, key->co, orig_prev_co); + mul_v3_fl(delta, factor); + add_v3_v3v3(new_co, prev_co, delta); + + copy_v3_v3(orig_prev_co, key->co); + copy_v3_v3(key->co, new_co); + copy_v3_v3(prev_co, key->co); + } + } + point->flag |= PEP_EDIT_RECALC; } static void scale_point_to_length(PTCacheEditPoint *point, float length) { - const float point_length = calculate_point_length(point); - if (point_length != 0.0f) { - const float factor = length / point_length; - scale_point_factor(point, factor); - } + const float point_length = calculate_point_length(point); + if (point_length != 0.0f) { + const float factor = length / point_length; + scale_point_factor(point, factor); + } } static void scale_points_to_length(PTCacheEdit *edit, float length) { - POINT_P; - LOOP_SELECTED_POINTS { - scale_point_to_length(point, length); - } - recalc_lengths(edit); + POINT_P; + LOOP_SELECTED_POINTS + { + scale_point_to_length(point, length); + } + recalc_lengths(edit); } static int unify_length_exec(bContext *C, wmOperator *UNUSED(op)) { - Object *ob = CTX_data_active_object(C); - Scene *scene = CTX_data_scene(C); - Depsgraph *depsgraph = CTX_data_depsgraph(C); + Object *ob = CTX_data_active_object(C); + Scene *scene = CTX_data_scene(C); + Depsgraph *depsgraph = CTX_data_depsgraph(C); - PTCacheEdit *edit = PE_get_current(scene, ob); - float average_length = calculate_average_length(edit); + PTCacheEdit *edit = PE_get_current(scene, ob); + float average_length = calculate_average_length(edit); - if (average_length == 0.0f) { - return OPERATOR_CANCELLED; - } - scale_points_to_length(edit, average_length); + if (average_length == 0.0f) { + return OPERATOR_CANCELLED; + } + scale_points_to_length(edit, average_length); - PE_update_object(depsgraph, scene, ob, 1); - if (edit->psys) { - WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_EDITED, ob); - } - else { - DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY); - WM_event_add_notifier(C, NC_OBJECT | ND_MODIFIER, ob); - } + PE_update_object(depsgraph, scene, ob, 1); + if (edit->psys) { + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE | NA_EDITED, ob); + } + else { + DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY); + WM_event_add_notifier(C, NC_OBJECT | ND_MODIFIER, ob); + } - return OPERATOR_FINISHED; + return OPERATOR_FINISHED; } void PARTICLE_OT_unify_length(struct wmOperatorType *ot) { - /* identifiers */ - ot->name = "Unify Length"; - ot->idname = "PARTICLE_OT_unify_length"; - ot->description = "Make selected hair the same length"; + /* identifiers */ + ot->name = "Unify Length"; + ot->idname = "PARTICLE_OT_unify_length"; + ot->description = "Make selected hair the same length"; - /* api callbacks */ - ot->exec = unify_length_exec; - ot->poll = PE_poll_view3d; + /* api callbacks */ + ot->exec = unify_length_exec; + ot->poll = PE_poll_view3d; - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } diff --git a/source/blender/editors/physics/particle_edit_undo.c b/source/blender/editors/physics/particle_edit_undo.c index 877bfbac953..be625eb939f 100644 --- a/source/blender/editors/physics/particle_edit_undo.c +++ b/source/blender/editors/physics/particle_edit_undo.c @@ -56,153 +56,161 @@ static void undoptcache_from_editcache(PTCacheUndo *undo, PTCacheEdit *edit) { - PTCacheEditPoint *point; - int i; + PTCacheEditPoint *point; + int i; - size_t mem_used_prev = MEM_get_memory_in_use(); + size_t mem_used_prev = MEM_get_memory_in_use(); - undo->totpoint = edit->totpoint; + undo->totpoint = edit->totpoint; - if (edit->psys) { - ParticleData *pa; + if (edit->psys) { + ParticleData *pa; - pa = undo->particles = MEM_dupallocN(edit->psys->particles); + pa = undo->particles = MEM_dupallocN(edit->psys->particles); - for (i = 0; i < edit->totpoint; i++, pa++) { - pa->hair = MEM_dupallocN(pa->hair); - } + for (i = 0; i < edit->totpoint; i++, pa++) { + pa->hair = MEM_dupallocN(pa->hair); + } - undo->psys_flag = edit->psys->flag; - } - else { - PTCacheMem *pm; + undo->psys_flag = edit->psys->flag; + } + else { + PTCacheMem *pm; - BLI_duplicatelist(&undo->mem_cache, &edit->pid.cache->mem_cache); - pm = undo->mem_cache.first; + BLI_duplicatelist(&undo->mem_cache, &edit->pid.cache->mem_cache); + pm = undo->mem_cache.first; - for (; pm; pm = pm->next) { - for (i = 0; i < BPHYS_TOT_DATA; i++) { - pm->data[i] = MEM_dupallocN(pm->data[i]); - } - } - } + for (; pm; pm = pm->next) { + for (i = 0; i < BPHYS_TOT_DATA; i++) { + pm->data[i] = MEM_dupallocN(pm->data[i]); + } + } + } - point = undo->points = MEM_dupallocN(edit->points); - undo->totpoint = edit->totpoint; + point = undo->points = MEM_dupallocN(edit->points); + undo->totpoint = edit->totpoint; - for (i = 0; i < edit->totpoint; i++, point++) { - point->keys = MEM_dupallocN(point->keys); - /* no need to update edit key->co & key->time pointers here */ - } + for (i = 0; i < edit->totpoint; i++, point++) { + point->keys = MEM_dupallocN(point->keys); + /* no need to update edit key->co & key->time pointers here */ + } - size_t mem_used_curr = MEM_get_memory_in_use(); + size_t mem_used_curr = MEM_get_memory_in_use(); - undo->undo_size = mem_used_prev < mem_used_curr ? mem_used_curr - mem_used_prev : sizeof(PTCacheUndo); + undo->undo_size = mem_used_prev < mem_used_curr ? mem_used_curr - mem_used_prev : + sizeof(PTCacheUndo); } static void undoptcache_to_editcache(PTCacheUndo *undo, PTCacheEdit *edit) { - ParticleSystem *psys = edit->psys; - ParticleData *pa; - HairKey *hkey; - POINT_P; KEY_K; - - LOOP_POINTS { - if (psys && psys->particles[p].hair) { - MEM_freeN(psys->particles[p].hair); - } - - if (point->keys) { - MEM_freeN(point->keys); - } - } - if (psys && psys->particles) { - MEM_freeN(psys->particles); - } - if (edit->points) { - MEM_freeN(edit->points); - } - if (edit->mirror_cache) { - MEM_freeN(edit->mirror_cache); - edit->mirror_cache = NULL; - } - - edit->points = MEM_dupallocN(undo->points); - edit->totpoint = undo->totpoint; - - LOOP_POINTS { - point->keys = MEM_dupallocN(point->keys); - } - - if (psys) { - psys->particles = MEM_dupallocN(undo->particles); - - psys->totpart = undo->totpoint; - - LOOP_POINTS { - pa = psys->particles + p; - hkey = pa->hair = MEM_dupallocN(pa->hair); - - LOOP_KEYS { - key->co = hkey->co; - key->time = &hkey->time; - hkey++; - } - } - - psys->flag = undo->psys_flag; - } - else { - PTCacheMem *pm; - int i; - - BKE_ptcache_free_mem(&edit->pid.cache->mem_cache); - - BLI_duplicatelist(&edit->pid.cache->mem_cache, &undo->mem_cache); - - pm = edit->pid.cache->mem_cache.first; - - for (; pm; pm = pm->next) { - for (i = 0; i < BPHYS_TOT_DATA; i++) { - pm->data[i] = MEM_dupallocN(pm->data[i]); - } - BKE_ptcache_mem_pointers_init(pm); - - LOOP_POINTS { - LOOP_KEYS { - if ((int)key->ftime == (int)pm->frame) { - key->co = pm->cur[BPHYS_DATA_LOCATION]; - key->vel = pm->cur[BPHYS_DATA_VELOCITY]; - key->rot = pm->cur[BPHYS_DATA_ROTATION]; - key->time = &key->ftime; - } - } - BKE_ptcache_mem_pointers_incr(pm); - } - } - } + ParticleSystem *psys = edit->psys; + ParticleData *pa; + HairKey *hkey; + POINT_P; + KEY_K; + + LOOP_POINTS + { + if (psys && psys->particles[p].hair) { + MEM_freeN(psys->particles[p].hair); + } + + if (point->keys) { + MEM_freeN(point->keys); + } + } + if (psys && psys->particles) { + MEM_freeN(psys->particles); + } + if (edit->points) { + MEM_freeN(edit->points); + } + if (edit->mirror_cache) { + MEM_freeN(edit->mirror_cache); + edit->mirror_cache = NULL; + } + + edit->points = MEM_dupallocN(undo->points); + edit->totpoint = undo->totpoint; + + LOOP_POINTS + { + point->keys = MEM_dupallocN(point->keys); + } + + if (psys) { + psys->particles = MEM_dupallocN(undo->particles); + + psys->totpart = undo->totpoint; + + LOOP_POINTS + { + pa = psys->particles + p; + hkey = pa->hair = MEM_dupallocN(pa->hair); + + LOOP_KEYS + { + key->co = hkey->co; + key->time = &hkey->time; + hkey++; + } + } + + psys->flag = undo->psys_flag; + } + else { + PTCacheMem *pm; + int i; + + BKE_ptcache_free_mem(&edit->pid.cache->mem_cache); + + BLI_duplicatelist(&edit->pid.cache->mem_cache, &undo->mem_cache); + + pm = edit->pid.cache->mem_cache.first; + + for (; pm; pm = pm->next) { + for (i = 0; i < BPHYS_TOT_DATA; i++) { + pm->data[i] = MEM_dupallocN(pm->data[i]); + } + BKE_ptcache_mem_pointers_init(pm); + + LOOP_POINTS + { + LOOP_KEYS + { + if ((int)key->ftime == (int)pm->frame) { + key->co = pm->cur[BPHYS_DATA_LOCATION]; + key->vel = pm->cur[BPHYS_DATA_VELOCITY]; + key->rot = pm->cur[BPHYS_DATA_ROTATION]; + key->time = &key->ftime; + } + } + BKE_ptcache_mem_pointers_incr(pm); + } + } + } } static void undoptcache_free_data(PTCacheUndo *undo) { - PTCacheEditPoint *point; - int i; - - for (i = 0, point = undo->points; i < undo->totpoint; i++, point++) { - if (undo->particles && (undo->particles + i)->hair) { - MEM_freeN((undo->particles + i)->hair); - } - if (point->keys) { - MEM_freeN(point->keys); - } - } - if (undo->points) { - MEM_freeN(undo->points); - } - if (undo->particles) { - MEM_freeN(undo->particles); - } - BKE_ptcache_free_mem(&undo->mem_cache); + PTCacheEditPoint *point; + int i; + + for (i = 0, point = undo->points; i < undo->totpoint; i++, point++) { + if (undo->particles && (undo->particles + i)->hair) { + MEM_freeN((undo->particles + i)->hair); + } + if (point->keys) { + MEM_freeN(point->keys); + } + } + if (undo->points) { + MEM_freeN(undo->points); + } + if (undo->particles) { + MEM_freeN(undo->particles); + } + BKE_ptcache_free_mem(&undo->mem_cache); } /** \} */ @@ -212,80 +220,86 @@ static void undoptcache_free_data(PTCacheUndo *undo) * \{ */ typedef struct ParticleUndoStep { - UndoStep step; - UndoRefID_Scene scene_ref; - UndoRefID_Object object_ref; - PTCacheUndo data; + UndoStep step; + UndoRefID_Scene scene_ref; + UndoRefID_Object object_ref; + PTCacheUndo data; } ParticleUndoStep; static bool particle_undosys_poll(struct bContext *C) { - Scene *scene = CTX_data_scene(C); - ViewLayer *view_layer = CTX_data_view_layer(C); - Object *ob = OBACT(view_layer); - PTCacheEdit *edit = PE_get_current(scene, ob); + Scene *scene = CTX_data_scene(C); + ViewLayer *view_layer = CTX_data_view_layer(C); + Object *ob = OBACT(view_layer); + PTCacheEdit *edit = PE_get_current(scene, ob); - return (edit != NULL); + return (edit != NULL); } -static bool particle_undosys_step_encode(struct bContext *C, struct Main *UNUSED(bmain), UndoStep *us_p) +static bool particle_undosys_step_encode(struct bContext *C, + struct Main *UNUSED(bmain), + UndoStep *us_p) { - ParticleUndoStep *us = (ParticleUndoStep *)us_p; - ViewLayer *view_layer = CTX_data_view_layer(C); - us->scene_ref.ptr = CTX_data_scene(C); - us->object_ref.ptr = OBACT(view_layer); - PTCacheEdit *edit = PE_get_current(us->scene_ref.ptr, us->object_ref.ptr); - undoptcache_from_editcache(&us->data, edit); - return true; + ParticleUndoStep *us = (ParticleUndoStep *)us_p; + ViewLayer *view_layer = CTX_data_view_layer(C); + us->scene_ref.ptr = CTX_data_scene(C); + us->object_ref.ptr = OBACT(view_layer); + PTCacheEdit *edit = PE_get_current(us->scene_ref.ptr, us->object_ref.ptr); + undoptcache_from_editcache(&us->data, edit); + return true; } -static void particle_undosys_step_decode(struct bContext *C, struct Main *UNUSED(bmain), UndoStep *us_p, int UNUSED(dir)) +static void particle_undosys_step_decode(struct bContext *C, + struct Main *UNUSED(bmain), + UndoStep *us_p, + int UNUSED(dir)) { - /* TODO(campbell): undo_system: use low-level API to set mode. */ - ED_object_mode_set(C, OB_MODE_PARTICLE_EDIT); - BLI_assert(particle_undosys_poll(C)); - - ParticleUndoStep *us = (ParticleUndoStep *)us_p; - Scene *scene = us->scene_ref.ptr; - Object *ob = us->object_ref.ptr; - PTCacheEdit *edit = PE_get_current(scene, ob); - if (edit) { - undoptcache_to_editcache(&us->data, edit); - DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY); - } - else { - BLI_assert(0); - } + /* TODO(campbell): undo_system: use low-level API to set mode. */ + ED_object_mode_set(C, OB_MODE_PARTICLE_EDIT); + BLI_assert(particle_undosys_poll(C)); + + ParticleUndoStep *us = (ParticleUndoStep *)us_p; + Scene *scene = us->scene_ref.ptr; + Object *ob = us->object_ref.ptr; + PTCacheEdit *edit = PE_get_current(scene, ob); + if (edit) { + undoptcache_to_editcache(&us->data, edit); + DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY); + } + else { + BLI_assert(0); + } } static void particle_undosys_step_free(UndoStep *us_p) { - ParticleUndoStep *us = (ParticleUndoStep *)us_p; - undoptcache_free_data(&us->data); + ParticleUndoStep *us = (ParticleUndoStep *)us_p; + undoptcache_free_data(&us->data); } -static void particle_undosys_foreach_ID_ref( - UndoStep *us_p, UndoTypeForEachIDRefFn foreach_ID_ref_fn, void *user_data) +static void particle_undosys_foreach_ID_ref(UndoStep *us_p, + UndoTypeForEachIDRefFn foreach_ID_ref_fn, + void *user_data) { - ParticleUndoStep *us = (ParticleUndoStep *)us_p; - foreach_ID_ref_fn(user_data, ((UndoRefID *)&us->scene_ref)); - foreach_ID_ref_fn(user_data, ((UndoRefID *)&us->object_ref)); + ParticleUndoStep *us = (ParticleUndoStep *)us_p; + foreach_ID_ref_fn(user_data, ((UndoRefID *)&us->scene_ref)); + foreach_ID_ref_fn(user_data, ((UndoRefID *)&us->object_ref)); } /* Export for ED_undo_sys. */ void ED_particle_undosys_type(UndoType *ut) { - ut->name = "Edit Particle"; - ut->poll = particle_undosys_poll; - ut->step_encode = particle_undosys_step_encode; - ut->step_decode = particle_undosys_step_decode; - ut->step_free = particle_undosys_step_free; + ut->name = "Edit Particle"; + ut->poll = particle_undosys_poll; + ut->step_encode = particle_undosys_step_encode; + ut->step_decode = particle_undosys_step_decode; + ut->step_free = particle_undosys_step_free; - ut->step_foreach_ID_ref = particle_undosys_foreach_ID_ref; + ut->step_foreach_ID_ref = particle_undosys_foreach_ID_ref; - ut->use_context = true; + ut->use_context = true; - ut->step_size = sizeof(ParticleUndoStep); + ut->step_size = sizeof(ParticleUndoStep); } /** \} */ diff --git a/source/blender/editors/physics/particle_edit_utildefines.h b/source/blender/editors/physics/particle_edit_utildefines.h index afdeb5e985c..da27420505f 100644 --- a/source/blender/editors/physics/particle_edit_utildefines.h +++ b/source/blender/editors/physics/particle_edit_utildefines.h @@ -24,19 +24,39 @@ #ifndef __PARTICLE_EDIT_UTILDEFNIES_H__ #define __PARTICLE_EDIT_UTILDEFNIES_H__ -#define KEY_K PTCacheEditKey *key; int k -#define POINT_P PTCacheEditPoint *point; int p -#define LOOP_POINTS for (p = 0, point = edit->points; p < edit->totpoint; p++, point++) -#define LOOP_VISIBLE_POINTS for (p = 0, point = edit->points; p < edit->totpoint; p++, point++) if (!(point->flag & PEP_HIDE)) -#define LOOP_SELECTED_POINTS for (p = 0, point = edit->points; p < edit->totpoint; p++, point++) if (point_is_selected(point)) -#define LOOP_UNSELECTED_POINTS for (p = 0, point = edit->points; p < edit->totpoint; p++, point++) if (!point_is_selected(point)) -#define LOOP_EDITED_POINTS for (p = 0, point = edit->points; p < edit->totpoint; p++, point++) if (point->flag & PEP_EDIT_RECALC) -#define LOOP_TAGGED_POINTS for (p = 0, point = edit->points; p < edit->totpoint; p++, point++) if (point->flag & PEP_TAG) -#define LOOP_KEYS for (k = 0, key = point->keys; k < point->totkey; k++, key++) -#define LOOP_VISIBLE_KEYS for (k = 0, key = point->keys; k < point->totkey; k++, key++) if (!(key->flag & PEK_HIDE)) -#define LOOP_SELECTED_KEYS for (k = 0, key = point->keys; k < point->totkey; k++, key++) if ((key->flag & PEK_SELECT) && !(key->flag & PEK_HIDE)) -#define LOOP_TAGGED_KEYS for (k = 0, key = point->keys; k < point->totkey; k++, key++) if (key->flag & PEK_TAG) +#define KEY_K \ + PTCacheEditKey *key; \ + int k +#define POINT_P \ + PTCacheEditPoint *point; \ + int p +#define LOOP_POINTS for (p = 0, point = edit->points; p < edit->totpoint; p++, point++) +#define LOOP_VISIBLE_POINTS \ + for (p = 0, point = edit->points; p < edit->totpoint; p++, point++) \ + if (!(point->flag & PEP_HIDE)) +#define LOOP_SELECTED_POINTS \ + for (p = 0, point = edit->points; p < edit->totpoint; p++, point++) \ + if (point_is_selected(point)) +#define LOOP_UNSELECTED_POINTS \ + for (p = 0, point = edit->points; p < edit->totpoint; p++, point++) \ + if (!point_is_selected(point)) +#define LOOP_EDITED_POINTS \ + for (p = 0, point = edit->points; p < edit->totpoint; p++, point++) \ + if (point->flag & PEP_EDIT_RECALC) +#define LOOP_TAGGED_POINTS \ + for (p = 0, point = edit->points; p < edit->totpoint; p++, point++) \ + if (point->flag & PEP_TAG) +#define LOOP_KEYS for (k = 0, key = point->keys; k < point->totkey; k++, key++) +#define LOOP_VISIBLE_KEYS \ + for (k = 0, key = point->keys; k < point->totkey; k++, key++) \ + if (!(key->flag & PEK_HIDE)) +#define LOOP_SELECTED_KEYS \ + for (k = 0, key = point->keys; k < point->totkey; k++, key++) \ + if ((key->flag & PEK_SELECT) && !(key->flag & PEK_HIDE)) +#define LOOP_TAGGED_KEYS \ + for (k = 0, key = point->keys; k < point->totkey; k++, key++) \ + if (key->flag & PEK_TAG) -#define KEY_WCO ((key->flag & PEK_USE_WCO) ? key->world_co : key->co) +#define KEY_WCO ((key->flag & PEK_USE_WCO) ? key->world_co : key->co) -#endif /* __PARTICLE_EDIT_UTILDEFNIES_H__ */ +#endif /* __PARTICLE_EDIT_UTILDEFNIES_H__ */ diff --git a/source/blender/editors/physics/particle_object.c b/source/blender/editors/physics/particle_object.c index 2287659ef03..92eed9be2f5 100644 --- a/source/blender/editors/physics/particle_object.c +++ b/source/blender/editors/physics/particle_object.c @@ -21,7 +21,6 @@ * \ingroup edphys */ - #include #include @@ -70,956 +69,971 @@ #include "physics_intern.h" -static float I[4][4] = {{1.0f, 0.0f, 0.0f, 0.0f}, {0.0f, 1.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 1.0f, 0.0f}, {0.0f, 0.0f, 0.0f, 1.0f}}; +static float I[4][4] = {{1.0f, 0.0f, 0.0f, 0.0f}, + {0.0f, 1.0f, 0.0f, 0.0f}, + {0.0f, 0.0f, 1.0f, 0.0f}, + {0.0f, 0.0f, 0.0f, 1.0f}}; /********************** particle system slot operators *********************/ static int particle_system_add_exec(bContext *C, wmOperator *UNUSED(op)) { - Main *bmain = CTX_data_main(C); - Object *ob = ED_object_context(C); - Scene *scene = CTX_data_scene(C); + Main *bmain = CTX_data_main(C); + Object *ob = ED_object_context(C); + Scene *scene = CTX_data_scene(C); - if (!scene || !ob) - return OPERATOR_CANCELLED; + if (!scene || !ob) + return OPERATOR_CANCELLED; - object_add_particle_system(bmain, scene, ob, NULL); + object_add_particle_system(bmain, scene, ob, NULL); - WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE, ob); - WM_event_add_notifier(C, NC_OBJECT | ND_POINTCACHE, ob); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE, ob); + WM_event_add_notifier(C, NC_OBJECT | ND_POINTCACHE, ob); - return OPERATOR_FINISHED; + return OPERATOR_FINISHED; } void OBJECT_OT_particle_system_add(wmOperatorType *ot) { - /* identifiers */ - ot->name = "Add Particle System Slot"; - ot->idname = "OBJECT_OT_particle_system_add"; - ot->description = "Add a particle system"; + /* identifiers */ + ot->name = "Add Particle System Slot"; + ot->idname = "OBJECT_OT_particle_system_add"; + ot->description = "Add a particle system"; - /* api callbacks */ - ot->poll = ED_operator_object_active_editable; - ot->exec = particle_system_add_exec; + /* api callbacks */ + ot->poll = ED_operator_object_active_editable; + ot->exec = particle_system_add_exec; - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } static int particle_system_remove_exec(bContext *C, wmOperator *UNUSED(op)) { - Main *bmain = CTX_data_main(C); - Object *ob = ED_object_context(C); - Scene *scene = CTX_data_scene(C); - ViewLayer *view_layer = CTX_data_view_layer(C); - int mode_orig; - - if (!scene || !ob) - return OPERATOR_CANCELLED; - - mode_orig = ob->mode; - object_remove_particle_system(bmain, scene, ob); - - /* possible this isn't the active object - * object_remove_particle_system() clears the mode on the last psys - */ - if (mode_orig & OB_MODE_PARTICLE_EDIT) { - if ((ob->mode & OB_MODE_PARTICLE_EDIT) == 0) { - if (view_layer->basact && view_layer->basact->object == ob) { - WM_event_add_notifier(C, NC_SCENE | ND_MODE | NS_MODE_OBJECT, NULL); - } - } - } - - WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE, ob); - WM_event_add_notifier(C, NC_OBJECT | ND_POINTCACHE, ob); - - return OPERATOR_FINISHED; + Main *bmain = CTX_data_main(C); + Object *ob = ED_object_context(C); + Scene *scene = CTX_data_scene(C); + ViewLayer *view_layer = CTX_data_view_layer(C); + int mode_orig; + + if (!scene || !ob) + return OPERATOR_CANCELLED; + + mode_orig = ob->mode; + object_remove_particle_system(bmain, scene, ob); + + /* possible this isn't the active object + * object_remove_particle_system() clears the mode on the last psys + */ + if (mode_orig & OB_MODE_PARTICLE_EDIT) { + if ((ob->mode & OB_MODE_PARTICLE_EDIT) == 0) { + if (view_layer->basact && view_layer->basact->object == ob) { + WM_event_add_notifier(C, NC_SCENE | ND_MODE | NS_MODE_OBJECT, NULL); + } + } + } + + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE, ob); + WM_event_add_notifier(C, NC_OBJECT | ND_POINTCACHE, ob); + + return OPERATOR_FINISHED; } void OBJECT_OT_particle_system_remove(wmOperatorType *ot) { - /* identifiers */ - ot->name = "Remove Particle System Slot"; - ot->idname = "OBJECT_OT_particle_system_remove"; - ot->description = "Remove the selected particle system"; + /* identifiers */ + ot->name = "Remove Particle System Slot"; + ot->idname = "OBJECT_OT_particle_system_remove"; + ot->description = "Remove the selected particle system"; - /* api callbacks */ - ot->poll = ED_operator_object_active_editable; - ot->exec = particle_system_remove_exec; + /* api callbacks */ + ot->poll = ED_operator_object_active_editable; + ot->exec = particle_system_remove_exec; - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } /********************** new particle settings operator *********************/ static bool psys_poll(bContext *C) { - PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem); - return (ptr.data != NULL); + PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem); + return (ptr.data != NULL); } static int new_particle_settings_exec(bContext *C, wmOperator *UNUSED(op)) { - Main *bmain = CTX_data_main(C); - ParticleSystem *psys; - ParticleSettings *part = NULL; - Object *ob; - PointerRNA ptr; + Main *bmain = CTX_data_main(C); + ParticleSystem *psys; + ParticleSettings *part = NULL; + Object *ob; + PointerRNA ptr; - ptr = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem); + ptr = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem); - psys = ptr.data; + psys = ptr.data; - /* add or copy particle setting */ - if (psys->part) - part = BKE_particlesettings_copy(bmain, psys->part); - else - part = BKE_particlesettings_add(bmain, "ParticleSettings"); + /* add or copy particle setting */ + if (psys->part) + part = BKE_particlesettings_copy(bmain, psys->part); + else + part = BKE_particlesettings_add(bmain, "ParticleSettings"); - ob = ptr.id.data; + ob = ptr.id.data; - if (psys->part) - id_us_min(&psys->part->id); + if (psys->part) + id_us_min(&psys->part->id); - psys->part = part; + psys->part = part; - psys_check_boid_data(psys); + psys_check_boid_data(psys); - DEG_relations_tag_update(bmain); - DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY); + DEG_relations_tag_update(bmain); + DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY); - WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE, ob); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE, ob); - return OPERATOR_FINISHED; + return OPERATOR_FINISHED; } void PARTICLE_OT_new(wmOperatorType *ot) { - /* identifiers */ - ot->name = "New Particle Settings"; - ot->idname = "PARTICLE_OT_new"; - ot->description = "Add new particle settings"; + /* identifiers */ + ot->name = "New Particle Settings"; + ot->idname = "PARTICLE_OT_new"; + ot->description = "Add new particle settings"; - /* api callbacks */ - ot->exec = new_particle_settings_exec; - ot->poll = psys_poll; + /* api callbacks */ + ot->exec = new_particle_settings_exec; + ot->poll = psys_poll; - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } /********************** keyed particle target operators *********************/ static int new_particle_target_exec(bContext *C, wmOperator *UNUSED(op)) { - Main *bmain = CTX_data_main(C); - PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem); - ParticleSystem *psys = ptr.data; - Object *ob = ptr.id.data; + Main *bmain = CTX_data_main(C); + PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem); + ParticleSystem *psys = ptr.data; + Object *ob = ptr.id.data; - ParticleTarget *pt; + ParticleTarget *pt; - if (!psys) - return OPERATOR_CANCELLED; + if (!psys) + return OPERATOR_CANCELLED; - pt = psys->targets.first; - for (; pt; pt = pt->next) - pt->flag &= ~PTARGET_CURRENT; + pt = psys->targets.first; + for (; pt; pt = pt->next) + pt->flag &= ~PTARGET_CURRENT; - pt = MEM_callocN(sizeof(ParticleTarget), "keyed particle target"); + pt = MEM_callocN(sizeof(ParticleTarget), "keyed particle target"); - pt->flag |= PTARGET_CURRENT; - pt->psys = 1; + pt->flag |= PTARGET_CURRENT; + pt->psys = 1; - BLI_addtail(&psys->targets, pt); + BLI_addtail(&psys->targets, pt); - DEG_relations_tag_update(bmain); - DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY); + DEG_relations_tag_update(bmain); + DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY); - WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE, ob); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE, ob); - return OPERATOR_FINISHED; + return OPERATOR_FINISHED; } void PARTICLE_OT_new_target(wmOperatorType *ot) { - /* identifiers */ - ot->name = "New Particle Target"; - ot->idname = "PARTICLE_OT_new_target"; - ot->description = "Add a new particle target"; + /* identifiers */ + ot->name = "New Particle Target"; + ot->idname = "PARTICLE_OT_new_target"; + ot->description = "Add a new particle target"; - /* api callbacks */ - ot->exec = new_particle_target_exec; + /* api callbacks */ + ot->exec = new_particle_target_exec; - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } static int remove_particle_target_exec(bContext *C, wmOperator *UNUSED(op)) { - Main *bmain = CTX_data_main(C); - PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem); - ParticleSystem *psys = ptr.data; - Object *ob = ptr.id.data; - - ParticleTarget *pt; + Main *bmain = CTX_data_main(C); + PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem); + ParticleSystem *psys = ptr.data; + Object *ob = ptr.id.data; - if (!psys) - return OPERATOR_CANCELLED; + ParticleTarget *pt; - pt = psys->targets.first; - for (; pt; pt = pt->next) { - if (pt->flag & PTARGET_CURRENT) { - BLI_remlink(&psys->targets, pt); - MEM_freeN(pt); - break; - } + if (!psys) + return OPERATOR_CANCELLED; - } - pt = psys->targets.last; + pt = psys->targets.first; + for (; pt; pt = pt->next) { + if (pt->flag & PTARGET_CURRENT) { + BLI_remlink(&psys->targets, pt); + MEM_freeN(pt); + break; + } + } + pt = psys->targets.last; - if (pt) - pt->flag |= PTARGET_CURRENT; + if (pt) + pt->flag |= PTARGET_CURRENT; - DEG_relations_tag_update(bmain); - DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY); + DEG_relations_tag_update(bmain); + DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY); - WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE, ob); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE, ob); - return OPERATOR_FINISHED; + return OPERATOR_FINISHED; } void PARTICLE_OT_target_remove(wmOperatorType *ot) { - /* identifiers */ - ot->name = "Remove Particle Target"; - ot->idname = "PARTICLE_OT_target_remove"; - ot->description = "Remove the selected particle target"; + /* identifiers */ + ot->name = "Remove Particle Target"; + ot->idname = "PARTICLE_OT_target_remove"; + ot->description = "Remove the selected particle target"; - /* api callbacks */ - ot->exec = remove_particle_target_exec; + /* api callbacks */ + ot->exec = remove_particle_target_exec; - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } /************************ move up particle target operator *********************/ static int target_move_up_exec(bContext *C, wmOperator *UNUSED(op)) { - PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem); - ParticleSystem *psys = ptr.data; - Object *ob = ptr.id.data; - ParticleTarget *pt; - - if (!psys) - return OPERATOR_CANCELLED; - - pt = psys->targets.first; - for (; pt; pt = pt->next) { - if (pt->flag & PTARGET_CURRENT && pt->prev) { - BLI_remlink(&psys->targets, pt); - BLI_insertlinkbefore(&psys->targets, pt->prev, pt); - - DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY); - WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE, ob); - break; - } - } - - return OPERATOR_FINISHED; + PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem); + ParticleSystem *psys = ptr.data; + Object *ob = ptr.id.data; + ParticleTarget *pt; + + if (!psys) + return OPERATOR_CANCELLED; + + pt = psys->targets.first; + for (; pt; pt = pt->next) { + if (pt->flag & PTARGET_CURRENT && pt->prev) { + BLI_remlink(&psys->targets, pt); + BLI_insertlinkbefore(&psys->targets, pt->prev, pt); + + DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE, ob); + break; + } + } + + return OPERATOR_FINISHED; } void PARTICLE_OT_target_move_up(wmOperatorType *ot) { - ot->name = "Move Up Target"; - ot->idname = "PARTICLE_OT_target_move_up"; - ot->description = "Move particle target up in the list"; + ot->name = "Move Up Target"; + ot->idname = "PARTICLE_OT_target_move_up"; + ot->description = "Move particle target up in the list"; - ot->exec = target_move_up_exec; + ot->exec = target_move_up_exec; - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } /************************ move down particle target operator *********************/ static int target_move_down_exec(bContext *C, wmOperator *UNUSED(op)) { - PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem); - ParticleSystem *psys = ptr.data; - Object *ob = ptr.id.data; - ParticleTarget *pt; - - if (!psys) - return OPERATOR_CANCELLED; - pt = psys->targets.first; - for (; pt; pt = pt->next) { - if (pt->flag & PTARGET_CURRENT && pt->next) { - BLI_remlink(&psys->targets, pt); - BLI_insertlinkafter(&psys->targets, pt->next, pt); - - DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY); - WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE, ob); - break; - } - } - - return OPERATOR_FINISHED; + PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem); + ParticleSystem *psys = ptr.data; + Object *ob = ptr.id.data; + ParticleTarget *pt; + + if (!psys) + return OPERATOR_CANCELLED; + pt = psys->targets.first; + for (; pt; pt = pt->next) { + if (pt->flag & PTARGET_CURRENT && pt->next) { + BLI_remlink(&psys->targets, pt); + BLI_insertlinkafter(&psys->targets, pt->next, pt); + + DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE, ob); + break; + } + } + + return OPERATOR_FINISHED; } void PARTICLE_OT_target_move_down(wmOperatorType *ot) { - ot->name = "Move Down Target"; - ot->idname = "PARTICLE_OT_target_move_down"; - ot->description = "Move particle target down in the list"; + ot->name = "Move Down Target"; + ot->idname = "PARTICLE_OT_target_move_down"; + ot->description = "Move particle target down in the list"; - ot->exec = target_move_down_exec; + ot->exec = target_move_down_exec; - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } /************************ refresh dupli objects *********************/ static int dupliob_refresh_exec(bContext *C, wmOperator *UNUSED(op)) { - PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem); - ParticleSystem *psys = ptr.data; + PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem); + ParticleSystem *psys = ptr.data; - if (!psys) - return OPERATOR_CANCELLED; + if (!psys) + return OPERATOR_CANCELLED; - psys_check_group_weights(psys->part); - DEG_id_tag_update(&psys->part->id, ID_RECALC_GEOMETRY | ID_RECALC_PSYS_REDO); - WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE, NULL); + psys_check_group_weights(psys->part); + DEG_id_tag_update(&psys->part->id, ID_RECALC_GEOMETRY | ID_RECALC_PSYS_REDO); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE, NULL); - return OPERATOR_FINISHED; + return OPERATOR_FINISHED; } void PARTICLE_OT_dupliob_refresh(wmOperatorType *ot) { - ot->name = "Refresh Dupli Objects"; - ot->idname = "PARTICLE_OT_dupliob_refresh"; - ot->description = "Refresh list of dupli objects and their weights"; + ot->name = "Refresh Dupli Objects"; + ot->idname = "PARTICLE_OT_dupliob_refresh"; + ot->description = "Refresh list of dupli objects and their weights"; - ot->exec = dupliob_refresh_exec; + ot->exec = dupliob_refresh_exec; - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } /************************ move up particle dupliweight operator *********************/ static int dupliob_move_up_exec(bContext *C, wmOperator *UNUSED(op)) { - PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem); - ParticleSystem *psys = ptr.data; - ParticleSettings *part; - ParticleDupliWeight *dw; - - if (!psys) - return OPERATOR_CANCELLED; - - part = psys->part; - for (dw = part->instance_weights.first; dw; dw = dw->next) { - if (dw->flag & PART_DUPLIW_CURRENT && dw->prev) { - BLI_remlink(&part->instance_weights, dw); - BLI_insertlinkbefore(&part->instance_weights, dw->prev, dw); - - DEG_id_tag_update(&part->id, ID_RECALC_GEOMETRY | ID_RECALC_PSYS_REDO); - WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE, NULL); - break; - } - } - - return OPERATOR_FINISHED; + PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem); + ParticleSystem *psys = ptr.data; + ParticleSettings *part; + ParticleDupliWeight *dw; + + if (!psys) + return OPERATOR_CANCELLED; + + part = psys->part; + for (dw = part->instance_weights.first; dw; dw = dw->next) { + if (dw->flag & PART_DUPLIW_CURRENT && dw->prev) { + BLI_remlink(&part->instance_weights, dw); + BLI_insertlinkbefore(&part->instance_weights, dw->prev, dw); + + DEG_id_tag_update(&part->id, ID_RECALC_GEOMETRY | ID_RECALC_PSYS_REDO); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE, NULL); + break; + } + } + + return OPERATOR_FINISHED; } void PARTICLE_OT_dupliob_move_up(wmOperatorType *ot) { - ot->name = "Move Up Dupli Object"; - ot->idname = "PARTICLE_OT_dupliob_move_up"; - ot->description = "Move dupli object up in the list"; + ot->name = "Move Up Dupli Object"; + ot->idname = "PARTICLE_OT_dupliob_move_up"; + ot->description = "Move dupli object up in the list"; - ot->exec = dupliob_move_up_exec; + ot->exec = dupliob_move_up_exec; - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } /********************** particle dupliweight operators *********************/ static int copy_particle_dupliob_exec(bContext *C, wmOperator *UNUSED(op)) { - PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem); - ParticleSystem *psys = ptr.data; - ParticleSettings *part; - ParticleDupliWeight *dw; - - if (!psys) - return OPERATOR_CANCELLED; - part = psys->part; - for (dw = part->instance_weights.first; dw; dw = dw->next) { - if (dw->flag & PART_DUPLIW_CURRENT) { - dw->flag &= ~PART_DUPLIW_CURRENT; - dw = MEM_dupallocN(dw); - dw->flag |= PART_DUPLIW_CURRENT; - BLI_addhead(&part->instance_weights, dw); - - DEG_id_tag_update(&part->id, ID_RECALC_GEOMETRY | ID_RECALC_PSYS_REDO); - WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE, NULL); - break; - } - } - - return OPERATOR_FINISHED; + PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem); + ParticleSystem *psys = ptr.data; + ParticleSettings *part; + ParticleDupliWeight *dw; + + if (!psys) + return OPERATOR_CANCELLED; + part = psys->part; + for (dw = part->instance_weights.first; dw; dw = dw->next) { + if (dw->flag & PART_DUPLIW_CURRENT) { + dw->flag &= ~PART_DUPLIW_CURRENT; + dw = MEM_dupallocN(dw); + dw->flag |= PART_DUPLIW_CURRENT; + BLI_addhead(&part->instance_weights, dw); + + DEG_id_tag_update(&part->id, ID_RECALC_GEOMETRY | ID_RECALC_PSYS_REDO); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE, NULL); + break; + } + } + + return OPERATOR_FINISHED; } void PARTICLE_OT_dupliob_copy(wmOperatorType *ot) { - /* identifiers */ - ot->name = "Copy Particle Dupliob"; - ot->idname = "PARTICLE_OT_dupliob_copy"; - ot->description = "Duplicate the current dupliobject"; + /* identifiers */ + ot->name = "Copy Particle Dupliob"; + ot->idname = "PARTICLE_OT_dupliob_copy"; + ot->description = "Duplicate the current dupliobject"; - /* api callbacks */ - ot->exec = copy_particle_dupliob_exec; + /* api callbacks */ + ot->exec = copy_particle_dupliob_exec; - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } static int remove_particle_dupliob_exec(bContext *C, wmOperator *UNUSED(op)) { - PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem); - ParticleSystem *psys = ptr.data; - ParticleSettings *part; - ParticleDupliWeight *dw; - - if (!psys) - return OPERATOR_CANCELLED; - - part = psys->part; - for (dw = part->instance_weights.first; dw; dw = dw->next) { - if (dw->flag & PART_DUPLIW_CURRENT) { - BLI_remlink(&part->instance_weights, dw); - MEM_freeN(dw); - break; - } - - } - dw = part->instance_weights.last; - - if (dw) - dw->flag |= PART_DUPLIW_CURRENT; - - DEG_id_tag_update(&part->id, ID_RECALC_GEOMETRY | ID_RECALC_PSYS_REDO); - WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE, NULL); - - return OPERATOR_FINISHED; + PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem); + ParticleSystem *psys = ptr.data; + ParticleSettings *part; + ParticleDupliWeight *dw; + + if (!psys) + return OPERATOR_CANCELLED; + + part = psys->part; + for (dw = part->instance_weights.first; dw; dw = dw->next) { + if (dw->flag & PART_DUPLIW_CURRENT) { + BLI_remlink(&part->instance_weights, dw); + MEM_freeN(dw); + break; + } + } + dw = part->instance_weights.last; + + if (dw) + dw->flag |= PART_DUPLIW_CURRENT; + + DEG_id_tag_update(&part->id, ID_RECALC_GEOMETRY | ID_RECALC_PSYS_REDO); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE, NULL); + + return OPERATOR_FINISHED; } void PARTICLE_OT_dupliob_remove(wmOperatorType *ot) { - /* identifiers */ - ot->name = "Remove Particle Dupliobject"; - ot->idname = "PARTICLE_OT_dupliob_remove"; - ot->description = "Remove the selected dupliobject"; + /* identifiers */ + ot->name = "Remove Particle Dupliobject"; + ot->idname = "PARTICLE_OT_dupliob_remove"; + ot->description = "Remove the selected dupliobject"; - /* api callbacks */ - ot->exec = remove_particle_dupliob_exec; + /* api callbacks */ + ot->exec = remove_particle_dupliob_exec; - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } /************************ move down particle dupliweight operator *********************/ static int dupliob_move_down_exec(bContext *C, wmOperator *UNUSED(op)) { - PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem); - ParticleSystem *psys = ptr.data; - ParticleSettings *part; - ParticleDupliWeight *dw; - - if (!psys) - return OPERATOR_CANCELLED; - - part = psys->part; - for (dw = part->instance_weights.first; dw; dw = dw->next) { - if (dw->flag & PART_DUPLIW_CURRENT && dw->next) { - BLI_remlink(&part->instance_weights, dw); - BLI_insertlinkafter(&part->instance_weights, dw->next, dw); - - DEG_id_tag_update(&part->id, ID_RECALC_GEOMETRY | ID_RECALC_PSYS_REDO); - WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE, NULL); - break; - } - } - - return OPERATOR_FINISHED; + PointerRNA ptr = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem); + ParticleSystem *psys = ptr.data; + ParticleSettings *part; + ParticleDupliWeight *dw; + + if (!psys) + return OPERATOR_CANCELLED; + + part = psys->part; + for (dw = part->instance_weights.first; dw; dw = dw->next) { + if (dw->flag & PART_DUPLIW_CURRENT && dw->next) { + BLI_remlink(&part->instance_weights, dw); + BLI_insertlinkafter(&part->instance_weights, dw->next, dw); + + DEG_id_tag_update(&part->id, ID_RECALC_GEOMETRY | ID_RECALC_PSYS_REDO); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE, NULL); + break; + } + } + + return OPERATOR_FINISHED; } void PARTICLE_OT_dupliob_move_down(wmOperatorType *ot) { - ot->name = "Move Down Dupli Object"; - ot->idname = "PARTICLE_OT_dupliob_move_down"; - ot->description = "Move dupli object down in the list"; + ot->name = "Move Down Dupli Object"; + ot->idname = "PARTICLE_OT_dupliob_move_down"; + ot->description = "Move dupli object down in the list"; - ot->exec = dupliob_move_down_exec; + ot->exec = dupliob_move_down_exec; - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } /************************ connect/disconnect hair operators *********************/ -static void disconnect_hair( - Depsgraph *depsgraph, Scene *scene, - Object *ob, ParticleSystem *psys) +static void disconnect_hair(Depsgraph *depsgraph, Scene *scene, Object *ob, ParticleSystem *psys) { - Object *object_eval = DEG_get_evaluated_object(depsgraph, ob); - ParticleSystem *psys_eval = psys_eval_get(depsgraph, ob, psys); - ParticleSystemModifierData *psmd_eval = - psys_get_modifier(object_eval, psys_eval); - ParticleEditSettings *pset = PE_settings(scene); - ParticleData *pa; - PTCacheEdit *edit; - PTCacheEditPoint *point; - PTCacheEditKey *ekey = NULL; - HairKey *key; - int i, k; - float hairmat[4][4]; - - if (!ob || !psys || psys->flag & PSYS_GLOBAL_HAIR) - return; - - if (!psys->part || psys->part->type != PART_HAIR) - return; - - edit = psys->edit; - point = edit ? edit->points : NULL; - - for (i = 0, pa = psys->particles; i < psys->totpart; i++, pa++) { - if (point) { - ekey = point->keys; - point++; - } - - psys_mat_hair_to_global( - ob, psmd_eval->mesh_final, psys->part->from, pa, hairmat); - - for (k = 0, key = pa->hair; k < pa->totkey; k++, key++) { - mul_m4_v3(hairmat, key->co); - - if (ekey) { - ekey->flag &= ~PEK_USE_WCO; - ekey++; - } - } - } - - psys_free_path_cache(psys, psys->edit); - - psys->flag |= PSYS_GLOBAL_HAIR; - - if (ELEM(pset->brushtype, PE_BRUSH_ADD, PE_BRUSH_PUFF)) { - pset->brushtype = PE_BRUSH_COMB; - } - - PE_update_object(depsgraph, scene, ob, 0); + Object *object_eval = DEG_get_evaluated_object(depsgraph, ob); + ParticleSystem *psys_eval = psys_eval_get(depsgraph, ob, psys); + ParticleSystemModifierData *psmd_eval = psys_get_modifier(object_eval, psys_eval); + ParticleEditSettings *pset = PE_settings(scene); + ParticleData *pa; + PTCacheEdit *edit; + PTCacheEditPoint *point; + PTCacheEditKey *ekey = NULL; + HairKey *key; + int i, k; + float hairmat[4][4]; + + if (!ob || !psys || psys->flag & PSYS_GLOBAL_HAIR) + return; + + if (!psys->part || psys->part->type != PART_HAIR) + return; + + edit = psys->edit; + point = edit ? edit->points : NULL; + + for (i = 0, pa = psys->particles; i < psys->totpart; i++, pa++) { + if (point) { + ekey = point->keys; + point++; + } + + psys_mat_hair_to_global(ob, psmd_eval->mesh_final, psys->part->from, pa, hairmat); + + for (k = 0, key = pa->hair; k < pa->totkey; k++, key++) { + mul_m4_v3(hairmat, key->co); + + if (ekey) { + ekey->flag &= ~PEK_USE_WCO; + ekey++; + } + } + } + + psys_free_path_cache(psys, psys->edit); + + psys->flag |= PSYS_GLOBAL_HAIR; + + if (ELEM(pset->brushtype, PE_BRUSH_ADD, PE_BRUSH_PUFF)) { + pset->brushtype = PE_BRUSH_COMB; + } + + PE_update_object(depsgraph, scene, ob, 0); } static int disconnect_hair_exec(bContext *C, wmOperator *op) { - Depsgraph *depsgraph = CTX_data_depsgraph(C); - Scene *scene = CTX_data_scene(C); - Object *ob = ED_object_context(C); - ParticleSystem *psys = NULL; - const bool all = RNA_boolean_get(op->ptr, "all"); - - if (!ob) - return OPERATOR_CANCELLED; - - if (all) { - for (psys = ob->particlesystem.first; psys; psys = psys->next) { - disconnect_hair(depsgraph, scene, ob, psys); - } - } - else { - psys = psys_get_current(ob); - disconnect_hair(depsgraph, scene, ob, psys); - } - - DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY); - WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE, ob); - - return OPERATOR_FINISHED; + Depsgraph *depsgraph = CTX_data_depsgraph(C); + Scene *scene = CTX_data_scene(C); + Object *ob = ED_object_context(C); + ParticleSystem *psys = NULL; + const bool all = RNA_boolean_get(op->ptr, "all"); + + if (!ob) + return OPERATOR_CANCELLED; + + if (all) { + for (psys = ob->particlesystem.first; psys; psys = psys->next) { + disconnect_hair(depsgraph, scene, ob, psys); + } + } + else { + psys = psys_get_current(ob); + disconnect_hair(depsgraph, scene, ob, psys); + } + + DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE, ob); + + return OPERATOR_FINISHED; } void PARTICLE_OT_disconnect_hair(wmOperatorType *ot) { - ot->name = "Disconnect Hair"; - ot->description = "Disconnect hair from the emitter mesh"; - ot->idname = "PARTICLE_OT_disconnect_hair"; + ot->name = "Disconnect Hair"; + ot->description = "Disconnect hair from the emitter mesh"; + ot->idname = "PARTICLE_OT_disconnect_hair"; - ot->exec = disconnect_hair_exec; + ot->exec = disconnect_hair_exec; - /* flags */ - /* No REGISTER, redo does not work due to missing update, see T47750. */ - ot->flag = OPTYPE_UNDO; + /* flags */ + /* No REGISTER, redo does not work due to missing update, see T47750. */ + ot->flag = OPTYPE_UNDO; - RNA_def_boolean(ot->srna, "all", 0, "All hair", "Disconnect all hair systems from the emitter mesh"); + RNA_def_boolean( + ot->srna, "all", 0, "All hair", "Disconnect all hair systems from the emitter mesh"); } /* from/to_world_space : whether from/to particles are in world or hair space * from/to_mat : additional transform for from/to particles (e.g. for using object space copying) */ -static bool remap_hair_emitter( - Depsgraph *depsgraph, Scene *scene, Object *ob, ParticleSystem *psys, - Object *target_ob, ParticleSystem *target_psys, PTCacheEdit *target_edit, - float from_mat[4][4], float to_mat[4][4], bool from_global, bool to_global) +static bool remap_hair_emitter(Depsgraph *depsgraph, + Scene *scene, + Object *ob, + ParticleSystem *psys, + Object *target_ob, + ParticleSystem *target_psys, + PTCacheEdit *target_edit, + float from_mat[4][4], + float to_mat[4][4], + bool from_global, + bool to_global) { - Object *object_eval = DEG_get_evaluated_object(depsgraph, ob); - ParticleSystem *psys_eval = psys_eval_get(depsgraph, ob, psys); - ParticleSystemModifierData *target_psmd = - psys_get_modifier(object_eval, psys_eval); - ParticleData *pa, *tpa; - PTCacheEditPoint *edit_point; - PTCacheEditKey *ekey; - BVHTreeFromMesh bvhtree = {NULL}; - MFace *mface = NULL, *mf; - MEdge *medge = NULL, *me; - MVert *mvert; - Mesh *mesh, *target_mesh; - int numverts; - int i, k; - float from_ob_imat[4][4], to_ob_imat[4][4]; - float from_imat[4][4], to_imat[4][4]; - - if (!target_psmd->mesh_final) - return false; - if (!psys->part || psys->part->type != PART_HAIR) - return false; - if (!target_psys->part || target_psys->part->type != PART_HAIR) - return false; - - edit_point = target_edit ? target_edit->points : NULL; - - invert_m4_m4(from_ob_imat, ob->obmat); - invert_m4_m4(to_ob_imat, target_ob->obmat); - invert_m4_m4(from_imat, from_mat); - invert_m4_m4(to_imat, to_mat); - - if (target_psmd->mesh_final->runtime.deformed_only) { - /* we don't want to mess up target_psmd->dm when converting to global coordinates below */ - mesh = target_psmd->mesh_final; - } - else { - mesh = target_psmd->mesh_original; - } - target_mesh = target_psmd->mesh_final; - if (mesh == NULL) { - return false; - } - /* don't modify the original vertices */ - BKE_id_copy_ex(NULL, &mesh->id, (ID **)&mesh, LIB_ID_COPY_LOCALIZE); - - /* BMESH_ONLY, deform dm may not have tessface */ - BKE_mesh_tessface_ensure(mesh); - - numverts = mesh->totvert; - mvert = mesh->mvert; - - /* convert to global coordinates */ - for (i = 0; i < numverts; i++) - mul_m4_v3(to_mat, mvert[i].co); - - if (mesh->totface != 0) { - mface = mesh->mface; - BKE_bvhtree_from_mesh_get(&bvhtree, mesh, BVHTREE_FROM_FACES, 2); - } - else if (mesh->totedge != 0) { - medge = mesh->medge; - BKE_bvhtree_from_mesh_get(&bvhtree, mesh, BVHTREE_FROM_EDGES, 2); - } - else { - BKE_id_free(NULL, mesh); - return false; - } - - for (i = 0, tpa = target_psys->particles, pa = psys->particles; - i < target_psys->totpart; - i++, tpa++, pa++) - { - float from_co[3]; - BVHTreeNearest nearest; - - if (from_global) - mul_v3_m4v3(from_co, from_ob_imat, pa->hair[0].co); - else - mul_v3_m4v3(from_co, from_ob_imat, pa->hair[0].world_co); - mul_m4_v3(from_mat, from_co); - - nearest.index = -1; - nearest.dist_sq = FLT_MAX; - - BLI_bvhtree_find_nearest(bvhtree.tree, from_co, &nearest, bvhtree.nearest_callback, &bvhtree); - - if (nearest.index == -1) { - if (G.debug & G_DEBUG) - printf("No nearest point found for hair root!"); - continue; - } - - if (mface) { - float v[4][3]; - - mf = &mface[nearest.index]; - - copy_v3_v3(v[0], mvert[mf->v1].co); - copy_v3_v3(v[1], mvert[mf->v2].co); - copy_v3_v3(v[2], mvert[mf->v3].co); - if (mf->v4) { - copy_v3_v3(v[3], mvert[mf->v4].co); - interp_weights_poly_v3(tpa->fuv, v, 4, nearest.co); - } - else - interp_weights_poly_v3(tpa->fuv, v, 3, nearest.co); - tpa->foffset = 0.0f; - - tpa->num = nearest.index; - tpa->num_dmcache = psys_particle_dm_face_lookup(target_mesh, mesh, tpa->num, tpa->fuv, NULL); - } - else { - me = &medge[nearest.index]; - - tpa->fuv[1] = line_point_factor_v3(nearest.co, - mvert[me->v1].co, - mvert[me->v2].co); - tpa->fuv[0] = 1.0f - tpa->fuv[1]; - tpa->fuv[2] = tpa->fuv[3] = 0.0f; - tpa->foffset = 0.0f; - - tpa->num = nearest.index; - tpa->num_dmcache = -1; - } - - /* translate hair keys */ - { - HairKey *key, *tkey; - float hairmat[4][4], imat[4][4]; - float offset[3]; - - if (to_global) - copy_m4_m4(imat, target_ob->obmat); - else { - /* note: using target_dm here, which is in target_ob object space and has full modifiers */ - psys_mat_hair_to_object(target_ob, target_mesh, target_psys->part->from, tpa, hairmat); - invert_m4_m4(imat, hairmat); - } - mul_m4_m4m4(imat, imat, to_imat); - - /* offset in world space */ - sub_v3_v3v3(offset, nearest.co, from_co); - - if (edit_point) { - for (k = 0, key = pa->hair, tkey = tpa->hair, ekey = edit_point->keys; k < tpa->totkey; k++, key++, tkey++, ekey++) { - float co_orig[3]; - - if (from_global) - mul_v3_m4v3(co_orig, from_ob_imat, key->co); - else - mul_v3_m4v3(co_orig, from_ob_imat, key->world_co); - mul_m4_v3(from_mat, co_orig); - - add_v3_v3v3(tkey->co, co_orig, offset); - - mul_m4_v3(imat, tkey->co); - - ekey->flag |= PEK_USE_WCO; - } - - edit_point++; - } - else { - for (k = 0, key = pa->hair, tkey = tpa->hair; k < tpa->totkey; k++, key++, tkey++) { - float co_orig[3]; - - if (from_global) - mul_v3_m4v3(co_orig, from_ob_imat, key->co); - else - mul_v3_m4v3(co_orig, from_ob_imat, key->world_co); - mul_m4_v3(from_mat, co_orig); - - add_v3_v3v3(tkey->co, co_orig, offset); - - mul_m4_v3(imat, tkey->co); - } - } - } - } - - free_bvhtree_from_mesh(&bvhtree); - BKE_id_free(NULL, mesh); - - psys_free_path_cache(target_psys, target_edit); - - PE_update_object(depsgraph, scene, target_ob, 0); - - return true; + Object *object_eval = DEG_get_evaluated_object(depsgraph, ob); + ParticleSystem *psys_eval = psys_eval_get(depsgraph, ob, psys); + ParticleSystemModifierData *target_psmd = psys_get_modifier(object_eval, psys_eval); + ParticleData *pa, *tpa; + PTCacheEditPoint *edit_point; + PTCacheEditKey *ekey; + BVHTreeFromMesh bvhtree = {NULL}; + MFace *mface = NULL, *mf; + MEdge *medge = NULL, *me; + MVert *mvert; + Mesh *mesh, *target_mesh; + int numverts; + int i, k; + float from_ob_imat[4][4], to_ob_imat[4][4]; + float from_imat[4][4], to_imat[4][4]; + + if (!target_psmd->mesh_final) + return false; + if (!psys->part || psys->part->type != PART_HAIR) + return false; + if (!target_psys->part || target_psys->part->type != PART_HAIR) + return false; + + edit_point = target_edit ? target_edit->points : NULL; + + invert_m4_m4(from_ob_imat, ob->obmat); + invert_m4_m4(to_ob_imat, target_ob->obmat); + invert_m4_m4(from_imat, from_mat); + invert_m4_m4(to_imat, to_mat); + + if (target_psmd->mesh_final->runtime.deformed_only) { + /* we don't want to mess up target_psmd->dm when converting to global coordinates below */ + mesh = target_psmd->mesh_final; + } + else { + mesh = target_psmd->mesh_original; + } + target_mesh = target_psmd->mesh_final; + if (mesh == NULL) { + return false; + } + /* don't modify the original vertices */ + BKE_id_copy_ex(NULL, &mesh->id, (ID **)&mesh, LIB_ID_COPY_LOCALIZE); + + /* BMESH_ONLY, deform dm may not have tessface */ + BKE_mesh_tessface_ensure(mesh); + + numverts = mesh->totvert; + mvert = mesh->mvert; + + /* convert to global coordinates */ + for (i = 0; i < numverts; i++) + mul_m4_v3(to_mat, mvert[i].co); + + if (mesh->totface != 0) { + mface = mesh->mface; + BKE_bvhtree_from_mesh_get(&bvhtree, mesh, BVHTREE_FROM_FACES, 2); + } + else if (mesh->totedge != 0) { + medge = mesh->medge; + BKE_bvhtree_from_mesh_get(&bvhtree, mesh, BVHTREE_FROM_EDGES, 2); + } + else { + BKE_id_free(NULL, mesh); + return false; + } + + for (i = 0, tpa = target_psys->particles, pa = psys->particles; i < target_psys->totpart; + i++, tpa++, pa++) { + float from_co[3]; + BVHTreeNearest nearest; + + if (from_global) + mul_v3_m4v3(from_co, from_ob_imat, pa->hair[0].co); + else + mul_v3_m4v3(from_co, from_ob_imat, pa->hair[0].world_co); + mul_m4_v3(from_mat, from_co); + + nearest.index = -1; + nearest.dist_sq = FLT_MAX; + + BLI_bvhtree_find_nearest(bvhtree.tree, from_co, &nearest, bvhtree.nearest_callback, &bvhtree); + + if (nearest.index == -1) { + if (G.debug & G_DEBUG) + printf("No nearest point found for hair root!"); + continue; + } + + if (mface) { + float v[4][3]; + + mf = &mface[nearest.index]; + + copy_v3_v3(v[0], mvert[mf->v1].co); + copy_v3_v3(v[1], mvert[mf->v2].co); + copy_v3_v3(v[2], mvert[mf->v3].co); + if (mf->v4) { + copy_v3_v3(v[3], mvert[mf->v4].co); + interp_weights_poly_v3(tpa->fuv, v, 4, nearest.co); + } + else + interp_weights_poly_v3(tpa->fuv, v, 3, nearest.co); + tpa->foffset = 0.0f; + + tpa->num = nearest.index; + tpa->num_dmcache = psys_particle_dm_face_lookup(target_mesh, mesh, tpa->num, tpa->fuv, NULL); + } + else { + me = &medge[nearest.index]; + + tpa->fuv[1] = line_point_factor_v3(nearest.co, mvert[me->v1].co, mvert[me->v2].co); + tpa->fuv[0] = 1.0f - tpa->fuv[1]; + tpa->fuv[2] = tpa->fuv[3] = 0.0f; + tpa->foffset = 0.0f; + + tpa->num = nearest.index; + tpa->num_dmcache = -1; + } + + /* translate hair keys */ + { + HairKey *key, *tkey; + float hairmat[4][4], imat[4][4]; + float offset[3]; + + if (to_global) + copy_m4_m4(imat, target_ob->obmat); + else { + /* note: using target_dm here, which is in target_ob object space and has full modifiers */ + psys_mat_hair_to_object(target_ob, target_mesh, target_psys->part->from, tpa, hairmat); + invert_m4_m4(imat, hairmat); + } + mul_m4_m4m4(imat, imat, to_imat); + + /* offset in world space */ + sub_v3_v3v3(offset, nearest.co, from_co); + + if (edit_point) { + for (k = 0, key = pa->hair, tkey = tpa->hair, ekey = edit_point->keys; k < tpa->totkey; + k++, key++, tkey++, ekey++) { + float co_orig[3]; + + if (from_global) + mul_v3_m4v3(co_orig, from_ob_imat, key->co); + else + mul_v3_m4v3(co_orig, from_ob_imat, key->world_co); + mul_m4_v3(from_mat, co_orig); + + add_v3_v3v3(tkey->co, co_orig, offset); + + mul_m4_v3(imat, tkey->co); + + ekey->flag |= PEK_USE_WCO; + } + + edit_point++; + } + else { + for (k = 0, key = pa->hair, tkey = tpa->hair; k < tpa->totkey; k++, key++, tkey++) { + float co_orig[3]; + + if (from_global) + mul_v3_m4v3(co_orig, from_ob_imat, key->co); + else + mul_v3_m4v3(co_orig, from_ob_imat, key->world_co); + mul_m4_v3(from_mat, co_orig); + + add_v3_v3v3(tkey->co, co_orig, offset); + + mul_m4_v3(imat, tkey->co); + } + } + } + } + + free_bvhtree_from_mesh(&bvhtree); + BKE_id_free(NULL, mesh); + + psys_free_path_cache(target_psys, target_edit); + + PE_update_object(depsgraph, scene, target_ob, 0); + + return true; } -static bool connect_hair( - Depsgraph *depsgraph, Scene *scene, - Object *ob, ParticleSystem *psys) +static bool connect_hair(Depsgraph *depsgraph, Scene *scene, Object *ob, ParticleSystem *psys) { - bool ok; - - if (!psys) - return false; - - ok = remap_hair_emitter( - depsgraph, scene, ob, psys, ob, psys, psys->edit, - ob->obmat, ob->obmat, psys->flag & PSYS_GLOBAL_HAIR, false); - psys->flag &= ~PSYS_GLOBAL_HAIR; - - return ok; + bool ok; + + if (!psys) + return false; + + ok = remap_hair_emitter(depsgraph, + scene, + ob, + psys, + ob, + psys, + psys->edit, + ob->obmat, + ob->obmat, + psys->flag & PSYS_GLOBAL_HAIR, + false); + psys->flag &= ~PSYS_GLOBAL_HAIR; + + return ok; } static int connect_hair_exec(bContext *C, wmOperator *op) { - Depsgraph *depsgraph = CTX_data_depsgraph(C); - Scene *scene = CTX_data_scene(C); - Object *ob = ED_object_context(C); - ParticleSystem *psys = NULL; - const bool all = RNA_boolean_get(op->ptr, "all"); - bool any_connected = false; - - if (!ob) - return OPERATOR_CANCELLED; - - if (all) { - for (psys = ob->particlesystem.first; psys; psys = psys->next) { - any_connected |= connect_hair(depsgraph, scene, ob, psys); - } - } - else { - psys = psys_get_current(ob); - any_connected |= connect_hair(depsgraph, scene, ob, psys); - } - - if (!any_connected) { - BKE_report(op->reports, RPT_WARNING, - "No hair connected (can't connect hair if particle system modifier is disabled)"); - return OPERATOR_CANCELLED; - } - - DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY); - WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE, ob); - - return OPERATOR_FINISHED; + Depsgraph *depsgraph = CTX_data_depsgraph(C); + Scene *scene = CTX_data_scene(C); + Object *ob = ED_object_context(C); + ParticleSystem *psys = NULL; + const bool all = RNA_boolean_get(op->ptr, "all"); + bool any_connected = false; + + if (!ob) + return OPERATOR_CANCELLED; + + if (all) { + for (psys = ob->particlesystem.first; psys; psys = psys->next) { + any_connected |= connect_hair(depsgraph, scene, ob, psys); + } + } + else { + psys = psys_get_current(ob); + any_connected |= connect_hair(depsgraph, scene, ob, psys); + } + + if (!any_connected) { + BKE_report(op->reports, + RPT_WARNING, + "No hair connected (can't connect hair if particle system modifier is disabled)"); + return OPERATOR_CANCELLED; + } + + DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY); + WM_event_add_notifier(C, NC_OBJECT | ND_PARTICLE, ob); + + return OPERATOR_FINISHED; } void PARTICLE_OT_connect_hair(wmOperatorType *ot) { - ot->name = "Connect Hair"; - ot->description = "Connect hair to the emitter mesh"; - ot->idname = "PARTICLE_OT_connect_hair"; + ot->name = "Connect Hair"; + ot->description = "Connect hair to the emitter mesh"; + ot->idname = "PARTICLE_OT_connect_hair"; - ot->exec = connect_hair_exec; + ot->exec = connect_hair_exec; - /* flags */ - /* No REGISTER, redo does not work due to missing update, see T47750. */ - ot->flag = OPTYPE_UNDO; + /* flags */ + /* No REGISTER, redo does not work due to missing update, see T47750. */ + ot->flag = OPTYPE_UNDO; - RNA_def_boolean(ot->srna, "all", 0, "All hair", "Connect all hair systems to the emitter mesh"); + RNA_def_boolean(ot->srna, "all", 0, "All hair", "Connect all hair systems to the emitter mesh"); } /************************ particle system copy operator *********************/ typedef enum eCopyParticlesSpace { - PAR_COPY_SPACE_OBJECT = 0, - PAR_COPY_SPACE_WORLD = 1, + PAR_COPY_SPACE_OBJECT = 0, + PAR_COPY_SPACE_WORLD = 1, } eCopyParticlesSpace; -static void copy_particle_edit( - Depsgraph *depsgraph, Scene *scene, - Object *ob, ParticleSystem *psys, ParticleSystem *psys_from) +static void copy_particle_edit(Depsgraph *depsgraph, + Scene *scene, + Object *ob, + ParticleSystem *psys, + ParticleSystem *psys_from) { - PTCacheEdit *edit_from = psys_from->edit, *edit; - ParticleData *pa; - KEY_K; - POINT_P; - - if (!edit_from) - return; - - edit = MEM_dupallocN(edit_from); - edit->psys = psys; - psys->edit = edit; - - edit->pathcache = NULL; - BLI_listbase_clear(&edit->pathcachebufs); - - edit->emitter_field = NULL; - edit->emitter_cosnos = NULL; - - edit->points = MEM_dupallocN(edit_from->points); - pa = psys->particles; - LOOP_POINTS { - HairKey *hkey = pa->hair; - - point->keys = MEM_dupallocN(point->keys); - LOOP_KEYS { - key->co = hkey->co; - key->time = &hkey->time; - key->flag = hkey->editflag; - if (!(psys->flag & PSYS_GLOBAL_HAIR)) { - key->flag |= PEK_USE_WCO; - hkey->editflag |= PEK_USE_WCO; - } - - hkey++; - } - - pa++; - } - update_world_cos(depsgraph, ob, edit); - - UI_GetThemeColor3ubv(TH_EDGE_SELECT, edit->sel_col); - UI_GetThemeColor3ubv(TH_WIRE, edit->nosel_col); - - recalc_lengths(edit); - recalc_emitter_field(depsgraph, ob, psys); - PE_update_object(depsgraph, scene, ob, true); + PTCacheEdit *edit_from = psys_from->edit, *edit; + ParticleData *pa; + KEY_K; + POINT_P; + + if (!edit_from) + return; + + edit = MEM_dupallocN(edit_from); + edit->psys = psys; + psys->edit = edit; + + edit->pathcache = NULL; + BLI_listbase_clear(&edit->pathcachebufs); + + edit->emitter_field = NULL; + edit->emitter_cosnos = NULL; + + edit->points = MEM_dupallocN(edit_from->points); + pa = psys->particles; + LOOP_POINTS + { + HairKey *hkey = pa->hair; + + point->keys = MEM_dupallocN(point->keys); + LOOP_KEYS + { + key->co = hkey->co; + key->time = &hkey->time; + key->flag = hkey->editflag; + if (!(psys->flag & PSYS_GLOBAL_HAIR)) { + key->flag |= PEK_USE_WCO; + hkey->editflag |= PEK_USE_WCO; + } + + hkey++; + } + + pa++; + } + update_world_cos(depsgraph, ob, edit); + + UI_GetThemeColor3ubv(TH_EDGE_SELECT, edit->sel_col); + UI_GetThemeColor3ubv(TH_WIRE, edit->nosel_col); + + recalc_lengths(edit); + recalc_emitter_field(depsgraph, ob, psys); + PE_update_object(depsgraph, scene, ob, true); } static void remove_particle_systems_from_object(Object *ob_to) { - ModifierData *md, *md_next; - - if (ob_to->type != OB_MESH) - return; - if (!ob_to->data || ID_IS_LINKED(ob_to->data)) - return; - - for (md = ob_to->modifiers.first; md; md = md_next) { - md_next = md->next; - - /* remove all particle system modifiers as well, - * these need to sync to the particle system list - */ - if (ELEM(md->type, eModifierType_ParticleSystem, eModifierType_DynamicPaint, eModifierType_Smoke)) { - BLI_remlink(&ob_to->modifiers, md); - modifier_free(md); - } - } - - BKE_object_free_particlesystems(ob_to); + ModifierData *md, *md_next; + + if (ob_to->type != OB_MESH) + return; + if (!ob_to->data || ID_IS_LINKED(ob_to->data)) + return; + + for (md = ob_to->modifiers.first; md; md = md_next) { + md_next = md->next; + + /* remove all particle system modifiers as well, + * these need to sync to the particle system list + */ + if (ELEM(md->type, + eModifierType_ParticleSystem, + eModifierType_DynamicPaint, + eModifierType_Smoke)) { + BLI_remlink(&ob_to->modifiers, md); + modifier_free(md); + } + } + + BKE_object_free_particlesystems(ob_to); } /* single_psys_from is optional, if NULL all psys of ob_from are copied */ @@ -1031,245 +1045,265 @@ static bool copy_particle_systems_to_object(const bContext *C, int space, bool duplicate_settings) { - Main *bmain = CTX_data_main(C); - Depsgraph *depsgraph = CTX_data_depsgraph(C); - ModifierData *md; - ParticleSystem *psys_start = NULL, *psys, *psys_from; - ParticleSystem **tmp_psys; - Mesh *final_mesh; - CustomData_MeshMasks cdmask = {0}; - int i, totpsys; - - if (ob_to->type != OB_MESH) - return false; - if (!ob_to->data || ID_IS_LINKED(ob_to->data)) - return false; - - /* For remapping we need a valid DM. - * Because the modifiers are appended at the end it's safe to use - * the final DM of the object without particles. - * However, when evaluating the DM all the particle modifiers must be valid, - * i.e. have the psys assigned already. - * To break this hen/egg problem we create all psys separately first (to collect required customdata masks), - * then create the DM, then add them to the object and make the psys modifiers ... - */ - #define PSYS_FROM_FIRST (single_psys_from ? single_psys_from : ob_from->particlesystem.first) - #define PSYS_FROM_NEXT(cur) (single_psys_from ? NULL : (cur)->next) - totpsys = single_psys_from ? 1 : BLI_listbase_count(&ob_from->particlesystem); - - tmp_psys = MEM_mallocN(sizeof(ParticleSystem *) * totpsys, "temporary particle system array"); - - for (psys_from = PSYS_FROM_FIRST, i = 0; - psys_from; - psys_from = PSYS_FROM_NEXT(psys_from), ++i) - { - psys = BKE_object_copy_particlesystem(psys_from, 0); - tmp_psys[i] = psys; - - if (psys_start == NULL) - psys_start = psys; - - psys_emitter_customdata_mask(psys, &cdmask); - } - /* to iterate source and target psys in sync, - * we need to know where the newly added psys start - */ - psys_start = totpsys > 0 ? tmp_psys[0] : NULL; - - /* Get the evaluated mesh (psys and their modifiers have not been appended yet) */ - final_mesh = mesh_get_eval_final(depsgraph, scene, ob_to, &cdmask); - - /* now append psys to the object and make modifiers */ - for (i = 0, psys_from = PSYS_FROM_FIRST; - i < totpsys; - ++i, psys_from = PSYS_FROM_NEXT(psys_from)) - { - ParticleSystemModifierData *psmd; - - psys = tmp_psys[i]; - - /* append to the object */ - BLI_addtail(&ob_to->particlesystem, psys); - - /* add a particle system modifier for each system */ - md = modifier_new(eModifierType_ParticleSystem); - psmd = (ParticleSystemModifierData *)md; - /* push on top of the stack, no use trying to reproduce old stack order */ - BLI_addtail(&ob_to->modifiers, md); - - BLI_snprintf(md->name, sizeof(md->name), "ParticleSystem %i", i); - modifier_unique_name(&ob_to->modifiers, (ModifierData *)psmd); - - psmd->psys = psys; - BKE_id_copy_ex(NULL, &final_mesh->id, (ID **)&psmd->mesh_final, LIB_ID_COPY_LOCALIZE); - - BKE_mesh_calc_normals(psmd->mesh_final); - BKE_mesh_tessface_ensure(psmd->mesh_final); - - if (psys_from->edit) { - copy_particle_edit(depsgraph, scene, ob_to, psys, psys_from); - } - - if (duplicate_settings) { - id_us_min(&psys->part->id); - psys->part = BKE_particlesettings_copy(bmain, psys->part); - } - } - MEM_freeN(tmp_psys); - - /* note: do this after creating DM copies for all the particle system modifiers, - * the remapping otherwise makes final_dm invalid! - */ - for (psys = psys_start, psys_from = PSYS_FROM_FIRST, i = 0; - psys; - psys = psys->next, psys_from = PSYS_FROM_NEXT(psys_from), ++i) - { - float(*from_mat)[4], (*to_mat)[4]; - - switch (space) { - case PAR_COPY_SPACE_OBJECT: - from_mat = I; - to_mat = I; - break; - case PAR_COPY_SPACE_WORLD: - from_mat = ob_from->obmat; - to_mat = ob_to->obmat; - break; - default: - /* should not happen */ - from_mat = to_mat = NULL; - BLI_assert(false); - break; - } - if (ob_from != ob_to) { - remap_hair_emitter( - depsgraph, scene, ob_from, psys_from, ob_to, psys, psys->edit, - from_mat, to_mat, psys_from->flag & PSYS_GLOBAL_HAIR, psys->flag & PSYS_GLOBAL_HAIR); - } - - /* tag for recalc */ -// psys->recalc |= ID_RECALC_PSYS_RESET; - } - - #undef PSYS_FROM_FIRST - #undef PSYS_FROM_NEXT - - DEG_id_tag_update(&ob_to->id, ID_RECALC_GEOMETRY); - WM_main_add_notifier(NC_OBJECT | ND_PARTICLE | NA_EDITED, ob_to); - return true; + Main *bmain = CTX_data_main(C); + Depsgraph *depsgraph = CTX_data_depsgraph(C); + ModifierData *md; + ParticleSystem *psys_start = NULL, *psys, *psys_from; + ParticleSystem **tmp_psys; + Mesh *final_mesh; + CustomData_MeshMasks cdmask = {0}; + int i, totpsys; + + if (ob_to->type != OB_MESH) + return false; + if (!ob_to->data || ID_IS_LINKED(ob_to->data)) + return false; + +/* For remapping we need a valid DM. + * Because the modifiers are appended at the end it's safe to use + * the final DM of the object without particles. + * However, when evaluating the DM all the particle modifiers must be valid, + * i.e. have the psys assigned already. + * To break this hen/egg problem we create all psys separately first (to collect required customdata masks), + * then create the DM, then add them to the object and make the psys modifiers ... + */ +#define PSYS_FROM_FIRST (single_psys_from ? single_psys_from : ob_from->particlesystem.first) +#define PSYS_FROM_NEXT(cur) (single_psys_from ? NULL : (cur)->next) + totpsys = single_psys_from ? 1 : BLI_listbase_count(&ob_from->particlesystem); + + tmp_psys = MEM_mallocN(sizeof(ParticleSystem *) * totpsys, "temporary particle system array"); + + for (psys_from = PSYS_FROM_FIRST, i = 0; psys_from; psys_from = PSYS_FROM_NEXT(psys_from), ++i) { + psys = BKE_object_copy_particlesystem(psys_from, 0); + tmp_psys[i] = psys; + + if (psys_start == NULL) + psys_start = psys; + + psys_emitter_customdata_mask(psys, &cdmask); + } + /* to iterate source and target psys in sync, + * we need to know where the newly added psys start + */ + psys_start = totpsys > 0 ? tmp_psys[0] : NULL; + + /* Get the evaluated mesh (psys and their modifiers have not been appended yet) */ + final_mesh = mesh_get_eval_final(depsgraph, scene, ob_to, &cdmask); + + /* now append psys to the object and make modifiers */ + for (i = 0, psys_from = PSYS_FROM_FIRST; i < totpsys; + ++i, psys_from = PSYS_FROM_NEXT(psys_from)) { + ParticleSystemModifierData *psmd; + + psys = tmp_psys[i]; + + /* append to the object */ + BLI_addtail(&ob_to->particlesystem, psys); + + /* add a particle system modifier for each system */ + md = modifier_new(eModifierType_ParticleSystem); + psmd = (ParticleSystemModifierData *)md; + /* push on top of the stack, no use trying to reproduce old stack order */ + BLI_addtail(&ob_to->modifiers, md); + + BLI_snprintf(md->name, sizeof(md->name), "ParticleSystem %i", i); + modifier_unique_name(&ob_to->modifiers, (ModifierData *)psmd); + + psmd->psys = psys; + BKE_id_copy_ex(NULL, &final_mesh->id, (ID **)&psmd->mesh_final, LIB_ID_COPY_LOCALIZE); + + BKE_mesh_calc_normals(psmd->mesh_final); + BKE_mesh_tessface_ensure(psmd->mesh_final); + + if (psys_from->edit) { + copy_particle_edit(depsgraph, scene, ob_to, psys, psys_from); + } + + if (duplicate_settings) { + id_us_min(&psys->part->id); + psys->part = BKE_particlesettings_copy(bmain, psys->part); + } + } + MEM_freeN(tmp_psys); + + /* note: do this after creating DM copies for all the particle system modifiers, + * the remapping otherwise makes final_dm invalid! + */ + for (psys = psys_start, psys_from = PSYS_FROM_FIRST, i = 0; psys; + psys = psys->next, psys_from = PSYS_FROM_NEXT(psys_from), ++i) { + float(*from_mat)[4], (*to_mat)[4]; + + switch (space) { + case PAR_COPY_SPACE_OBJECT: + from_mat = I; + to_mat = I; + break; + case PAR_COPY_SPACE_WORLD: + from_mat = ob_from->obmat; + to_mat = ob_to->obmat; + break; + default: + /* should not happen */ + from_mat = to_mat = NULL; + BLI_assert(false); + break; + } + if (ob_from != ob_to) { + remap_hair_emitter(depsgraph, + scene, + ob_from, + psys_from, + ob_to, + psys, + psys->edit, + from_mat, + to_mat, + psys_from->flag & PSYS_GLOBAL_HAIR, + psys->flag & PSYS_GLOBAL_HAIR); + } + + /* tag for recalc */ + // psys->recalc |= ID_RECALC_PSYS_RESET; + } + +#undef PSYS_FROM_FIRST +#undef PSYS_FROM_NEXT + + DEG_id_tag_update(&ob_to->id, ID_RECALC_GEOMETRY); + WM_main_add_notifier(NC_OBJECT | ND_PARTICLE | NA_EDITED, ob_to); + return true; } static bool copy_particle_systems_poll(bContext *C) { - Object *ob; - if (!ED_operator_object_active_editable(C)) - return false; + Object *ob; + if (!ED_operator_object_active_editable(C)) + return false; - ob = ED_object_active_context(C); - if (BLI_listbase_is_empty(&ob->particlesystem)) - return false; + ob = ED_object_active_context(C); + if (BLI_listbase_is_empty(&ob->particlesystem)) + return false; - return true; + return true; } static int copy_particle_systems_exec(bContext *C, wmOperator *op) { - const int space = RNA_enum_get(op->ptr, "space"); - const bool remove_target_particles = RNA_boolean_get(op->ptr, "remove_target_particles"); - const bool use_active = RNA_boolean_get(op->ptr, "use_active"); - Scene *scene = CTX_data_scene(C); - Object *ob_from = ED_object_active_context(C); - ParticleSystem *psys_from = use_active ? CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem).data : NULL; - - int changed_tot = 0; - int fail = 0; - - CTX_DATA_BEGIN (C, Object *, ob_to, selected_editable_objects) - { - if (ob_from != ob_to) { - bool changed = false; - if (remove_target_particles) { - remove_particle_systems_from_object(ob_to); - changed = true; - } - if (copy_particle_systems_to_object(C, scene, ob_from, psys_from, ob_to, space, false)) - changed = true; - else - fail++; - - if (changed) - changed_tot++; - } - } - CTX_DATA_END; - - if ((changed_tot == 0 && fail == 0) || fail) { - BKE_reportf(op->reports, RPT_ERROR, - "Copy particle systems to selected: %d done, %d failed", - changed_tot, fail); - } - - return OPERATOR_FINISHED; + const int space = RNA_enum_get(op->ptr, "space"); + const bool remove_target_particles = RNA_boolean_get(op->ptr, "remove_target_particles"); + const bool use_active = RNA_boolean_get(op->ptr, "use_active"); + Scene *scene = CTX_data_scene(C); + Object *ob_from = ED_object_active_context(C); + ParticleSystem *psys_from = + use_active ? CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem).data : + NULL; + + int changed_tot = 0; + int fail = 0; + + CTX_DATA_BEGIN (C, Object *, ob_to, selected_editable_objects) { + if (ob_from != ob_to) { + bool changed = false; + if (remove_target_particles) { + remove_particle_systems_from_object(ob_to); + changed = true; + } + if (copy_particle_systems_to_object(C, scene, ob_from, psys_from, ob_to, space, false)) + changed = true; + else + fail++; + + if (changed) + changed_tot++; + } + } + CTX_DATA_END; + + if ((changed_tot == 0 && fail == 0) || fail) { + BKE_reportf(op->reports, + RPT_ERROR, + "Copy particle systems to selected: %d done, %d failed", + changed_tot, + fail); + } + + return OPERATOR_FINISHED; } void PARTICLE_OT_copy_particle_systems(wmOperatorType *ot) { - static const EnumPropertyItem space_items[] = { - {PAR_COPY_SPACE_OBJECT, "OBJECT", 0, "Object", "Copy inside each object's local space"}, - {PAR_COPY_SPACE_WORLD, "WORLD", 0, "World", "Copy in world space"}, - {0, NULL, 0, NULL, NULL}, - }; - - ot->name = "Copy Particle Systems"; - ot->description = "Copy particle systems from the active object to selected objects"; - ot->idname = "PARTICLE_OT_copy_particle_systems"; - - ot->poll = copy_particle_systems_poll; - ot->exec = copy_particle_systems_exec; - - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; - - RNA_def_enum(ot->srna, "space", space_items, PAR_COPY_SPACE_OBJECT, "Space", "Space transform for copying from one object to another"); - RNA_def_boolean(ot->srna, "remove_target_particles", true, "Remove Target Particles", "Remove particle systems on the target objects"); - RNA_def_boolean(ot->srna, "use_active", false, "Use Active", "Use the active particle system from the context"); + static const EnumPropertyItem space_items[] = { + {PAR_COPY_SPACE_OBJECT, "OBJECT", 0, "Object", "Copy inside each object's local space"}, + {PAR_COPY_SPACE_WORLD, "WORLD", 0, "World", "Copy in world space"}, + {0, NULL, 0, NULL, NULL}, + }; + + ot->name = "Copy Particle Systems"; + ot->description = "Copy particle systems from the active object to selected objects"; + ot->idname = "PARTICLE_OT_copy_particle_systems"; + + ot->poll = copy_particle_systems_poll; + ot->exec = copy_particle_systems_exec; + + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + + RNA_def_enum(ot->srna, + "space", + space_items, + PAR_COPY_SPACE_OBJECT, + "Space", + "Space transform for copying from one object to another"); + RNA_def_boolean(ot->srna, + "remove_target_particles", + true, + "Remove Target Particles", + "Remove particle systems on the target objects"); + RNA_def_boolean(ot->srna, + "use_active", + false, + "Use Active", + "Use the active particle system from the context"); } static bool duplicate_particle_systems_poll(bContext *C) { - if (!ED_operator_object_active_editable(C)) { - return false; - } - Object *ob = ED_object_active_context(C); - if (BLI_listbase_is_empty(&ob->particlesystem)) { - return false; - } - return true; + if (!ED_operator_object_active_editable(C)) { + return false; + } + Object *ob = ED_object_active_context(C); + if (BLI_listbase_is_empty(&ob->particlesystem)) { + return false; + } + return true; } static int duplicate_particle_systems_exec(bContext *C, wmOperator *op) { - const bool duplicate_settings = RNA_boolean_get(op->ptr, "use_duplicate_settings"); - Scene *scene = CTX_data_scene(C); - Object *ob = ED_object_active_context(C); - ParticleSystem *psys = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem).data; - copy_particle_systems_to_object(C, scene, ob, psys, ob, - PAR_COPY_SPACE_OBJECT, duplicate_settings); - return OPERATOR_FINISHED; + const bool duplicate_settings = RNA_boolean_get(op->ptr, "use_duplicate_settings"); + Scene *scene = CTX_data_scene(C); + Object *ob = ED_object_active_context(C); + ParticleSystem *psys = CTX_data_pointer_get_type(C, "particle_system", &RNA_ParticleSystem).data; + copy_particle_systems_to_object( + C, scene, ob, psys, ob, PAR_COPY_SPACE_OBJECT, duplicate_settings); + return OPERATOR_FINISHED; } void PARTICLE_OT_duplicate_particle_system(wmOperatorType *ot) { - ot->name = "Duplicate Particle System"; - ot->description = "Duplicate particle system within the active object"; - ot->idname = "PARTICLE_OT_duplicate_particle_system"; + ot->name = "Duplicate Particle System"; + ot->description = "Duplicate particle system within the active object"; + ot->idname = "PARTICLE_OT_duplicate_particle_system"; - ot->poll = duplicate_particle_systems_poll; - ot->exec = duplicate_particle_systems_exec; + ot->poll = duplicate_particle_systems_poll; + ot->exec = duplicate_particle_systems_exec; - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; - RNA_def_boolean(ot->srna, "use_duplicate_settings", false, "Duplicate Settings", - "Duplicate settings as well, so the new particle system uses its own settings"); + RNA_def_boolean(ot->srna, + "use_duplicate_settings", + false, + "Duplicate Settings", + "Duplicate settings as well, so the new particle system uses its own settings"); } diff --git a/source/blender/editors/physics/physics_fluid.c b/source/blender/editors/physics/physics_fluid.c index d3b57a09a9e..2769d1a9dc3 100644 --- a/source/blender/editors/physics/physics_fluid.c +++ b/source/blender/editors/physics/physics_fluid.c @@ -50,156 +50,153 @@ #include "WM_types.h" #include "WM_api.h" -#include "physics_intern.h" // own include +#include "physics_intern.h" // own include /* enable/disable overall compilation */ #ifdef WITH_MOD_FLUID -#include "LBM_fluidsim.h" +# include "LBM_fluidsim.h" -#include "BLI_blenlib.h" -#include "BLI_path_util.h" -#include "BLI_math.h" +# include "BLI_blenlib.h" +# include "BLI_path_util.h" +# include "BLI_math.h" -#include "BKE_global.h" -#include "BKE_main.h" +# include "BKE_global.h" +# include "BKE_main.h" -#include "WM_api.h" - -#include "DNA_scene_types.h" -#include "DNA_mesh_types.h" +# include "WM_api.h" +# include "DNA_scene_types.h" +# include "DNA_mesh_types.h" static float get_fluid_viscosity(FluidsimSettings *settings) { - return (1.0f/powf(10.0f, settings->viscosityExponent)) * settings->viscosityValue; + return (1.0f / powf(10.0f, settings->viscosityExponent)) * settings->viscosityValue; } static float get_fluid_rate(FluidsimSettings *settings) { - float rate = 1.0f; /* default rate if not animated... */ + float rate = 1.0f; /* default rate if not animated... */ - rate = settings->animRate; + rate = settings->animRate; - if (rate < 0.0f) - rate = 0.0f; + if (rate < 0.0f) + rate = 0.0f; - return rate; + return rate; } static void get_fluid_gravity(float *gravity, Scene *scene, FluidsimSettings *fss) { - if (scene->physics_settings.flag & PHYS_GLOBAL_GRAVITY) { - copy_v3_v3(gravity, scene->physics_settings.gravity); - } - else { - copy_v3_v3(gravity, fss->grav); - } + if (scene->physics_settings.flag & PHYS_GLOBAL_GRAVITY) { + copy_v3_v3(gravity, scene->physics_settings.gravity); + } + else { + copy_v3_v3(gravity, fss->grav); + } } static float get_fluid_size_m(Scene *scene, Object *domainob, FluidsimSettings *fss) { - if (!scene->unit.system) { - return fss->realsize; - } - else { - float dim[3]; - float longest_axis; - - BKE_object_dimensions_get(domainob, dim); - longest_axis = max_fff(dim[0], dim[1], dim[2]); - - return longest_axis * scene->unit.scale_length; - } + if (!scene->unit.system) { + return fss->realsize; + } + else { + float dim[3]; + float longest_axis; + + BKE_object_dimensions_get(domainob, dim); + longest_axis = max_fff(dim[0], dim[1], dim[2]); + + return longest_axis * scene->unit.scale_length; + } } static bool fluid_is_animated_mesh(FluidsimSettings *fss) { - return ((fss->type == OB_FLUIDSIM_CONTROL) || fss->domainNovecgen); + return ((fss->type == OB_FLUIDSIM_CONTROL) || fss->domainNovecgen); } /* ********************** fluid sim settings struct functions ********************** */ -#if 0 +# if 0 /* helper function */ void fluidsimGetGeometryObjFilename(Object *ob, char *dst) //, char *srcname) { - //BLI_snprintf(dst, FILE_MAXFILE, "%s_cfgdata_%s.bobj.gz", srcname, ob->id.name); - BLI_snprintf(dst, FILE_MAXFILE, "fluidcfgdata_%s.bobj.gz", ob->id.name); + //BLI_snprintf(dst, FILE_MAXFILE, "%s_cfgdata_%s.bobj.gz", srcname, ob->id.name); + BLI_snprintf(dst, FILE_MAXFILE, "fluidcfgdata_%s.bobj.gz", ob->id.name); } -#endif - +# endif /* ********************** fluid sim channel helper functions ********************** */ typedef struct FluidAnimChannels { - int length; + int length; - double aniFrameTime; + double aniFrameTime; - float *timeAtFrame; - float *DomainTime; - float *DomainGravity; - float *DomainViscosity; + float *timeAtFrame; + float *DomainTime; + float *DomainGravity; + float *DomainViscosity; } FluidAnimChannels; typedef struct FluidObject { - struct FluidObject *next, *prev; + struct FluidObject *next, *prev; - struct Object *object; + struct Object *object; - float *Translation; - float *Rotation; - float *Scale; - float *Active; + float *Translation; + float *Rotation; + float *Scale; + float *Active; - float *InitialVelocity; + float *InitialVelocity; - float *AttractforceStrength; - float *AttractforceRadius; - float *VelocityforceStrength; - float *VelocityforceRadius; + float *AttractforceStrength; + float *AttractforceRadius; + float *VelocityforceStrength; + float *VelocityforceRadius; - float *VertexCache; - int numVerts, numTris; + float *VertexCache; + int numVerts, numTris; } FluidObject; // no. of entries for the two channel sizes -#define CHANNEL_FLOAT 1 -#define CHANNEL_VEC 3 +# define CHANNEL_FLOAT 1 +# define CHANNEL_VEC 3 // simplify channels before printing // for API this is done anyway upon init -#if 0 +# if 0 static void fluidsimPrintChannel(FILE *file, float *channel, int paramsize, char *str, int entries) { - int i, j; - int channelSize = paramsize; - - if (entries == 3) { - elbeemSimplifyChannelVec3(channel, &channelSize); - } - else if (entries == 1) { - elbeemSimplifyChannelFloat(channel, &channelSize); - } - else { - /* invalid, cant happen? */ - } - - fprintf(file, " CHANNEL %s =\n", str); - for (i=0; i < channelSize; i++) { - fprintf(file, " "); - for (j=0;j <= entries;j++) { // also print time value - fprintf(file, " %f ", channel[i*(entries + 1) + j]); - if (j == entries-1) { fprintf(file, " "); } - } - fprintf(file, "\n"); - } - - fprintf(file, " ;\n"); + int i, j; + int channelSize = paramsize; + + if (entries == 3) { + elbeemSimplifyChannelVec3(channel, &channelSize); + } + else if (entries == 1) { + elbeemSimplifyChannelFloat(channel, &channelSize); + } + else { + /* invalid, cant happen? */ + } + + fprintf(file, " CHANNEL %s =\n", str); + for (i=0; i < channelSize; i++) { + fprintf(file, " "); + for (j=0;j <= entries;j++) { // also print time value + fprintf(file, " %f ", channel[i*(entries + 1) + j]); + if (j == entries-1) { fprintf(file, " "); } + } + fprintf(file, "\n"); + } + + fprintf(file, " ;\n"); } -#endif - +# endif /* Note: fluid anim channel data layout * ------------------------------------ @@ -214,472 +211,534 @@ static void fluidsimPrintChannel(FILE *file, float *channel, int paramsize, char static void init_time(FluidsimSettings *domainSettings, FluidAnimChannels *channels) { - int i; + int i; - channels->timeAtFrame = MEM_callocN((channels->length + 1) * sizeof(float), "timeAtFrame channel"); + channels->timeAtFrame = MEM_callocN((channels->length + 1) * sizeof(float), + "timeAtFrame channel"); - channels->timeAtFrame[0] = channels->timeAtFrame[1] = domainSettings->animStart; // start at index 1 + channels->timeAtFrame[0] = channels->timeAtFrame[1] = + domainSettings->animStart; // start at index 1 - for (i=2; i <= channels->length; i++) { - channels->timeAtFrame[i] = channels->timeAtFrame[i - 1] + (float)channels->aniFrameTime; - } + for (i = 2; i <= channels->length; i++) { + channels->timeAtFrame[i] = channels->timeAtFrame[i - 1] + (float)channels->aniFrameTime; + } } /* if this is slow, can replace with faster, less readable code */ static void set_channel(float *channel, float time, float *value, int i, int size) { - if (size == CHANNEL_FLOAT) { - channel[(i * 2) + 0] = value[0]; - channel[(i * 2) + 1] = time; - } - else if (size == CHANNEL_VEC) { - channel[(i * 4) + 0] = value[0]; - channel[(i * 4) + 1] = value[1]; - channel[(i * 4) + 2] = value[2]; - channel[(i * 4) + 3] = time; - } + if (size == CHANNEL_FLOAT) { + channel[(i * 2) + 0] = value[0]; + channel[(i * 2) + 1] = time; + } + else if (size == CHANNEL_VEC) { + channel[(i * 4) + 0] = value[0]; + channel[(i * 4) + 1] = value[1]; + channel[(i * 4) + 2] = value[2]; + channel[(i * 4) + 3] = time; + } } -static void set_vertex_channel(Depsgraph *depsgraph, float *channel, float time, struct Scene *scene, struct FluidObject *fobj, int i) +static void set_vertex_channel(Depsgraph *depsgraph, + float *channel, + float time, + struct Scene *scene, + struct FluidObject *fobj, + int i) { - Object *ob = fobj->object; - FluidsimModifierData *fluidmd = (FluidsimModifierData *)modifiers_findByType(ob, eModifierType_Fluidsim); - float *verts; - int *tris=NULL, numVerts=0, numTris=0; - int modifierIndex = BLI_findindex(&ob->modifiers, fluidmd); - int framesize = (3*fobj->numVerts) + 1; - int j; - - if (channel == NULL) - return; - - initElbeemMesh(depsgraph, scene, ob, &numVerts, &verts, &numTris, &tris, 1, modifierIndex); - - /* don't allow mesh to change number of verts in anim sequence */ - if (numVerts != fobj->numVerts) { - MEM_freeN(channel); - channel = NULL; - return; - } - - /* fill frame of channel with vertex locations */ - for (j=0; j < (3*numVerts); j++) { - channel[i*framesize + j] = verts[j]; - } - channel[i*framesize + framesize-1] = time; - - MEM_freeN(verts); - MEM_freeN(tris); + Object *ob = fobj->object; + FluidsimModifierData *fluidmd = (FluidsimModifierData *)modifiers_findByType( + ob, eModifierType_Fluidsim); + float *verts; + int *tris = NULL, numVerts = 0, numTris = 0; + int modifierIndex = BLI_findindex(&ob->modifiers, fluidmd); + int framesize = (3 * fobj->numVerts) + 1; + int j; + + if (channel == NULL) + return; + + initElbeemMesh(depsgraph, scene, ob, &numVerts, &verts, &numTris, &tris, 1, modifierIndex); + + /* don't allow mesh to change number of verts in anim sequence */ + if (numVerts != fobj->numVerts) { + MEM_freeN(channel); + channel = NULL; + return; + } + + /* fill frame of channel with vertex locations */ + for (j = 0; j < (3 * numVerts); j++) { + channel[i * framesize + j] = verts[j]; + } + channel[i * framesize + framesize - 1] = time; + + MEM_freeN(verts); + MEM_freeN(tris); } static void free_domain_channels(FluidAnimChannels *channels) { - if (!channels->timeAtFrame) - return; - MEM_freeN(channels->timeAtFrame); - channels->timeAtFrame = NULL; - MEM_freeN(channels->DomainGravity); - channels->DomainGravity = NULL; - MEM_freeN(channels->DomainViscosity); - channels->DomainViscosity = NULL; - MEM_freeN(channels->DomainTime); - channels->DomainTime = NULL; + if (!channels->timeAtFrame) + return; + MEM_freeN(channels->timeAtFrame); + channels->timeAtFrame = NULL; + MEM_freeN(channels->DomainGravity); + channels->DomainGravity = NULL; + MEM_freeN(channels->DomainViscosity); + channels->DomainViscosity = NULL; + MEM_freeN(channels->DomainTime); + channels->DomainTime = NULL; } static void free_all_fluidobject_channels(ListBase *fobjects) { - FluidObject *fobj; - - for (fobj=fobjects->first; fobj; fobj=fobj->next) { - if (fobj->Translation) { - MEM_freeN(fobj->Translation); - fobj->Translation = NULL; - MEM_freeN(fobj->Rotation); - fobj->Rotation = NULL; - MEM_freeN(fobj->Scale); - fobj->Scale = NULL; - MEM_freeN(fobj->Active); - fobj->Active = NULL; - MEM_freeN(fobj->InitialVelocity); - fobj->InitialVelocity = NULL; - } - - if (fobj->AttractforceStrength) { - MEM_freeN(fobj->AttractforceStrength); - fobj->AttractforceStrength = NULL; - MEM_freeN(fobj->AttractforceRadius); - fobj->AttractforceRadius = NULL; - MEM_freeN(fobj->VelocityforceStrength); - fobj->VelocityforceStrength = NULL; - MEM_freeN(fobj->VelocityforceRadius); - fobj->VelocityforceRadius = NULL; - } - - if (fobj->VertexCache) { - MEM_freeN(fobj->VertexCache); - fobj->VertexCache = NULL; - } - } + FluidObject *fobj; + + for (fobj = fobjects->first; fobj; fobj = fobj->next) { + if (fobj->Translation) { + MEM_freeN(fobj->Translation); + fobj->Translation = NULL; + MEM_freeN(fobj->Rotation); + fobj->Rotation = NULL; + MEM_freeN(fobj->Scale); + fobj->Scale = NULL; + MEM_freeN(fobj->Active); + fobj->Active = NULL; + MEM_freeN(fobj->InitialVelocity); + fobj->InitialVelocity = NULL; + } + + if (fobj->AttractforceStrength) { + MEM_freeN(fobj->AttractforceStrength); + fobj->AttractforceStrength = NULL; + MEM_freeN(fobj->AttractforceRadius); + fobj->AttractforceRadius = NULL; + MEM_freeN(fobj->VelocityforceStrength); + fobj->VelocityforceStrength = NULL; + MEM_freeN(fobj->VelocityforceRadius); + fobj->VelocityforceRadius = NULL; + } + + if (fobj->VertexCache) { + MEM_freeN(fobj->VertexCache); + fobj->VertexCache = NULL; + } + } } -static void fluid_init_all_channels(bContext *C, Object *UNUSED(fsDomain), FluidsimSettings *domainSettings, FluidAnimChannels *channels, ListBase *fobjects) +static void fluid_init_all_channels(bContext *C, + Object *UNUSED(fsDomain), + FluidsimSettings *domainSettings, + FluidAnimChannels *channels, + ListBase *fobjects) { - Scene *scene = CTX_data_scene(C); - ViewLayer *view_layer = CTX_data_view_layer(C); - Depsgraph *depsgraph = CTX_data_depsgraph(C); - Base *base; - int i; - int length = channels->length; - float eval_time; - - /* init time values (assuming that time moves at a constant speed; may be overridden later) */ - init_time(domainSettings, channels); - - /* allocate domain animation channels */ - channels->DomainGravity = MEM_callocN(length * (CHANNEL_VEC+1) * sizeof(float), "channel DomainGravity"); - channels->DomainViscosity = MEM_callocN(length * (CHANNEL_FLOAT+1) * sizeof(float), "channel DomainViscosity"); - channels->DomainTime = MEM_callocN(length * (CHANNEL_FLOAT+1) * sizeof(float), "channel DomainTime"); - - /* allocate fluid objects */ - for (base = FIRSTBASE(view_layer); base; base = base->next) { - Object *ob = base->object; - FluidsimModifierData *fluidmd = (FluidsimModifierData *)modifiers_findByType(ob, eModifierType_Fluidsim); - - if (fluidmd) { - FluidObject *fobj = MEM_callocN(sizeof(FluidObject), "Fluid Object"); - fobj->object = ob; - - if (ELEM(fluidmd->fss->type, OB_FLUIDSIM_DOMAIN, OB_FLUIDSIM_PARTICLE)) { - BLI_addtail(fobjects, fobj); - continue; - } - - fobj->Translation = MEM_callocN(length * (CHANNEL_VEC+1) * sizeof(float), "fluidobject Translation"); - fobj->Rotation = MEM_callocN(length * (CHANNEL_VEC+1) * sizeof(float), "fluidobject Rotation"); - fobj->Scale = MEM_callocN(length * (CHANNEL_VEC+1) * sizeof(float), "fluidobject Scale"); - fobj->Active = MEM_callocN(length * (CHANNEL_FLOAT+1) * sizeof(float), "fluidobject Active"); - fobj->InitialVelocity = MEM_callocN(length * (CHANNEL_VEC+1) * sizeof(float), "fluidobject InitialVelocity"); - - if (fluidmd->fss->type == OB_FLUIDSIM_CONTROL) { - fobj->AttractforceStrength = MEM_callocN(length * (CHANNEL_FLOAT+1) * sizeof(float), "fluidobject AttractforceStrength"); - fobj->AttractforceRadius = MEM_callocN(length * (CHANNEL_FLOAT+1) * sizeof(float), "fluidobject AttractforceRadius"); - fobj->VelocityforceStrength = MEM_callocN(length * (CHANNEL_FLOAT+1) * sizeof(float), "fluidobject VelocityforceStrength"); - fobj->VelocityforceRadius = MEM_callocN(length * (CHANNEL_FLOAT+1) * sizeof(float), "fluidobject VelocityforceRadius"); - } - - if (fluid_is_animated_mesh(fluidmd->fss)) { - float *verts=NULL; - int *tris=NULL, modifierIndex = BLI_findindex(&ob->modifiers, (ModifierData *)fluidmd); - - initElbeemMesh(depsgraph, scene, ob, &fobj->numVerts, &verts, &fobj->numTris, &tris, 0, modifierIndex); - fobj->VertexCache = MEM_callocN(length *((fobj->numVerts*CHANNEL_VEC)+1) * sizeof(float), "fluidobject VertexCache"); - - MEM_freeN(verts); - MEM_freeN(tris); - } - - BLI_addtail(fobjects, fobj); - } - } - - /* now we loop over the frames and fill the allocated channels with data */ - for (i=0; i < channels->length; i++) { - FluidObject *fobj; - float viscosity, gravity[3]; - float timeAtFrame, time; - - eval_time = domainSettings->bakeStart + i; - - /* Modifying the global scene isn't nice, but we can do it in - * this part of the process before a threaded job is created */ - scene->r.cfra = (int)eval_time; - ED_update_for_newframe(CTX_data_main(C), depsgraph); - - /* now scene data should be current according to animation system, so we fill the channels */ - - /* Domain time */ - // TODO: have option for not running sim, time mangling, in which case second case comes in handy - if (channels->DomainTime) { - time = get_fluid_rate(domainSettings) * (float)channels->aniFrameTime; - timeAtFrame = channels->timeAtFrame[i] + time; - - channels->timeAtFrame[i+1] = timeAtFrame; - set_channel(channels->DomainTime, i, &time, i, CHANNEL_FLOAT); - } - else { - timeAtFrame = channels->timeAtFrame[i+1]; - } - - /* Domain properties - gravity/viscosity */ - get_fluid_gravity(gravity, scene, domainSettings); - set_channel(channels->DomainGravity, timeAtFrame, gravity, i, CHANNEL_VEC); - viscosity = get_fluid_viscosity(domainSettings); - set_channel(channels->DomainViscosity, timeAtFrame, &viscosity, i, CHANNEL_FLOAT); - - /* object movement */ - for (fobj=fobjects->first; fobj; fobj=fobj->next) { - Object *ob = fobj->object; - FluidsimModifierData *fluidmd = (FluidsimModifierData *)modifiers_findByType(ob, eModifierType_Fluidsim); - float active = (float) ((fluidmd->fss->flag & OB_FLUIDSIM_ACTIVE) ? 1 : 0); - float rot_d[3] = {0.f, 0.f, 0.f}, old_rot[3] = {0.f, 0.f, 0.f}; - - if (ELEM(fluidmd->fss->type, OB_FLUIDSIM_DOMAIN, OB_FLUIDSIM_PARTICLE)) - continue; - - /* init euler rotation values and convert to elbeem format */ - /* get the rotation from ob->obmat rather than ob->rot to account for parent animations */ - if (i) { - copy_v3_v3(old_rot, fobj->Rotation + 4*(i-1)); - mul_v3_fl(old_rot, (float)-M_PI / 180.f); - } - - mat4_to_compatible_eulO(rot_d, old_rot, 0, ob->obmat); - mul_v3_fl(rot_d, -180.0f / (float)M_PI); - - set_channel(fobj->Translation, timeAtFrame, ob->loc, i, CHANNEL_VEC); - set_channel(fobj->Rotation, timeAtFrame, rot_d, i, CHANNEL_VEC); - set_channel(fobj->Scale, timeAtFrame, ob->scale, i, CHANNEL_VEC); - set_channel(fobj->Active, timeAtFrame, &active, i, CHANNEL_FLOAT); - set_channel(fobj->InitialVelocity, timeAtFrame, &fluidmd->fss->iniVelx, i, CHANNEL_VEC); - - // printf("Active: %f, Frame: %f\n", active, timeAtFrame); - - if (fluidmd->fss->type == OB_FLUIDSIM_CONTROL) { - set_channel(fobj->AttractforceStrength, timeAtFrame, &fluidmd->fss->attractforceStrength, i, CHANNEL_FLOAT); - set_channel(fobj->AttractforceRadius, timeAtFrame, &fluidmd->fss->attractforceRadius, i, CHANNEL_FLOAT); - set_channel(fobj->VelocityforceStrength, timeAtFrame, &fluidmd->fss->velocityforceStrength, i, CHANNEL_FLOAT); - set_channel(fobj->VelocityforceRadius, timeAtFrame, &fluidmd->fss->velocityforceRadius, i, CHANNEL_FLOAT); - } - - if (fluid_is_animated_mesh(fluidmd->fss)) { - set_vertex_channel(depsgraph, fobj->VertexCache, timeAtFrame, scene, fobj, i); - } - } - } + Scene *scene = CTX_data_scene(C); + ViewLayer *view_layer = CTX_data_view_layer(C); + Depsgraph *depsgraph = CTX_data_depsgraph(C); + Base *base; + int i; + int length = channels->length; + float eval_time; + + /* init time values (assuming that time moves at a constant speed; may be overridden later) */ + init_time(domainSettings, channels); + + /* allocate domain animation channels */ + channels->DomainGravity = MEM_callocN(length * (CHANNEL_VEC + 1) * sizeof(float), + "channel DomainGravity"); + channels->DomainViscosity = MEM_callocN(length * (CHANNEL_FLOAT + 1) * sizeof(float), + "channel DomainViscosity"); + channels->DomainTime = MEM_callocN(length * (CHANNEL_FLOAT + 1) * sizeof(float), + "channel DomainTime"); + + /* allocate fluid objects */ + for (base = FIRSTBASE(view_layer); base; base = base->next) { + Object *ob = base->object; + FluidsimModifierData *fluidmd = (FluidsimModifierData *)modifiers_findByType( + ob, eModifierType_Fluidsim); + + if (fluidmd) { + FluidObject *fobj = MEM_callocN(sizeof(FluidObject), "Fluid Object"); + fobj->object = ob; + + if (ELEM(fluidmd->fss->type, OB_FLUIDSIM_DOMAIN, OB_FLUIDSIM_PARTICLE)) { + BLI_addtail(fobjects, fobj); + continue; + } + + fobj->Translation = MEM_callocN(length * (CHANNEL_VEC + 1) * sizeof(float), + "fluidobject Translation"); + fobj->Rotation = MEM_callocN(length * (CHANNEL_VEC + 1) * sizeof(float), + "fluidobject Rotation"); + fobj->Scale = MEM_callocN(length * (CHANNEL_VEC + 1) * sizeof(float), "fluidobject Scale"); + fobj->Active = MEM_callocN(length * (CHANNEL_FLOAT + 1) * sizeof(float), + "fluidobject Active"); + fobj->InitialVelocity = MEM_callocN(length * (CHANNEL_VEC + 1) * sizeof(float), + "fluidobject InitialVelocity"); + + if (fluidmd->fss->type == OB_FLUIDSIM_CONTROL) { + fobj->AttractforceStrength = MEM_callocN(length * (CHANNEL_FLOAT + 1) * sizeof(float), + "fluidobject AttractforceStrength"); + fobj->AttractforceRadius = MEM_callocN(length * (CHANNEL_FLOAT + 1) * sizeof(float), + "fluidobject AttractforceRadius"); + fobj->VelocityforceStrength = MEM_callocN(length * (CHANNEL_FLOAT + 1) * sizeof(float), + "fluidobject VelocityforceStrength"); + fobj->VelocityforceRadius = MEM_callocN(length * (CHANNEL_FLOAT + 1) * sizeof(float), + "fluidobject VelocityforceRadius"); + } + + if (fluid_is_animated_mesh(fluidmd->fss)) { + float *verts = NULL; + int *tris = NULL, modifierIndex = BLI_findindex(&ob->modifiers, (ModifierData *)fluidmd); + + initElbeemMesh(depsgraph, + scene, + ob, + &fobj->numVerts, + &verts, + &fobj->numTris, + &tris, + 0, + modifierIndex); + fobj->VertexCache = MEM_callocN(length * ((fobj->numVerts * CHANNEL_VEC) + 1) * + sizeof(float), + "fluidobject VertexCache"); + + MEM_freeN(verts); + MEM_freeN(tris); + } + + BLI_addtail(fobjects, fobj); + } + } + + /* now we loop over the frames and fill the allocated channels with data */ + for (i = 0; i < channels->length; i++) { + FluidObject *fobj; + float viscosity, gravity[3]; + float timeAtFrame, time; + + eval_time = domainSettings->bakeStart + i; + + /* Modifying the global scene isn't nice, but we can do it in + * this part of the process before a threaded job is created */ + scene->r.cfra = (int)eval_time; + ED_update_for_newframe(CTX_data_main(C), depsgraph); + + /* now scene data should be current according to animation system, so we fill the channels */ + + /* Domain time */ + // TODO: have option for not running sim, time mangling, in which case second case comes in handy + if (channels->DomainTime) { + time = get_fluid_rate(domainSettings) * (float)channels->aniFrameTime; + timeAtFrame = channels->timeAtFrame[i] + time; + + channels->timeAtFrame[i + 1] = timeAtFrame; + set_channel(channels->DomainTime, i, &time, i, CHANNEL_FLOAT); + } + else { + timeAtFrame = channels->timeAtFrame[i + 1]; + } + + /* Domain properties - gravity/viscosity */ + get_fluid_gravity(gravity, scene, domainSettings); + set_channel(channels->DomainGravity, timeAtFrame, gravity, i, CHANNEL_VEC); + viscosity = get_fluid_viscosity(domainSettings); + set_channel(channels->DomainViscosity, timeAtFrame, &viscosity, i, CHANNEL_FLOAT); + + /* object movement */ + for (fobj = fobjects->first; fobj; fobj = fobj->next) { + Object *ob = fobj->object; + FluidsimModifierData *fluidmd = (FluidsimModifierData *)modifiers_findByType( + ob, eModifierType_Fluidsim); + float active = (float)((fluidmd->fss->flag & OB_FLUIDSIM_ACTIVE) ? 1 : 0); + float rot_d[3] = {0.f, 0.f, 0.f}, old_rot[3] = {0.f, 0.f, 0.f}; + + if (ELEM(fluidmd->fss->type, OB_FLUIDSIM_DOMAIN, OB_FLUIDSIM_PARTICLE)) + continue; + + /* init euler rotation values and convert to elbeem format */ + /* get the rotation from ob->obmat rather than ob->rot to account for parent animations */ + if (i) { + copy_v3_v3(old_rot, fobj->Rotation + 4 * (i - 1)); + mul_v3_fl(old_rot, (float)-M_PI / 180.f); + } + + mat4_to_compatible_eulO(rot_d, old_rot, 0, ob->obmat); + mul_v3_fl(rot_d, -180.0f / (float)M_PI); + + set_channel(fobj->Translation, timeAtFrame, ob->loc, i, CHANNEL_VEC); + set_channel(fobj->Rotation, timeAtFrame, rot_d, i, CHANNEL_VEC); + set_channel(fobj->Scale, timeAtFrame, ob->scale, i, CHANNEL_VEC); + set_channel(fobj->Active, timeAtFrame, &active, i, CHANNEL_FLOAT); + set_channel(fobj->InitialVelocity, timeAtFrame, &fluidmd->fss->iniVelx, i, CHANNEL_VEC); + + // printf("Active: %f, Frame: %f\n", active, timeAtFrame); + + if (fluidmd->fss->type == OB_FLUIDSIM_CONTROL) { + set_channel(fobj->AttractforceStrength, + timeAtFrame, + &fluidmd->fss->attractforceStrength, + i, + CHANNEL_FLOAT); + set_channel(fobj->AttractforceRadius, + timeAtFrame, + &fluidmd->fss->attractforceRadius, + i, + CHANNEL_FLOAT); + set_channel(fobj->VelocityforceStrength, + timeAtFrame, + &fluidmd->fss->velocityforceStrength, + i, + CHANNEL_FLOAT); + set_channel(fobj->VelocityforceRadius, + timeAtFrame, + &fluidmd->fss->velocityforceRadius, + i, + CHANNEL_FLOAT); + } + + if (fluid_is_animated_mesh(fluidmd->fss)) { + set_vertex_channel(depsgraph, fobj->VertexCache, timeAtFrame, scene, fobj, i); + } + } + } } static void export_fluid_objects(const bContext *C, ListBase *fobjects, Scene *scene, int length) { - Depsgraph *depsgraph = CTX_data_depsgraph(C); - FluidObject *fobj; - - for (fobj=fobjects->first; fobj; fobj=fobj->next) { - Object *ob = fobj->object; - FluidsimModifierData *fluidmd = (FluidsimModifierData *)modifiers_findByType(ob, eModifierType_Fluidsim); - int modifierIndex = BLI_findindex(&ob->modifiers, fluidmd); - - float *verts=NULL; - int *tris=NULL; - int numVerts=0, numTris=0; - bool deform = fluid_is_animated_mesh(fluidmd->fss); - - elbeemMesh fsmesh; - - if (ELEM(fluidmd->fss->type, OB_FLUIDSIM_DOMAIN, OB_FLUIDSIM_PARTICLE)) - continue; - - elbeemResetMesh(&fsmesh); - - fsmesh.type = fluidmd->fss->type; - fsmesh.name = ob->id.name; - - initElbeemMesh(depsgraph, scene, ob, &numVerts, &verts, &numTris, &tris, 0, modifierIndex); - - fsmesh.numVertices = numVerts; - fsmesh.numTriangles = numTris; - fsmesh.vertices = verts; - fsmesh.triangles = tris; - - fsmesh.channelSizeTranslation = - fsmesh.channelSizeRotation = - fsmesh.channelSizeScale = - fsmesh.channelSizeInitialVel = - fsmesh.channelSizeActive = length; - - fsmesh.channelTranslation = fobj->Translation; - fsmesh.channelRotation = fobj->Rotation; - fsmesh.channelScale = fobj->Scale; - fsmesh.channelActive = fobj->Active; - - if ( ELEM(fsmesh.type, OB_FLUIDSIM_FLUID, OB_FLUIDSIM_INFLOW)) { - fsmesh.channelInitialVel = fobj->InitialVelocity; - fsmesh.localInivelCoords = ((fluidmd->fss->typeFlags & OB_FSINFLOW_LOCALCOORD) ? 1 : 0); - } - - if (fluidmd->fss->typeFlags & OB_FSBND_NOSLIP) - fsmesh.obstacleType = FLUIDSIM_OBSTACLE_NOSLIP; - else if (fluidmd->fss->typeFlags & OB_FSBND_PARTSLIP) - fsmesh.obstacleType = FLUIDSIM_OBSTACLE_PARTSLIP; - else if (fluidmd->fss->typeFlags & OB_FSBND_FREESLIP) - fsmesh.obstacleType = FLUIDSIM_OBSTACLE_FREESLIP; - - fsmesh.obstaclePartslip = fluidmd->fss->partSlipValue; - fsmesh.volumeInitType = fluidmd->fss->volumeInitType; - fsmesh.obstacleImpactFactor = fluidmd->fss->surfaceSmoothing; // misused value - - if (fsmesh.type == OB_FLUIDSIM_CONTROL) { - fsmesh.cpsTimeStart = fluidmd->fss->cpsTimeStart; - fsmesh.cpsTimeEnd = fluidmd->fss->cpsTimeEnd; - fsmesh.cpsQuality = fluidmd->fss->cpsQuality; - fsmesh.obstacleType = (fluidmd->fss->flag & OB_FLUIDSIM_REVERSE); - - fsmesh.channelSizeAttractforceRadius = - fsmesh.channelSizeVelocityforceStrength = - fsmesh.channelSizeVelocityforceRadius = - fsmesh.channelSizeAttractforceStrength = length; - - fsmesh.channelAttractforceStrength = fobj->AttractforceStrength; - fsmesh.channelAttractforceRadius = fobj->AttractforceRadius; - fsmesh.channelVelocityforceStrength = fobj->VelocityforceStrength; - fsmesh.channelVelocityforceRadius = fobj->VelocityforceRadius; - } - else { - fsmesh.channelAttractforceStrength = - fsmesh.channelAttractforceRadius = - fsmesh.channelVelocityforceStrength = - fsmesh.channelVelocityforceRadius = NULL; - } - - /* animated meshes */ - if (deform) { - fsmesh.channelSizeVertices = length; - fsmesh.channelVertices = fobj->VertexCache; - - /* remove channels */ - fsmesh.channelTranslation = - fsmesh.channelRotation = - fsmesh.channelScale = NULL; - - /* Override user settings, only noslip is supported here! */ - if (fsmesh.type != OB_FLUIDSIM_CONTROL) - fsmesh.obstacleType = FLUIDSIM_OBSTACLE_NOSLIP; - } - - elbeemAddMesh(&fsmesh); - - if (verts) MEM_freeN(verts); - if (tris) MEM_freeN(tris); - } + Depsgraph *depsgraph = CTX_data_depsgraph(C); + FluidObject *fobj; + + for (fobj = fobjects->first; fobj; fobj = fobj->next) { + Object *ob = fobj->object; + FluidsimModifierData *fluidmd = (FluidsimModifierData *)modifiers_findByType( + ob, eModifierType_Fluidsim); + int modifierIndex = BLI_findindex(&ob->modifiers, fluidmd); + + float *verts = NULL; + int *tris = NULL; + int numVerts = 0, numTris = 0; + bool deform = fluid_is_animated_mesh(fluidmd->fss); + + elbeemMesh fsmesh; + + if (ELEM(fluidmd->fss->type, OB_FLUIDSIM_DOMAIN, OB_FLUIDSIM_PARTICLE)) + continue; + + elbeemResetMesh(&fsmesh); + + fsmesh.type = fluidmd->fss->type; + fsmesh.name = ob->id.name; + + initElbeemMesh(depsgraph, scene, ob, &numVerts, &verts, &numTris, &tris, 0, modifierIndex); + + fsmesh.numVertices = numVerts; + fsmesh.numTriangles = numTris; + fsmesh.vertices = verts; + fsmesh.triangles = tris; + + fsmesh.channelSizeTranslation = fsmesh.channelSizeRotation = fsmesh.channelSizeScale = + fsmesh.channelSizeInitialVel = fsmesh.channelSizeActive = length; + + fsmesh.channelTranslation = fobj->Translation; + fsmesh.channelRotation = fobj->Rotation; + fsmesh.channelScale = fobj->Scale; + fsmesh.channelActive = fobj->Active; + + if (ELEM(fsmesh.type, OB_FLUIDSIM_FLUID, OB_FLUIDSIM_INFLOW)) { + fsmesh.channelInitialVel = fobj->InitialVelocity; + fsmesh.localInivelCoords = ((fluidmd->fss->typeFlags & OB_FSINFLOW_LOCALCOORD) ? 1 : 0); + } + + if (fluidmd->fss->typeFlags & OB_FSBND_NOSLIP) + fsmesh.obstacleType = FLUIDSIM_OBSTACLE_NOSLIP; + else if (fluidmd->fss->typeFlags & OB_FSBND_PARTSLIP) + fsmesh.obstacleType = FLUIDSIM_OBSTACLE_PARTSLIP; + else if (fluidmd->fss->typeFlags & OB_FSBND_FREESLIP) + fsmesh.obstacleType = FLUIDSIM_OBSTACLE_FREESLIP; + + fsmesh.obstaclePartslip = fluidmd->fss->partSlipValue; + fsmesh.volumeInitType = fluidmd->fss->volumeInitType; + fsmesh.obstacleImpactFactor = fluidmd->fss->surfaceSmoothing; // misused value + + if (fsmesh.type == OB_FLUIDSIM_CONTROL) { + fsmesh.cpsTimeStart = fluidmd->fss->cpsTimeStart; + fsmesh.cpsTimeEnd = fluidmd->fss->cpsTimeEnd; + fsmesh.cpsQuality = fluidmd->fss->cpsQuality; + fsmesh.obstacleType = (fluidmd->fss->flag & OB_FLUIDSIM_REVERSE); + + fsmesh.channelSizeAttractforceRadius = fsmesh.channelSizeVelocityforceStrength = + fsmesh.channelSizeVelocityforceRadius = fsmesh.channelSizeAttractforceStrength = length; + + fsmesh.channelAttractforceStrength = fobj->AttractforceStrength; + fsmesh.channelAttractforceRadius = fobj->AttractforceRadius; + fsmesh.channelVelocityforceStrength = fobj->VelocityforceStrength; + fsmesh.channelVelocityforceRadius = fobj->VelocityforceRadius; + } + else { + fsmesh.channelAttractforceStrength = fsmesh.channelAttractforceRadius = + fsmesh.channelVelocityforceStrength = fsmesh.channelVelocityforceRadius = NULL; + } + + /* animated meshes */ + if (deform) { + fsmesh.channelSizeVertices = length; + fsmesh.channelVertices = fobj->VertexCache; + + /* remove channels */ + fsmesh.channelTranslation = fsmesh.channelRotation = fsmesh.channelScale = NULL; + + /* Override user settings, only noslip is supported here! */ + if (fsmesh.type != OB_FLUIDSIM_CONTROL) + fsmesh.obstacleType = FLUIDSIM_OBSTACLE_NOSLIP; + } + + elbeemAddMesh(&fsmesh); + + if (verts) + MEM_freeN(verts); + if (tris) + MEM_freeN(tris); + } } static int fluid_validate_scene(ReportList *reports, ViewLayer *view_layer, Object *fsDomain) { - Base *base; - Object *newdomain = NULL; - int channelObjCount = 0; - int fluidInputCount = 0; - - for (base = FIRSTBASE(view_layer); base; base = base->next) { - Object *ob = base->object; - FluidsimModifierData *fluidmdtmp = (FluidsimModifierData *)modifiers_findByType(ob, eModifierType_Fluidsim); - - /* only find objects with fluid modifiers */ - if (!fluidmdtmp || ob->type != OB_MESH) continue; - - if (fluidmdtmp->fss->type == OB_FLUIDSIM_DOMAIN) { - /* if no initial domain object given, find another potential domain */ - if (!fsDomain) { - newdomain = ob; - } - /* if there's more than one domain, cancel */ - else if (fsDomain && ob != fsDomain) { - BKE_report(reports, RPT_ERROR, "There should be only one domain object"); - return 0; - } - } - - /* count number of objects needed for animation channels */ - if ( !ELEM(fluidmdtmp->fss->type, OB_FLUIDSIM_DOMAIN, OB_FLUIDSIM_PARTICLE) ) - channelObjCount++; - - /* count number of fluid input objects */ - if (ELEM(fluidmdtmp->fss->type, OB_FLUIDSIM_FLUID, OB_FLUIDSIM_INFLOW)) - fluidInputCount++; - } - - if (newdomain) - fsDomain = newdomain; - - if (!fsDomain) { - BKE_report(reports, RPT_ERROR, "No domain object found"); - return 0; - } - - if (channelObjCount >= 255) { - BKE_report(reports, RPT_ERROR, "Cannot bake with more than 256 objects"); - return 0; - } - - if (fluidInputCount == 0) { - BKE_report(reports, RPT_ERROR, "No fluid input objects in the scene"); - return 0; - } - - return 1; + Base *base; + Object *newdomain = NULL; + int channelObjCount = 0; + int fluidInputCount = 0; + + for (base = FIRSTBASE(view_layer); base; base = base->next) { + Object *ob = base->object; + FluidsimModifierData *fluidmdtmp = (FluidsimModifierData *)modifiers_findByType( + ob, eModifierType_Fluidsim); + + /* only find objects with fluid modifiers */ + if (!fluidmdtmp || ob->type != OB_MESH) + continue; + + if (fluidmdtmp->fss->type == OB_FLUIDSIM_DOMAIN) { + /* if no initial domain object given, find another potential domain */ + if (!fsDomain) { + newdomain = ob; + } + /* if there's more than one domain, cancel */ + else if (fsDomain && ob != fsDomain) { + BKE_report(reports, RPT_ERROR, "There should be only one domain object"); + return 0; + } + } + + /* count number of objects needed for animation channels */ + if (!ELEM(fluidmdtmp->fss->type, OB_FLUIDSIM_DOMAIN, OB_FLUIDSIM_PARTICLE)) + channelObjCount++; + + /* count number of fluid input objects */ + if (ELEM(fluidmdtmp->fss->type, OB_FLUIDSIM_FLUID, OB_FLUIDSIM_INFLOW)) + fluidInputCount++; + } + + if (newdomain) + fsDomain = newdomain; + + if (!fsDomain) { + BKE_report(reports, RPT_ERROR, "No domain object found"); + return 0; + } + + if (channelObjCount >= 255) { + BKE_report(reports, RPT_ERROR, "Cannot bake with more than 256 objects"); + return 0; + } + + if (fluidInputCount == 0) { + BKE_report(reports, RPT_ERROR, "No fluid input objects in the scene"); + return 0; + } + + return 1; } +# define FLUID_SUFFIX_CONFIG "fluidsim.cfg" +# define FLUID_SUFFIX_CONFIG_TMP (FLUID_SUFFIX_CONFIG ".tmp") +# define FLUID_SUFFIX_SURFACE "fluidsurface" -#define FLUID_SUFFIX_CONFIG "fluidsim.cfg" -#define FLUID_SUFFIX_CONFIG_TMP (FLUID_SUFFIX_CONFIG ".tmp") -#define FLUID_SUFFIX_SURFACE "fluidsurface" - -static bool fluid_init_filepaths( - Main *bmain, ReportList *reports, FluidsimSettings *domainSettings, Object *fsDomain, - char *targetDir, char *targetFile) +static bool fluid_init_filepaths(Main *bmain, + ReportList *reports, + FluidsimSettings *domainSettings, + Object *fsDomain, + char *targetDir, + char *targetFile) { - const char *suffixConfigTmp = FLUID_SUFFIX_CONFIG_TMP; - - /* prepare names... */ - const char *relbase = modifier_path_relbase(bmain, fsDomain); - - /* We do not accept empty paths, they can end in random places silently, see T51176. */ - if (domainSettings->surfdataPath[0] == '\0') { - modifier_path_init(domainSettings->surfdataPath, sizeof(domainSettings->surfdataPath), - OB_FLUIDSIM_SURF_DIR_DEFAULT); - BKE_reportf(reports, RPT_WARNING, "Fluidsim: empty cache path, reset to default '%s'", - domainSettings->surfdataPath); - } - - BLI_strncpy(targetDir, domainSettings->surfdataPath, FILE_MAXDIR); - BLI_path_abs(targetDir, relbase); - - /* .tmp: don't overwrite/delete original file */ - BLI_join_dirfile(targetFile, FILE_MAX, targetDir, suffixConfigTmp); - - /* Ensure whole path exists and is wirtable. */ - const bool dir_exists = BLI_dir_create_recursive(targetDir); - const bool is_writable = BLI_file_is_writable(targetFile); - - /* We change path to some presumably valid default value, but do not allow bake process to continue, - * this gives user chance to set manually another path. */ - if (!dir_exists || !is_writable) { - modifier_path_init(domainSettings->surfdataPath, sizeof(domainSettings->surfdataPath), - OB_FLUIDSIM_SURF_DIR_DEFAULT); - - if (!dir_exists) { - BKE_reportf(reports, RPT_ERROR, "Fluidsim: could not create cache directory '%s', reset to default '%s'", - targetDir, domainSettings->surfdataPath); - } - else { - BKE_reportf(reports, RPT_ERROR, "Fluidsim: cache directory '%s' is not writable, reset to default '%s'", - targetDir, domainSettings->surfdataPath); - } - - BLI_strncpy(targetDir, domainSettings->surfdataPath, FILE_MAXDIR); - BLI_path_abs(targetDir, relbase); - - /* .tmp: don't overwrite/delete original file */ - BLI_join_dirfile(targetFile, FILE_MAX, targetDir, suffixConfigTmp); - - /* Ensure whole path exists and is wirtable. */ - if (!BLI_dir_create_recursive(targetDir) || !BLI_file_is_writable(targetFile)) { - BKE_reportf(reports, RPT_ERROR, "Fluidsim: could not use default cache directory '%s', " - "please define a valid cache path manually", targetDir); - } - return false; - } - - return true; + const char *suffixConfigTmp = FLUID_SUFFIX_CONFIG_TMP; + + /* prepare names... */ + const char *relbase = modifier_path_relbase(bmain, fsDomain); + + /* We do not accept empty paths, they can end in random places silently, see T51176. */ + if (domainSettings->surfdataPath[0] == '\0') { + modifier_path_init(domainSettings->surfdataPath, + sizeof(domainSettings->surfdataPath), + OB_FLUIDSIM_SURF_DIR_DEFAULT); + BKE_reportf(reports, + RPT_WARNING, + "Fluidsim: empty cache path, reset to default '%s'", + domainSettings->surfdataPath); + } + + BLI_strncpy(targetDir, domainSettings->surfdataPath, FILE_MAXDIR); + BLI_path_abs(targetDir, relbase); + + /* .tmp: don't overwrite/delete original file */ + BLI_join_dirfile(targetFile, FILE_MAX, targetDir, suffixConfigTmp); + + /* Ensure whole path exists and is wirtable. */ + const bool dir_exists = BLI_dir_create_recursive(targetDir); + const bool is_writable = BLI_file_is_writable(targetFile); + + /* We change path to some presumably valid default value, but do not allow bake process to continue, + * this gives user chance to set manually another path. */ + if (!dir_exists || !is_writable) { + modifier_path_init(domainSettings->surfdataPath, + sizeof(domainSettings->surfdataPath), + OB_FLUIDSIM_SURF_DIR_DEFAULT); + + if (!dir_exists) { + BKE_reportf(reports, + RPT_ERROR, + "Fluidsim: could not create cache directory '%s', reset to default '%s'", + targetDir, + domainSettings->surfdataPath); + } + else { + BKE_reportf(reports, + RPT_ERROR, + "Fluidsim: cache directory '%s' is not writable, reset to default '%s'", + targetDir, + domainSettings->surfdataPath); + } + + BLI_strncpy(targetDir, domainSettings->surfdataPath, FILE_MAXDIR); + BLI_path_abs(targetDir, relbase); + + /* .tmp: don't overwrite/delete original file */ + BLI_join_dirfile(targetFile, FILE_MAX, targetDir, suffixConfigTmp); + + /* Ensure whole path exists and is wirtable. */ + if (!BLI_dir_create_recursive(targetDir) || !BLI_file_is_writable(targetFile)) { + BKE_reportf(reports, + RPT_ERROR, + "Fluidsim: could not use default cache directory '%s', " + "please define a valid cache path manually", + targetDir); + } + return false; + } + + return true; } /* ******************************************************************************** */ @@ -687,392 +746,431 @@ static bool fluid_init_filepaths( /* ******************************************************************************** */ typedef struct FluidBakeJob { - /* from wmJob */ - void *owner; - short *stop, *do_update; - float *progress; - int current_frame; - elbeemSimulationSettings *settings; + /* from wmJob */ + void *owner; + short *stop, *do_update; + float *progress; + int current_frame; + elbeemSimulationSettings *settings; } FluidBakeJob; static void fluidbake_free(void *customdata) { - FluidBakeJob *fb= (FluidBakeJob *)customdata; - MEM_freeN(fb); + FluidBakeJob *fb = (FluidBakeJob *)customdata; + MEM_freeN(fb); } /* called by fluidbake, only to check job 'stop' value */ static int fluidbake_breakjob(void *customdata) { - FluidBakeJob *fb= (FluidBakeJob *)customdata; + FluidBakeJob *fb = (FluidBakeJob *)customdata; - if (fb->stop && *(fb->stop)) - return 1; + if (fb->stop && *(fb->stop)) + return 1; - /* this is not nice yet, need to make the jobs list template better - * for identifying/acting upon various different jobs */ - /* but for now we'll reuse the render break... */ - return (G.is_break); + /* this is not nice yet, need to make the jobs list template better + * for identifying/acting upon various different jobs */ + /* but for now we'll reuse the render break... */ + return (G.is_break); } /* called by fluidbake, wmJob sends notifier */ static void fluidbake_updatejob(void *customdata, float progress) { - FluidBakeJob *fb= (FluidBakeJob *)customdata; + FluidBakeJob *fb = (FluidBakeJob *)customdata; - *(fb->do_update) = true; - *(fb->progress) = progress; + *(fb->do_update) = true; + *(fb->progress) = progress; } static void fluidbake_startjob(void *customdata, short *stop, short *do_update, float *progress) { - FluidBakeJob *fb= (FluidBakeJob *)customdata; + FluidBakeJob *fb = (FluidBakeJob *)customdata; - fb->stop= stop; - fb->do_update = do_update; - fb->progress = progress; + fb->stop = stop; + fb->do_update = do_update; + fb->progress = progress; - G.is_break = false; /* XXX shared with render - replace with job 'stop' switch */ + G.is_break = false; /* XXX shared with render - replace with job 'stop' switch */ - elbeemSimulate(); - *do_update = true; - *stop = 0; + elbeemSimulate(); + *do_update = true; + *stop = 0; } static void fluidbake_endjob(void *customdata) { - FluidBakeJob *fb= (FluidBakeJob *)customdata; + FluidBakeJob *fb = (FluidBakeJob *)customdata; - if (fb->settings) { - MEM_freeN(fb->settings); - fb->settings = NULL; - } + if (fb->settings) { + MEM_freeN(fb->settings); + fb->settings = NULL; + } } static int runSimulationCallback(void *data, int status, int frame) { - FluidBakeJob *fb = (FluidBakeJob *)data; - elbeemSimulationSettings *settings = fb->settings; + FluidBakeJob *fb = (FluidBakeJob *)data; + elbeemSimulationSettings *settings = fb->settings; - if (status == FLUIDSIM_CBSTATUS_NEWFRAME) { - fluidbake_updatejob(fb, frame / (float)settings->noOfFrames); - //printf("elbeem blender cb s%d, f%d, domainid:%d noOfFrames: %d\n", status, frame, settings->domainId, settings->noOfFrames ); // DEBUG - } + if (status == FLUIDSIM_CBSTATUS_NEWFRAME) { + fluidbake_updatejob(fb, frame / (float)settings->noOfFrames); + //printf("elbeem blender cb s%d, f%d, domainid:%d noOfFrames: %d\n", status, frame, settings->domainId, settings->noOfFrames ); // DEBUG + } - if (fluidbake_breakjob(fb)) { - return FLUIDSIM_CBRET_ABORT; - } + if (fluidbake_breakjob(fb)) { + return FLUIDSIM_CBRET_ABORT; + } - return FLUIDSIM_CBRET_CONTINUE; + return FLUIDSIM_CBRET_CONTINUE; } -static void fluidbake_free_data(FluidAnimChannels *channels, ListBase *fobjects, elbeemSimulationSettings *fsset, FluidBakeJob *fb) +static void fluidbake_free_data(FluidAnimChannels *channels, + ListBase *fobjects, + elbeemSimulationSettings *fsset, + FluidBakeJob *fb) { - free_domain_channels(channels); - MEM_freeN(channels); - channels = NULL; - - free_all_fluidobject_channels(fobjects); - BLI_freelistN(fobjects); - MEM_freeN(fobjects); - fobjects = NULL; - - if (fsset) { - MEM_freeN(fsset); - fsset = NULL; - } - - if (fb) { - MEM_freeN(fb); - fb = NULL; - } + free_domain_channels(channels); + MEM_freeN(channels); + channels = NULL; + + free_all_fluidobject_channels(fobjects); + BLI_freelistN(fobjects); + MEM_freeN(fobjects); + fobjects = NULL; + + if (fsset) { + MEM_freeN(fsset); + fsset = NULL; + } + + if (fb) { + MEM_freeN(fb); + fb = NULL; + } } /* copied from rna_fluidsim.c: fluidsim_find_lastframe() */ static void fluidsim_delete_until_lastframe(FluidsimSettings *fss, const char *relbase) { - char targetDir[FILE_MAX], targetFile[FILE_MAX]; - char targetDirVel[FILE_MAX], targetFileVel[FILE_MAX]; - char previewDir[FILE_MAX], previewFile[FILE_MAX]; - int curFrame = 1, exists = 0; - - BLI_join_dirfile(targetDir, sizeof(targetDir), fss->surfdataPath, OB_FLUIDSIM_SURF_FINAL_OBJ_FNAME); - BLI_join_dirfile(targetDirVel, sizeof(targetDirVel), fss->surfdataPath, OB_FLUIDSIM_SURF_FINAL_VEL_FNAME); - BLI_join_dirfile(previewDir, sizeof(previewDir), fss->surfdataPath, OB_FLUIDSIM_SURF_PREVIEW_OBJ_FNAME); - - BLI_path_abs(targetDir, relbase); - BLI_path_abs(targetDirVel, relbase); - BLI_path_abs(previewDir, relbase); - - do { - BLI_strncpy(targetFile, targetDir, sizeof(targetFile)); - BLI_strncpy(targetFileVel, targetDirVel, sizeof(targetFileVel)); - BLI_strncpy(previewFile, previewDir, sizeof(previewFile)); - - BLI_path_frame(targetFile, curFrame, 0); - BLI_path_frame(targetFileVel, curFrame, 0); - BLI_path_frame(previewFile, curFrame, 0); - - curFrame++; - - if ((exists = BLI_exists(targetFile))) { - BLI_delete(targetFile, false, false); - BLI_delete(targetFileVel, false, false); - BLI_delete(previewFile, false, false); - } - } while (exists); - - return; + char targetDir[FILE_MAX], targetFile[FILE_MAX]; + char targetDirVel[FILE_MAX], targetFileVel[FILE_MAX]; + char previewDir[FILE_MAX], previewFile[FILE_MAX]; + int curFrame = 1, exists = 0; + + BLI_join_dirfile( + targetDir, sizeof(targetDir), fss->surfdataPath, OB_FLUIDSIM_SURF_FINAL_OBJ_FNAME); + BLI_join_dirfile( + targetDirVel, sizeof(targetDirVel), fss->surfdataPath, OB_FLUIDSIM_SURF_FINAL_VEL_FNAME); + BLI_join_dirfile( + previewDir, sizeof(previewDir), fss->surfdataPath, OB_FLUIDSIM_SURF_PREVIEW_OBJ_FNAME); + + BLI_path_abs(targetDir, relbase); + BLI_path_abs(targetDirVel, relbase); + BLI_path_abs(previewDir, relbase); + + do { + BLI_strncpy(targetFile, targetDir, sizeof(targetFile)); + BLI_strncpy(targetFileVel, targetDirVel, sizeof(targetFileVel)); + BLI_strncpy(previewFile, previewDir, sizeof(previewFile)); + + BLI_path_frame(targetFile, curFrame, 0); + BLI_path_frame(targetFileVel, curFrame, 0); + BLI_path_frame(previewFile, curFrame, 0); + + curFrame++; + + if ((exists = BLI_exists(targetFile))) { + BLI_delete(targetFile, false, false); + BLI_delete(targetFileVel, false, false); + BLI_delete(previewFile, false, false); + } + } while (exists); + + return; } static int fluidsimBake(bContext *C, ReportList *reports, Object *fsDomain, short do_job) { - Main *bmain = CTX_data_main(C); - Scene *scene = CTX_data_scene(C); - ViewLayer *view_layer = CTX_data_view_layer(C); - Depsgraph *depsgraph = CTX_data_depsgraph(C); - int i; - FluidsimSettings *domainSettings; - - char debugStrBuffer[256]; - - int gridlevels = 0; - const char *relbase= modifier_path_relbase(bmain, fsDomain); - const char *strEnvName = "BLENDER_ELBEEMDEBUG"; // from blendercall.cpp - const char *suffixConfigTmp = FLUID_SUFFIX_CONFIG_TMP; - const char *suffixSurface = FLUID_SUFFIX_SURFACE; - - char targetDir[FILE_MAX]; // store & modify output settings - char targetFile[FILE_MAX]; // temp. store filename from targetDir for access - - float domainMat[4][4]; - float invDomMat[4][4]; - - int noFrames; - int origFrame = scene->r.cfra; - - FluidAnimChannels *channels = MEM_callocN(sizeof(FluidAnimChannels), "fluid domain animation channels"); - ListBase *fobjects = MEM_callocN(sizeof(ListBase), "fluid objects"); - FluidsimModifierData *fluidmd = NULL; - Mesh *mesh = NULL; - - FluidBakeJob *fb; - elbeemSimulationSettings *fsset= MEM_callocN(sizeof(elbeemSimulationSettings), "Fluid sim settings"); - - fb= MEM_callocN(sizeof(FluidBakeJob), "fluid bake job"); - - if (BLI_getenv(strEnvName)) { - int dlevel = atoi(BLI_getenv(strEnvName)); - elbeemSetDebugLevel(dlevel); - BLI_snprintf(debugStrBuffer, sizeof(debugStrBuffer), "fluidsimBake::msg: Debug messages activated due to envvar '%s'\n", strEnvName); - elbeemDebugOut(debugStrBuffer); - } - - /* make sure it corresponds to startFrame setting (old: noFrames = scene->r.efra - scene->r.sfra +1) */; - noFrames = scene->r.efra - 0; - if (noFrames<=0) { - BKE_report(reports, RPT_ERROR, "No frames to export (check your animation range settings)"); - fluidbake_free_data(channels, fobjects, fsset, fb); - return 0; - } - - /* check scene for sane object/modifier settings */ - if (!fluid_validate_scene(reports, view_layer, fsDomain)) { - fluidbake_free_data(channels, fobjects, fsset, fb); - return 0; - } - - /* these both have to be valid, otherwise we wouldn't be here */ - fluidmd = (FluidsimModifierData *)modifiers_findByType(fsDomain, eModifierType_Fluidsim); - domainSettings = fluidmd->fss; - mesh = fsDomain->data; - - domainSettings->bakeStart = 1; - domainSettings->bakeEnd = scene->r.efra; - - // calculate bounding box - fluid_get_bb(mesh->mvert, mesh->totvert, fsDomain->obmat, domainSettings->bbStart, domainSettings->bbSize); - - // reset last valid frame - domainSettings->lastgoodframe = -1; - - /* delete old baked files */ - fluidsim_delete_until_lastframe(domainSettings, relbase); - - /* rough check of settings... */ - if (domainSettings->previewresxyz > domainSettings->resolutionxyz) { - BLI_snprintf(debugStrBuffer, sizeof(debugStrBuffer), "fluidsimBake::warning - Preview (%d) >= Resolution (%d)... setting equal.\n", domainSettings->previewresxyz, domainSettings->resolutionxyz); - elbeemDebugOut(debugStrBuffer); - domainSettings->previewresxyz = domainSettings->resolutionxyz; - } - // set adaptive coarsening according to resolutionxyz - // this should do as an approximation, with in/outflow - // doing this more accurate would be overkill - // perhaps add manual setting? - if (domainSettings->maxRefine <0) { - if (domainSettings->resolutionxyz>128) { - gridlevels = 2; - } - else if (domainSettings->resolutionxyz > 64) { - gridlevels = 1; - } - else { - gridlevels = 0; - } - } - else { - gridlevels = domainSettings->maxRefine; - } - BLI_snprintf(debugStrBuffer, sizeof(debugStrBuffer), "fluidsimBake::msg: Baking %s, refine: %d\n", fsDomain->id.name, gridlevels); - elbeemDebugOut(debugStrBuffer); - - - - /* ******** prepare output file paths ******** */ - if (!fluid_init_filepaths(bmain, reports, domainSettings, fsDomain, targetDir, targetFile)) { - fluidbake_free_data(channels, fobjects, fsset, fb); - return false; - } - - channels->length = scene->r.efra; // DG TODO: why using endframe and not "noFrames" here? .. because "noFrames" is buggy too? (not using sfra) - channels->aniFrameTime = (double)((double)domainSettings->animEnd - (double)domainSettings->animStart) / (double)noFrames; - - /* ******** initialize and allocate animation channels ******** */ - fluid_init_all_channels(C, fsDomain, domainSettings, channels, fobjects); - - /* reset to original current frame */ - scene->r.cfra = origFrame; - ED_update_for_newframe(CTX_data_main(C), depsgraph); - - /* ******** init domain object's matrix ******** */ - copy_m4_m4(domainMat, fsDomain->obmat); - if (!invert_m4_m4(invDomMat, domainMat)) { - BLI_snprintf(debugStrBuffer, sizeof(debugStrBuffer), "fluidsimBake::error - Invalid obj matrix?\n"); - elbeemDebugOut(debugStrBuffer); - BKE_report(reports, RPT_ERROR, "Invalid object matrix"); - - fluidbake_free_data(channels, fobjects, fsset, fb); - return 0; - } - - /* ******** start writing / exporting ******** */ - // use .tmp, don't overwrite/delete original file - BLI_join_dirfile(targetFile, sizeof(targetFile), targetDir, suffixConfigTmp); - - /* ******** export domain to elbeem ******** */ - elbeemResetSettings(fsset); - fsset->version = 1; - fsset->threads = (domainSettings->threads == 0) ? BKE_scene_num_threads(scene) : domainSettings->threads; - // setup global settings - copy_v3_v3(fsset->geoStart, domainSettings->bbStart); - copy_v3_v3(fsset->geoSize, domainSettings->bbSize); - - // simulate with 50^3 - fsset->resolutionxyz = (int)domainSettings->resolutionxyz; - fsset->previewresxyz = (int)domainSettings->previewresxyz; - - fsset->realsize = get_fluid_size_m(scene, fsDomain, domainSettings); - fsset->viscosity = get_fluid_viscosity(domainSettings); - get_fluid_gravity(fsset->gravity, scene, domainSettings); - - // simulate 5 frames, each 0.03 seconds, output to ./apitest_XXX.bobj.gz - fsset->animStart = domainSettings->animStart; - fsset->aniFrameTime = channels->aniFrameTime; - fsset->noOfFrames = noFrames; // is otherwise subtracted in parser - - BLI_join_dirfile(targetFile, sizeof(targetFile), targetDir, suffixSurface); - - // defaults for compressibility and adaptive grids - fsset->gstar = domainSettings->gstar; - fsset->maxRefine = domainSettings->maxRefine; // check <-> gridlevels - fsset->generateParticles = domainSettings->generateParticles; - fsset->numTracerParticles = domainSettings->generateTracers; - fsset->surfaceSmoothing = domainSettings->surfaceSmoothing; - fsset->surfaceSubdivs = domainSettings->surfaceSubdivs; - fsset->farFieldSize = domainSettings->farFieldSize; - BLI_strncpy(fsset->outputPath, targetFile, sizeof(fsset->outputPath)); - - // domain channels - fsset->channelSizeFrameTime = - fsset->channelSizeViscosity = - fsset->channelSizeGravity = channels->length; - fsset->channelFrameTime = channels->DomainTime; - fsset->channelViscosity = channels->DomainViscosity; - fsset->channelGravity = channels->DomainGravity; - - fsset->runsimCallback = &runSimulationCallback; - fsset->runsimUserData = fb; - - if (domainSettings->typeFlags & OB_FSBND_NOSLIP) fsset->domainobsType = FLUIDSIM_OBSTACLE_NOSLIP; - else if (domainSettings->typeFlags&OB_FSBND_PARTSLIP) fsset->domainobsType = FLUIDSIM_OBSTACLE_PARTSLIP; - else if (domainSettings->typeFlags&OB_FSBND_FREESLIP) fsset->domainobsType = FLUIDSIM_OBSTACLE_FREESLIP; - fsset->domainobsPartslip = domainSettings->partSlipValue; - - /* use domainobsType also for surface generation flag (bit: >=64) */ - if (domainSettings->typeFlags & OB_FSSG_NOOBS) - fsset->mFsSurfGenSetting = FLUIDSIM_FSSG_NOOBS; - else - fsset->mFsSurfGenSetting = 0; // "normal" mode - - fsset->generateVertexVectors = (domainSettings->domainNovecgen==0); - - // init blender domain transform matrix - { int j; - for (i=0; i<4; i++) { - for (j=0; j<4; j++) { - fsset->surfaceTrafo[i*4+j] = invDomMat[j][i]; - } - } } - - /* ******** init solver with settings ******** */ - elbeemInit(); - elbeemAddDomain(fsset); - - /* ******** export all fluid objects to elbeem ******** */ - export_fluid_objects(C, fobjects, scene, channels->length); - - /* custom data for fluid bake job */ - fb->settings = fsset; - - if (do_job) { - wmJob *wm_job = WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), scene, "Fluid Simulation", - WM_JOB_PROGRESS, WM_JOB_TYPE_OBJECT_SIM_FLUID); - - /* setup job */ - WM_jobs_customdata_set(wm_job, fb, fluidbake_free); - WM_jobs_timer(wm_job, 0.1, NC_SCENE|ND_FRAME, NC_SCENE|ND_FRAME); - WM_jobs_callbacks(wm_job, fluidbake_startjob, NULL, NULL, fluidbake_endjob); - - WM_jobs_start(CTX_wm_manager(C), wm_job); - } - else { - short dummy_stop = 0, dummy_do_update = 0; - float dummy_progress = 0.0f; - - /* blocking, use with exec() */ - fluidbake_startjob((void *)fb, &dummy_stop, &dummy_do_update, &dummy_progress); - fluidbake_endjob((void *)fb); - fluidbake_free((void *)fb); - } - - /* ******** free stored animation data ******** */ - fluidbake_free_data(channels, fobjects, NULL, NULL); - - // elbeemFree(); - return 1; + Main *bmain = CTX_data_main(C); + Scene *scene = CTX_data_scene(C); + ViewLayer *view_layer = CTX_data_view_layer(C); + Depsgraph *depsgraph = CTX_data_depsgraph(C); + int i; + FluidsimSettings *domainSettings; + + char debugStrBuffer[256]; + + int gridlevels = 0; + const char *relbase = modifier_path_relbase(bmain, fsDomain); + const char *strEnvName = "BLENDER_ELBEEMDEBUG"; // from blendercall.cpp + const char *suffixConfigTmp = FLUID_SUFFIX_CONFIG_TMP; + const char *suffixSurface = FLUID_SUFFIX_SURFACE; + + char targetDir[FILE_MAX]; // store & modify output settings + char targetFile[FILE_MAX]; // temp. store filename from targetDir for access + + float domainMat[4][4]; + float invDomMat[4][4]; + + int noFrames; + int origFrame = scene->r.cfra; + + FluidAnimChannels *channels = MEM_callocN(sizeof(FluidAnimChannels), + "fluid domain animation channels"); + ListBase *fobjects = MEM_callocN(sizeof(ListBase), "fluid objects"); + FluidsimModifierData *fluidmd = NULL; + Mesh *mesh = NULL; + + FluidBakeJob *fb; + elbeemSimulationSettings *fsset = MEM_callocN(sizeof(elbeemSimulationSettings), + "Fluid sim settings"); + + fb = MEM_callocN(sizeof(FluidBakeJob), "fluid bake job"); + + if (BLI_getenv(strEnvName)) { + int dlevel = atoi(BLI_getenv(strEnvName)); + elbeemSetDebugLevel(dlevel); + BLI_snprintf(debugStrBuffer, + sizeof(debugStrBuffer), + "fluidsimBake::msg: Debug messages activated due to envvar '%s'\n", + strEnvName); + elbeemDebugOut(debugStrBuffer); + } + + /* make sure it corresponds to startFrame setting (old: noFrames = scene->r.efra - scene->r.sfra +1) */ + ; + noFrames = scene->r.efra - 0; + if (noFrames <= 0) { + BKE_report(reports, RPT_ERROR, "No frames to export (check your animation range settings)"); + fluidbake_free_data(channels, fobjects, fsset, fb); + return 0; + } + + /* check scene for sane object/modifier settings */ + if (!fluid_validate_scene(reports, view_layer, fsDomain)) { + fluidbake_free_data(channels, fobjects, fsset, fb); + return 0; + } + + /* these both have to be valid, otherwise we wouldn't be here */ + fluidmd = (FluidsimModifierData *)modifiers_findByType(fsDomain, eModifierType_Fluidsim); + domainSettings = fluidmd->fss; + mesh = fsDomain->data; + + domainSettings->bakeStart = 1; + domainSettings->bakeEnd = scene->r.efra; + + // calculate bounding box + fluid_get_bb(mesh->mvert, + mesh->totvert, + fsDomain->obmat, + domainSettings->bbStart, + domainSettings->bbSize); + + // reset last valid frame + domainSettings->lastgoodframe = -1; + + /* delete old baked files */ + fluidsim_delete_until_lastframe(domainSettings, relbase); + + /* rough check of settings... */ + if (domainSettings->previewresxyz > domainSettings->resolutionxyz) { + BLI_snprintf(debugStrBuffer, + sizeof(debugStrBuffer), + "fluidsimBake::warning - Preview (%d) >= Resolution (%d)... setting equal.\n", + domainSettings->previewresxyz, + domainSettings->resolutionxyz); + elbeemDebugOut(debugStrBuffer); + domainSettings->previewresxyz = domainSettings->resolutionxyz; + } + // set adaptive coarsening according to resolutionxyz + // this should do as an approximation, with in/outflow + // doing this more accurate would be overkill + // perhaps add manual setting? + if (domainSettings->maxRefine < 0) { + if (domainSettings->resolutionxyz > 128) { + gridlevels = 2; + } + else if (domainSettings->resolutionxyz > 64) { + gridlevels = 1; + } + else { + gridlevels = 0; + } + } + else { + gridlevels = domainSettings->maxRefine; + } + BLI_snprintf(debugStrBuffer, + sizeof(debugStrBuffer), + "fluidsimBake::msg: Baking %s, refine: %d\n", + fsDomain->id.name, + gridlevels); + elbeemDebugOut(debugStrBuffer); + + /* ******** prepare output file paths ******** */ + if (!fluid_init_filepaths(bmain, reports, domainSettings, fsDomain, targetDir, targetFile)) { + fluidbake_free_data(channels, fobjects, fsset, fb); + return false; + } + + channels->length = + scene->r + .efra; // DG TODO: why using endframe and not "noFrames" here? .. because "noFrames" is buggy too? (not using sfra) + channels->aniFrameTime = (double)((double)domainSettings->animEnd - + (double)domainSettings->animStart) / + (double)noFrames; + + /* ******** initialize and allocate animation channels ******** */ + fluid_init_all_channels(C, fsDomain, domainSettings, channels, fobjects); + + /* reset to original current frame */ + scene->r.cfra = origFrame; + ED_update_for_newframe(CTX_data_main(C), depsgraph); + + /* ******** init domain object's matrix ******** */ + copy_m4_m4(domainMat, fsDomain->obmat); + if (!invert_m4_m4(invDomMat, domainMat)) { + BLI_snprintf( + debugStrBuffer, sizeof(debugStrBuffer), "fluidsimBake::error - Invalid obj matrix?\n"); + elbeemDebugOut(debugStrBuffer); + BKE_report(reports, RPT_ERROR, "Invalid object matrix"); + + fluidbake_free_data(channels, fobjects, fsset, fb); + return 0; + } + + /* ******** start writing / exporting ******** */ + // use .tmp, don't overwrite/delete original file + BLI_join_dirfile(targetFile, sizeof(targetFile), targetDir, suffixConfigTmp); + + /* ******** export domain to elbeem ******** */ + elbeemResetSettings(fsset); + fsset->version = 1; + fsset->threads = (domainSettings->threads == 0) ? BKE_scene_num_threads(scene) : + domainSettings->threads; + // setup global settings + copy_v3_v3(fsset->geoStart, domainSettings->bbStart); + copy_v3_v3(fsset->geoSize, domainSettings->bbSize); + + // simulate with 50^3 + fsset->resolutionxyz = (int)domainSettings->resolutionxyz; + fsset->previewresxyz = (int)domainSettings->previewresxyz; + + fsset->realsize = get_fluid_size_m(scene, fsDomain, domainSettings); + fsset->viscosity = get_fluid_viscosity(domainSettings); + get_fluid_gravity(fsset->gravity, scene, domainSettings); + + // simulate 5 frames, each 0.03 seconds, output to ./apitest_XXX.bobj.gz + fsset->animStart = domainSettings->animStart; + fsset->aniFrameTime = channels->aniFrameTime; + fsset->noOfFrames = noFrames; // is otherwise subtracted in parser + + BLI_join_dirfile(targetFile, sizeof(targetFile), targetDir, suffixSurface); + + // defaults for compressibility and adaptive grids + fsset->gstar = domainSettings->gstar; + fsset->maxRefine = domainSettings->maxRefine; // check <-> gridlevels + fsset->generateParticles = domainSettings->generateParticles; + fsset->numTracerParticles = domainSettings->generateTracers; + fsset->surfaceSmoothing = domainSettings->surfaceSmoothing; + fsset->surfaceSubdivs = domainSettings->surfaceSubdivs; + fsset->farFieldSize = domainSettings->farFieldSize; + BLI_strncpy(fsset->outputPath, targetFile, sizeof(fsset->outputPath)); + + // domain channels + fsset->channelSizeFrameTime = fsset->channelSizeViscosity = fsset->channelSizeGravity = + channels->length; + fsset->channelFrameTime = channels->DomainTime; + fsset->channelViscosity = channels->DomainViscosity; + fsset->channelGravity = channels->DomainGravity; + + fsset->runsimCallback = &runSimulationCallback; + fsset->runsimUserData = fb; + + if (domainSettings->typeFlags & OB_FSBND_NOSLIP) + fsset->domainobsType = FLUIDSIM_OBSTACLE_NOSLIP; + else if (domainSettings->typeFlags & OB_FSBND_PARTSLIP) + fsset->domainobsType = FLUIDSIM_OBSTACLE_PARTSLIP; + else if (domainSettings->typeFlags & OB_FSBND_FREESLIP) + fsset->domainobsType = FLUIDSIM_OBSTACLE_FREESLIP; + fsset->domainobsPartslip = domainSettings->partSlipValue; + + /* use domainobsType also for surface generation flag (bit: >=64) */ + if (domainSettings->typeFlags & OB_FSSG_NOOBS) + fsset->mFsSurfGenSetting = FLUIDSIM_FSSG_NOOBS; + else + fsset->mFsSurfGenSetting = 0; // "normal" mode + + fsset->generateVertexVectors = (domainSettings->domainNovecgen == 0); + + // init blender domain transform matrix + { + int j; + for (i = 0; i < 4; i++) { + for (j = 0; j < 4; j++) { + fsset->surfaceTrafo[i * 4 + j] = invDomMat[j][i]; + } + } + } + + /* ******** init solver with settings ******** */ + elbeemInit(); + elbeemAddDomain(fsset); + + /* ******** export all fluid objects to elbeem ******** */ + export_fluid_objects(C, fobjects, scene, channels->length); + + /* custom data for fluid bake job */ + fb->settings = fsset; + + if (do_job) { + wmJob *wm_job = WM_jobs_get(CTX_wm_manager(C), + CTX_wm_window(C), + scene, + "Fluid Simulation", + WM_JOB_PROGRESS, + WM_JOB_TYPE_OBJECT_SIM_FLUID); + + /* setup job */ + WM_jobs_customdata_set(wm_job, fb, fluidbake_free); + WM_jobs_timer(wm_job, 0.1, NC_SCENE | ND_FRAME, NC_SCENE | ND_FRAME); + WM_jobs_callbacks(wm_job, fluidbake_startjob, NULL, NULL, fluidbake_endjob); + + WM_jobs_start(CTX_wm_manager(C), wm_job); + } + else { + short dummy_stop = 0, dummy_do_update = 0; + float dummy_progress = 0.0f; + + /* blocking, use with exec() */ + fluidbake_startjob((void *)fb, &dummy_stop, &dummy_do_update, &dummy_progress); + fluidbake_endjob((void *)fb); + fluidbake_free((void *)fb); + } + + /* ******** free stored animation data ******** */ + fluidbake_free_data(channels, fobjects, NULL, NULL); + + // elbeemFree(); + return 1; } static void UNUSED_FUNCTION(fluidsimFreeBake)(Object *UNUSED(ob)) { - /* not implemented yet */ + /* not implemented yet */ } #else /* WITH_MOD_FLUID */ /* only compile dummy functions */ -static int fluidsimBake(bContext *UNUSED(C), ReportList *UNUSED(reports), Object *UNUSED(ob), short UNUSED(do_job)) +static int fluidsimBake(bContext *UNUSED(C), + ReportList *UNUSED(reports), + Object *UNUSED(ob), + short UNUSED(do_job)) { - return 0; + return 0; } #endif /* WITH_MOD_FLUID */ @@ -1081,33 +1179,33 @@ static int fluidsimBake(bContext *UNUSED(C), ReportList *UNUSED(reports), Object static int fluid_bake_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event)) { - /* only one bake job at a time */ - if (WM_jobs_test(CTX_wm_manager(C), CTX_data_scene(C), WM_JOB_TYPE_OBJECT_SIM_FLUID)) - return OPERATOR_CANCELLED; + /* only one bake job at a time */ + if (WM_jobs_test(CTX_wm_manager(C), CTX_data_scene(C), WM_JOB_TYPE_OBJECT_SIM_FLUID)) + return OPERATOR_CANCELLED; - if (!fluidsimBake(C, op->reports, CTX_data_active_object(C), true)) - return OPERATOR_CANCELLED; + if (!fluidsimBake(C, op->reports, CTX_data_active_object(C), true)) + return OPERATOR_CANCELLED; - return OPERATOR_FINISHED; + return OPERATOR_FINISHED; } static int fluid_bake_exec(bContext *C, wmOperator *op) { - if (!fluidsimBake(C, op->reports, CTX_data_active_object(C), false)) - return OPERATOR_CANCELLED; + if (!fluidsimBake(C, op->reports, CTX_data_active_object(C), false)) + return OPERATOR_CANCELLED; - return OPERATOR_FINISHED; + return OPERATOR_FINISHED; } void FLUID_OT_bake(wmOperatorType *ot) { - /* identifiers */ - ot->name = "Fluid Simulation Bake"; - ot->description = "Bake fluid simulation"; - ot->idname = "FLUID_OT_bake"; - - /* api callbacks */ - ot->invoke = fluid_bake_invoke; - ot->exec = fluid_bake_exec; - ot->poll = ED_operator_object_active_editable; + /* identifiers */ + ot->name = "Fluid Simulation Bake"; + ot->description = "Bake fluid simulation"; + ot->idname = "FLUID_OT_bake"; + + /* api callbacks */ + ot->invoke = fluid_bake_invoke; + ot->exec = fluid_bake_exec; + ot->poll = ED_operator_object_active_editable; } diff --git a/source/blender/editors/physics/physics_intern.h b/source/blender/editors/physics/physics_intern.h index dbadb2356d1..bb7cfe9b1a3 100644 --- a/source/blender/editors/physics/physics_intern.h +++ b/source/blender/editors/physics/physics_intern.h @@ -21,7 +21,6 @@ * \ingroup edphys */ - #ifndef __PHYSICS_INTERN_H__ #define __PHYSICS_INTERN_H__ @@ -62,11 +61,15 @@ void PARTICLE_OT_edited_clear(struct wmOperatorType *ot); void PARTICLE_OT_unify_length(struct wmOperatorType *ot); -void PE_create_particle_edit( - struct Depsgraph *depsgraph, struct Scene *scene, - struct Object *ob, struct PointCache *cache, struct ParticleSystem *psys); +void PE_create_particle_edit(struct Depsgraph *depsgraph, + struct Scene *scene, + struct Object *ob, + struct PointCache *cache, + struct ParticleSystem *psys); void recalc_lengths(struct PTCacheEdit *edit); -void recalc_emitter_field(struct Depsgraph *depsgraph, struct Object *ob, struct ParticleSystem *psys); +void recalc_emitter_field(struct Depsgraph *depsgraph, + struct Object *ob, + struct ParticleSystem *psys); void update_world_cos(struct Depsgraph *depsgraph, struct Object *ob, struct PTCacheEdit *edit); /* particle_object.c */ diff --git a/source/blender/editors/physics/physics_ops.c b/source/blender/editors/physics/physics_ops.c index 40cbf51b840..b1b3927d05e 100644 --- a/source/blender/editors/physics/physics_ops.c +++ b/source/blender/editors/physics/physics_ops.c @@ -32,141 +32,139 @@ #include "ED_physics.h" #include "ED_object.h" -#include "physics_intern.h" // own include - +#include "physics_intern.h" // own include /***************************** particles ***********************************/ static void operatortypes_particle(void) { - WM_operatortype_append(PARTICLE_OT_select_all); - WM_operatortype_append(PARTICLE_OT_select_roots); - WM_operatortype_append(PARTICLE_OT_select_tips); - WM_operatortype_append(PARTICLE_OT_select_random); - WM_operatortype_append(PARTICLE_OT_select_linked); - WM_operatortype_append(PARTICLE_OT_select_less); - WM_operatortype_append(PARTICLE_OT_select_more); - - WM_operatortype_append(PARTICLE_OT_hide); - WM_operatortype_append(PARTICLE_OT_reveal); - - WM_operatortype_append(PARTICLE_OT_rekey); - WM_operatortype_append(PARTICLE_OT_subdivide); - WM_operatortype_append(PARTICLE_OT_remove_doubles); - WM_operatortype_append(PARTICLE_OT_weight_set); - WM_operatortype_append(PARTICLE_OT_delete); - WM_operatortype_append(PARTICLE_OT_mirror); - - WM_operatortype_append(PARTICLE_OT_brush_edit); - - WM_operatortype_append(PARTICLE_OT_shape_cut); - - WM_operatortype_append(PARTICLE_OT_particle_edit_toggle); - WM_operatortype_append(PARTICLE_OT_edited_clear); - - WM_operatortype_append(PARTICLE_OT_unify_length); - - - WM_operatortype_append(OBJECT_OT_particle_system_add); - WM_operatortype_append(OBJECT_OT_particle_system_remove); - - WM_operatortype_append(PARTICLE_OT_new); - WM_operatortype_append(PARTICLE_OT_new_target); - WM_operatortype_append(PARTICLE_OT_target_remove); - WM_operatortype_append(PARTICLE_OT_target_move_up); - WM_operatortype_append(PARTICLE_OT_target_move_down); - WM_operatortype_append(PARTICLE_OT_connect_hair); - WM_operatortype_append(PARTICLE_OT_disconnect_hair); - WM_operatortype_append(PARTICLE_OT_copy_particle_systems); - WM_operatortype_append(PARTICLE_OT_duplicate_particle_system); - - WM_operatortype_append(PARTICLE_OT_dupliob_refresh); - WM_operatortype_append(PARTICLE_OT_dupliob_copy); - WM_operatortype_append(PARTICLE_OT_dupliob_remove); - WM_operatortype_append(PARTICLE_OT_dupliob_move_up); - WM_operatortype_append(PARTICLE_OT_dupliob_move_down); - - WM_operatortype_append(RIGIDBODY_OT_object_add); - WM_operatortype_append(RIGIDBODY_OT_object_remove); - - WM_operatortype_append(RIGIDBODY_OT_objects_add); - WM_operatortype_append(RIGIDBODY_OT_objects_remove); - - WM_operatortype_append(RIGIDBODY_OT_shape_change); - WM_operatortype_append(RIGIDBODY_OT_mass_calculate); - - WM_operatortype_append(RIGIDBODY_OT_constraint_add); - WM_operatortype_append(RIGIDBODY_OT_constraint_remove); - - WM_operatortype_append(RIGIDBODY_OT_world_add); - WM_operatortype_append(RIGIDBODY_OT_world_remove); -// WM_operatortype_append(RIGIDBODY_OT_world_export); + WM_operatortype_append(PARTICLE_OT_select_all); + WM_operatortype_append(PARTICLE_OT_select_roots); + WM_operatortype_append(PARTICLE_OT_select_tips); + WM_operatortype_append(PARTICLE_OT_select_random); + WM_operatortype_append(PARTICLE_OT_select_linked); + WM_operatortype_append(PARTICLE_OT_select_less); + WM_operatortype_append(PARTICLE_OT_select_more); + + WM_operatortype_append(PARTICLE_OT_hide); + WM_operatortype_append(PARTICLE_OT_reveal); + + WM_operatortype_append(PARTICLE_OT_rekey); + WM_operatortype_append(PARTICLE_OT_subdivide); + WM_operatortype_append(PARTICLE_OT_remove_doubles); + WM_operatortype_append(PARTICLE_OT_weight_set); + WM_operatortype_append(PARTICLE_OT_delete); + WM_operatortype_append(PARTICLE_OT_mirror); + + WM_operatortype_append(PARTICLE_OT_brush_edit); + + WM_operatortype_append(PARTICLE_OT_shape_cut); + + WM_operatortype_append(PARTICLE_OT_particle_edit_toggle); + WM_operatortype_append(PARTICLE_OT_edited_clear); + + WM_operatortype_append(PARTICLE_OT_unify_length); + + WM_operatortype_append(OBJECT_OT_particle_system_add); + WM_operatortype_append(OBJECT_OT_particle_system_remove); + + WM_operatortype_append(PARTICLE_OT_new); + WM_operatortype_append(PARTICLE_OT_new_target); + WM_operatortype_append(PARTICLE_OT_target_remove); + WM_operatortype_append(PARTICLE_OT_target_move_up); + WM_operatortype_append(PARTICLE_OT_target_move_down); + WM_operatortype_append(PARTICLE_OT_connect_hair); + WM_operatortype_append(PARTICLE_OT_disconnect_hair); + WM_operatortype_append(PARTICLE_OT_copy_particle_systems); + WM_operatortype_append(PARTICLE_OT_duplicate_particle_system); + + WM_operatortype_append(PARTICLE_OT_dupliob_refresh); + WM_operatortype_append(PARTICLE_OT_dupliob_copy); + WM_operatortype_append(PARTICLE_OT_dupliob_remove); + WM_operatortype_append(PARTICLE_OT_dupliob_move_up); + WM_operatortype_append(PARTICLE_OT_dupliob_move_down); + + WM_operatortype_append(RIGIDBODY_OT_object_add); + WM_operatortype_append(RIGIDBODY_OT_object_remove); + + WM_operatortype_append(RIGIDBODY_OT_objects_add); + WM_operatortype_append(RIGIDBODY_OT_objects_remove); + + WM_operatortype_append(RIGIDBODY_OT_shape_change); + WM_operatortype_append(RIGIDBODY_OT_mass_calculate); + + WM_operatortype_append(RIGIDBODY_OT_constraint_add); + WM_operatortype_append(RIGIDBODY_OT_constraint_remove); + + WM_operatortype_append(RIGIDBODY_OT_world_add); + WM_operatortype_append(RIGIDBODY_OT_world_remove); + // WM_operatortype_append(RIGIDBODY_OT_world_export); } static void keymap_particle(wmKeyConfig *keyconf) { - wmKeyMap *keymap = WM_keymap_ensure(keyconf, "Particle", 0, 0); - keymap->poll = PE_poll; + wmKeyMap *keymap = WM_keymap_ensure(keyconf, "Particle", 0, 0); + keymap->poll = PE_poll; } /******************************* boids *************************************/ static void operatortypes_boids(void) { - WM_operatortype_append(BOID_OT_rule_add); - WM_operatortype_append(BOID_OT_rule_del); - WM_operatortype_append(BOID_OT_rule_move_up); - WM_operatortype_append(BOID_OT_rule_move_down); - - WM_operatortype_append(BOID_OT_state_add); - WM_operatortype_append(BOID_OT_state_del); - WM_operatortype_append(BOID_OT_state_move_up); - WM_operatortype_append(BOID_OT_state_move_down); + WM_operatortype_append(BOID_OT_rule_add); + WM_operatortype_append(BOID_OT_rule_del); + WM_operatortype_append(BOID_OT_rule_move_up); + WM_operatortype_append(BOID_OT_rule_move_down); + + WM_operatortype_append(BOID_OT_state_add); + WM_operatortype_append(BOID_OT_state_del); + WM_operatortype_append(BOID_OT_state_move_up); + WM_operatortype_append(BOID_OT_state_move_down); } /********************************* fluid ***********************************/ static void operatortypes_fluid(void) { - WM_operatortype_append(FLUID_OT_bake); + WM_operatortype_append(FLUID_OT_bake); } /**************************** point cache **********************************/ static void operatortypes_pointcache(void) { - WM_operatortype_append(PTCACHE_OT_bake_all); - WM_operatortype_append(PTCACHE_OT_free_bake_all); - WM_operatortype_append(PTCACHE_OT_bake); - WM_operatortype_append(PTCACHE_OT_free_bake); - WM_operatortype_append(PTCACHE_OT_bake_from_cache); - WM_operatortype_append(PTCACHE_OT_add); - WM_operatortype_append(PTCACHE_OT_remove); + WM_operatortype_append(PTCACHE_OT_bake_all); + WM_operatortype_append(PTCACHE_OT_free_bake_all); + WM_operatortype_append(PTCACHE_OT_bake); + WM_operatortype_append(PTCACHE_OT_free_bake); + WM_operatortype_append(PTCACHE_OT_bake_from_cache); + WM_operatortype_append(PTCACHE_OT_add); + WM_operatortype_append(PTCACHE_OT_remove); } /********************************* dynamic paint ***********************************/ static void operatortypes_dynamicpaint(void) { - WM_operatortype_append(DPAINT_OT_bake); - WM_operatortype_append(DPAINT_OT_surface_slot_add); - WM_operatortype_append(DPAINT_OT_surface_slot_remove); - WM_operatortype_append(DPAINT_OT_type_toggle); - WM_operatortype_append(DPAINT_OT_output_toggle); + WM_operatortype_append(DPAINT_OT_bake); + WM_operatortype_append(DPAINT_OT_surface_slot_add); + WM_operatortype_append(DPAINT_OT_surface_slot_remove); + WM_operatortype_append(DPAINT_OT_type_toggle); + WM_operatortype_append(DPAINT_OT_output_toggle); } /****************************** general ************************************/ void ED_operatortypes_physics(void) { - operatortypes_particle(); - operatortypes_boids(); - operatortypes_fluid(); - operatortypes_pointcache(); - operatortypes_dynamicpaint(); + operatortypes_particle(); + operatortypes_boids(); + operatortypes_fluid(); + operatortypes_pointcache(); + operatortypes_dynamicpaint(); } void ED_keymap_physics(wmKeyConfig *keyconf) { - keymap_particle(keyconf); + keymap_particle(keyconf); } diff --git a/source/blender/editors/physics/physics_pointcache.c b/source/blender/editors/physics/physics_pointcache.c index ab89922e89c..e9e89a31f94 100644 --- a/source/blender/editors/physics/physics_pointcache.c +++ b/source/blender/editors/physics/physics_pointcache.c @@ -51,384 +51,387 @@ static bool ptcache_bake_all_poll(bContext *C) { - return CTX_data_scene(C) != NULL; + return CTX_data_scene(C) != NULL; } static bool ptcache_poll(bContext *C) { - PointerRNA ptr= CTX_data_pointer_get_type(C, "point_cache", &RNA_PointCache); - return (ptr.data && ptr.id.data); + PointerRNA ptr = CTX_data_pointer_get_type(C, "point_cache", &RNA_PointCache); + return (ptr.data && ptr.id.data); } typedef struct PointCacheJob { - wmWindowManager *wm; - void *owner; - short *stop, *do_update; - float *progress; + wmWindowManager *wm; + void *owner; + short *stop, *do_update; + float *progress; - PTCacheBaker *baker; + PTCacheBaker *baker; } PointCacheJob; static void ptcache_job_free(void *customdata) { - PointCacheJob *job = customdata; - MEM_freeN(job->baker); - MEM_freeN(job); + PointCacheJob *job = customdata; + MEM_freeN(job->baker); + MEM_freeN(job); } static int ptcache_job_break(void *customdata) { - PointCacheJob *job = customdata; + PointCacheJob *job = customdata; - if (G.is_break) { - return 1; - } + if (G.is_break) { + return 1; + } - if (job->stop && *(job->stop)) { - return 1; - } + if (job->stop && *(job->stop)) { + return 1; + } - return 0; + return 0; } static void ptcache_job_update(void *customdata, float progress, int *cancel) { - PointCacheJob *job = customdata; + PointCacheJob *job = customdata; - if (ptcache_job_break(job)) { - *cancel = 1; - } + if (ptcache_job_break(job)) { + *cancel = 1; + } - *(job->do_update) = true; - *(job->progress) = progress; + *(job->do_update) = true; + *(job->progress) = progress; } static void ptcache_job_startjob(void *customdata, short *stop, short *do_update, float *progress) { - PointCacheJob *job = customdata; + PointCacheJob *job = customdata; - job->stop = stop; - job->do_update = do_update; - job->progress = progress; + job->stop = stop; + job->do_update = do_update; + job->progress = progress; - G.is_break = false; + G.is_break = false; - /* XXX annoying hack: needed to prevent data corruption when changing - * scene frame in separate threads - */ - WM_set_locked_interface(job->wm, true); + /* XXX annoying hack: needed to prevent data corruption when changing + * scene frame in separate threads + */ + WM_set_locked_interface(job->wm, true); - BKE_ptcache_bake(job->baker); + BKE_ptcache_bake(job->baker); - *do_update = true; - *stop = 0; + *do_update = true; + *stop = 0; } static void ptcache_job_endjob(void *customdata) { - PointCacheJob *job = customdata; - Scene *scene = job->baker->scene; + PointCacheJob *job = customdata; + Scene *scene = job->baker->scene; - WM_set_locked_interface(job->wm, false); + WM_set_locked_interface(job->wm, false); - WM_main_add_notifier(NC_SCENE | ND_FRAME, scene); - WM_main_add_notifier(NC_OBJECT | ND_POINTCACHE, job->baker->pid.ob); + WM_main_add_notifier(NC_SCENE | ND_FRAME, scene); + WM_main_add_notifier(NC_OBJECT | ND_POINTCACHE, job->baker->pid.ob); } static void ptcache_free_bake(PointCache *cache) { - if (cache->edit) { - if (!cache->edit->edited || 1) {// XXX okee("Lose changes done in particle mode?")) { - PE_free_ptcache_edit(cache->edit); - cache->edit = NULL; - cache->flag &= ~PTCACHE_BAKED; - } - } - else { - cache->flag &= ~PTCACHE_BAKED; - } + if (cache->edit) { + if (!cache->edit->edited || 1) { // XXX okee("Lose changes done in particle mode?")) { + PE_free_ptcache_edit(cache->edit); + cache->edit = NULL; + cache->flag &= ~PTCACHE_BAKED; + } + } + else { + cache->flag &= ~PTCACHE_BAKED; + } } static PTCacheBaker *ptcache_baker_create(bContext *C, wmOperator *op, bool all) { - PTCacheBaker *baker = MEM_callocN(sizeof(PTCacheBaker), "PTCacheBaker"); - - baker->bmain = CTX_data_main(C); - baker->scene = CTX_data_scene(C); - baker->view_layer = CTX_data_view_layer(C); - baker->depsgraph = CTX_data_depsgraph(C); - baker->bake = RNA_boolean_get(op->ptr, "bake"); - baker->render = 0; - baker->anim_init = 0; - baker->quick_step = 1; - - if (!all) { - PointerRNA ptr = CTX_data_pointer_get_type(C, "point_cache", &RNA_PointCache); - Object *ob = ptr.id.data; - PointCache *cache = ptr.data; - baker->pid = BKE_ptcache_id_find(ob, baker->scene, cache); - } - - return baker; + PTCacheBaker *baker = MEM_callocN(sizeof(PTCacheBaker), "PTCacheBaker"); + + baker->bmain = CTX_data_main(C); + baker->scene = CTX_data_scene(C); + baker->view_layer = CTX_data_view_layer(C); + baker->depsgraph = CTX_data_depsgraph(C); + baker->bake = RNA_boolean_get(op->ptr, "bake"); + baker->render = 0; + baker->anim_init = 0; + baker->quick_step = 1; + + if (!all) { + PointerRNA ptr = CTX_data_pointer_get_type(C, "point_cache", &RNA_PointCache); + Object *ob = ptr.id.data; + PointCache *cache = ptr.data; + baker->pid = BKE_ptcache_id_find(ob, baker->scene, cache); + } + + return baker; } static int ptcache_bake_exec(bContext *C, wmOperator *op) { - bool all = STREQ(op->type->idname, "PTCACHE_OT_bake_all"); + bool all = STREQ(op->type->idname, "PTCACHE_OT_bake_all"); - PTCacheBaker *baker = ptcache_baker_create(C, op, all); - BKE_ptcache_bake(baker); - MEM_freeN(baker); + PTCacheBaker *baker = ptcache_baker_create(C, op, all); + BKE_ptcache_bake(baker); + MEM_freeN(baker); - return OPERATOR_FINISHED; + return OPERATOR_FINISHED; } static int ptcache_bake_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event)) { - bool all = STREQ(op->type->idname, "PTCACHE_OT_bake_all"); + bool all = STREQ(op->type->idname, "PTCACHE_OT_bake_all"); - PointCacheJob *job = MEM_mallocN(sizeof(PointCacheJob), "PointCacheJob"); - job->wm = CTX_wm_manager(C); - job->baker = ptcache_baker_create(C, op, all); - job->baker->bake_job = job; - job->baker->update_progress = ptcache_job_update; + PointCacheJob *job = MEM_mallocN(sizeof(PointCacheJob), "PointCacheJob"); + job->wm = CTX_wm_manager(C); + job->baker = ptcache_baker_create(C, op, all); + job->baker->bake_job = job; + job->baker->update_progress = ptcache_job_update; - wmJob *wm_job = WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), CTX_data_scene(C), - "Point Cache", WM_JOB_PROGRESS, WM_JOB_TYPE_POINTCACHE); + wmJob *wm_job = WM_jobs_get(CTX_wm_manager(C), + CTX_wm_window(C), + CTX_data_scene(C), + "Point Cache", + WM_JOB_PROGRESS, + WM_JOB_TYPE_POINTCACHE); - WM_jobs_customdata_set(wm_job, job, ptcache_job_free); - WM_jobs_timer(wm_job, 0.1, NC_OBJECT | ND_POINTCACHE, NC_OBJECT | ND_POINTCACHE); - WM_jobs_callbacks(wm_job, ptcache_job_startjob, NULL, NULL, ptcache_job_endjob); + WM_jobs_customdata_set(wm_job, job, ptcache_job_free); + WM_jobs_timer(wm_job, 0.1, NC_OBJECT | ND_POINTCACHE, NC_OBJECT | ND_POINTCACHE); + WM_jobs_callbacks(wm_job, ptcache_job_startjob, NULL, NULL, ptcache_job_endjob); - WM_set_locked_interface(CTX_wm_manager(C), true); + WM_set_locked_interface(CTX_wm_manager(C), true); - WM_jobs_start(CTX_wm_manager(C), wm_job); + WM_jobs_start(CTX_wm_manager(C), wm_job); - WM_event_add_modal_handler(C, op); + WM_event_add_modal_handler(C, op); - /* we must run modal until the bake job is done, otherwise the undo push - * happens before the job ends, which can lead to race conditions between - * the baking and file writing code */ - return OPERATOR_RUNNING_MODAL; + /* we must run modal until the bake job is done, otherwise the undo push + * happens before the job ends, which can lead to race conditions between + * the baking and file writing code */ + return OPERATOR_RUNNING_MODAL; } static int ptcache_bake_modal(bContext *C, wmOperator *op, const wmEvent *UNUSED(event)) { - Scene *scene = (Scene *) op->customdata; + Scene *scene = (Scene *)op->customdata; - /* no running blender, remove handler and pass through */ - if (0 == WM_jobs_test(CTX_wm_manager(C), scene, WM_JOB_TYPE_POINTCACHE)) { - return OPERATOR_FINISHED | OPERATOR_PASS_THROUGH; - } + /* no running blender, remove handler and pass through */ + if (0 == WM_jobs_test(CTX_wm_manager(C), scene, WM_JOB_TYPE_POINTCACHE)) { + return OPERATOR_FINISHED | OPERATOR_PASS_THROUGH; + } - return OPERATOR_PASS_THROUGH; + return OPERATOR_PASS_THROUGH; } static void ptcache_bake_cancel(bContext *C, wmOperator *op) { - wmWindowManager *wm = CTX_wm_manager(C); - Scene *scene = (Scene *) op->customdata; + wmWindowManager *wm = CTX_wm_manager(C); + Scene *scene = (Scene *)op->customdata; - /* kill on cancel, because job is using op->reports */ - WM_jobs_kill_type(wm, scene, WM_JOB_TYPE_POINTCACHE); + /* kill on cancel, because job is using op->reports */ + WM_jobs_kill_type(wm, scene, WM_JOB_TYPE_POINTCACHE); } static int ptcache_free_bake_all_exec(bContext *C, wmOperator *UNUSED(op)) { - Scene *scene = CTX_data_scene(C); - PTCacheID *pid; - ListBase pidlist; + Scene *scene = CTX_data_scene(C); + PTCacheID *pid; + ListBase pidlist; - FOREACH_SCENE_OBJECT_BEGIN(scene, ob) - { - BKE_ptcache_ids_from_object(&pidlist, ob, scene, MAX_DUPLI_RECUR); + FOREACH_SCENE_OBJECT_BEGIN (scene, ob) { + BKE_ptcache_ids_from_object(&pidlist, ob, scene, MAX_DUPLI_RECUR); - for (pid = pidlist.first; pid; pid = pid->next) { - ptcache_free_bake(pid->cache); - } + for (pid = pidlist.first; pid; pid = pid->next) { + ptcache_free_bake(pid->cache); + } - BLI_freelistN(&pidlist); + BLI_freelistN(&pidlist); - WM_event_add_notifier(C, NC_OBJECT|ND_POINTCACHE, ob); - } - FOREACH_SCENE_OBJECT_END; + WM_event_add_notifier(C, NC_OBJECT | ND_POINTCACHE, ob); + } + FOREACH_SCENE_OBJECT_END; - WM_event_add_notifier(C, NC_SCENE|ND_FRAME, scene); + WM_event_add_notifier(C, NC_SCENE | ND_FRAME, scene); - return OPERATOR_FINISHED; + return OPERATOR_FINISHED; } void PTCACHE_OT_bake_all(wmOperatorType *ot) { - /* identifiers */ - ot->name = "Bake All Physics"; - ot->description = "Bake all physics"; - ot->idname = "PTCACHE_OT_bake_all"; - - /* api callbacks */ - ot->exec = ptcache_bake_exec; - ot->invoke = ptcache_bake_invoke; - ot->modal = ptcache_bake_modal; - ot->cancel = ptcache_bake_cancel; - ot->poll = ptcache_bake_all_poll; - - /* flags */ - ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO; - - RNA_def_boolean(ot->srna, "bake", 1, "Bake", ""); + /* identifiers */ + ot->name = "Bake All Physics"; + ot->description = "Bake all physics"; + ot->idname = "PTCACHE_OT_bake_all"; + + /* api callbacks */ + ot->exec = ptcache_bake_exec; + ot->invoke = ptcache_bake_invoke; + ot->modal = ptcache_bake_modal; + ot->cancel = ptcache_bake_cancel; + ot->poll = ptcache_bake_all_poll; + + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + + RNA_def_boolean(ot->srna, "bake", 1, "Bake", ""); } void PTCACHE_OT_free_bake_all(wmOperatorType *ot) { - /* identifiers */ - ot->name = "Delete All Physics Bakes"; - ot->idname = "PTCACHE_OT_free_bake_all"; - ot->description = "Delete all baked caches of all objects in the current scene"; + /* identifiers */ + ot->name = "Delete All Physics Bakes"; + ot->idname = "PTCACHE_OT_free_bake_all"; + ot->description = "Delete all baked caches of all objects in the current scene"; - /* api callbacks */ - ot->exec = ptcache_free_bake_all_exec; - ot->poll = ptcache_bake_all_poll; + /* api callbacks */ + ot->exec = ptcache_free_bake_all_exec; + ot->poll = ptcache_bake_all_poll; - /* flags */ - ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO; + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } static int ptcache_free_bake_exec(bContext *C, wmOperator *UNUSED(op)) { - PointerRNA ptr= CTX_data_pointer_get_type(C, "point_cache", &RNA_PointCache); - PointCache *cache= ptr.data; - Object *ob= ptr.id.data; + PointerRNA ptr = CTX_data_pointer_get_type(C, "point_cache", &RNA_PointCache); + PointCache *cache = ptr.data; + Object *ob = ptr.id.data; - ptcache_free_bake(cache); + ptcache_free_bake(cache); - WM_event_add_notifier(C, NC_OBJECT|ND_POINTCACHE, ob); + WM_event_add_notifier(C, NC_OBJECT | ND_POINTCACHE, ob); - return OPERATOR_FINISHED; + return OPERATOR_FINISHED; } static int ptcache_bake_from_cache_exec(bContext *C, wmOperator *UNUSED(op)) { - PointerRNA ptr= CTX_data_pointer_get_type(C, "point_cache", &RNA_PointCache); - PointCache *cache= ptr.data; - Object *ob= ptr.id.data; + PointerRNA ptr = CTX_data_pointer_get_type(C, "point_cache", &RNA_PointCache); + PointCache *cache = ptr.data; + Object *ob = ptr.id.data; - cache->flag |= PTCACHE_BAKED; + cache->flag |= PTCACHE_BAKED; - WM_event_add_notifier(C, NC_OBJECT|ND_POINTCACHE, ob); + WM_event_add_notifier(C, NC_OBJECT | ND_POINTCACHE, ob); - return OPERATOR_FINISHED; + return OPERATOR_FINISHED; } void PTCACHE_OT_bake(wmOperatorType *ot) { - /* identifiers */ - ot->name = "Bake Physics"; - ot->description = "Bake physics"; - ot->idname = "PTCACHE_OT_bake"; - - /* api callbacks */ - ot->exec = ptcache_bake_exec; - ot->invoke = ptcache_bake_invoke; - ot->modal = ptcache_bake_modal; - ot->cancel = ptcache_bake_cancel; - ot->poll = ptcache_poll; - - /* flags */ - ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO; - - RNA_def_boolean(ot->srna, "bake", 0, "Bake", ""); + /* identifiers */ + ot->name = "Bake Physics"; + ot->description = "Bake physics"; + ot->idname = "PTCACHE_OT_bake"; + + /* api callbacks */ + ot->exec = ptcache_bake_exec; + ot->invoke = ptcache_bake_invoke; + ot->modal = ptcache_bake_modal; + ot->cancel = ptcache_bake_cancel; + ot->poll = ptcache_poll; + + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + + RNA_def_boolean(ot->srna, "bake", 0, "Bake", ""); } void PTCACHE_OT_free_bake(wmOperatorType *ot) { - /* identifiers */ - ot->name = "Delete Physics Bake"; - ot->description = "Delete physics bake"; - ot->idname = "PTCACHE_OT_free_bake"; + /* identifiers */ + ot->name = "Delete Physics Bake"; + ot->description = "Delete physics bake"; + ot->idname = "PTCACHE_OT_free_bake"; - /* api callbacks */ - ot->exec = ptcache_free_bake_exec; - ot->poll = ptcache_poll; + /* api callbacks */ + ot->exec = ptcache_free_bake_exec; + ot->poll = ptcache_poll; - /* flags */ - ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO; + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } void PTCACHE_OT_bake_from_cache(wmOperatorType *ot) { - /* identifiers */ - ot->name = "Bake From Cache"; - ot->description = "Bake from cache"; - ot->idname = "PTCACHE_OT_bake_from_cache"; + /* identifiers */ + ot->name = "Bake From Cache"; + ot->description = "Bake from cache"; + ot->idname = "PTCACHE_OT_bake_from_cache"; - /* api callbacks */ - ot->exec = ptcache_bake_from_cache_exec; - ot->poll = ptcache_poll; + /* api callbacks */ + ot->exec = ptcache_bake_from_cache_exec; + ot->poll = ptcache_poll; - /* flags */ - ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO; + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } static int ptcache_add_new_exec(bContext *C, wmOperator *UNUSED(op)) { - Scene *scene = CTX_data_scene(C); - PointerRNA ptr= CTX_data_pointer_get_type(C, "point_cache", &RNA_PointCache); - Object *ob= ptr.id.data; - PointCache *cache= ptr.data; - PTCacheID pid = BKE_ptcache_id_find(ob, scene, cache); - - if (pid.cache) { - PointCache *cache_new = BKE_ptcache_add(pid.ptcaches); - cache_new->step = pid.default_step; - *(pid.cache_ptr) = cache_new; - - DEG_id_tag_update(&ob->id, ID_RECALC_POINT_CACHE); - WM_event_add_notifier(C, NC_SCENE|ND_FRAME, scene); - WM_event_add_notifier(C, NC_OBJECT|ND_POINTCACHE, ob); - } - - return OPERATOR_FINISHED; + Scene *scene = CTX_data_scene(C); + PointerRNA ptr = CTX_data_pointer_get_type(C, "point_cache", &RNA_PointCache); + Object *ob = ptr.id.data; + PointCache *cache = ptr.data; + PTCacheID pid = BKE_ptcache_id_find(ob, scene, cache); + + if (pid.cache) { + PointCache *cache_new = BKE_ptcache_add(pid.ptcaches); + cache_new->step = pid.default_step; + *(pid.cache_ptr) = cache_new; + + DEG_id_tag_update(&ob->id, ID_RECALC_POINT_CACHE); + WM_event_add_notifier(C, NC_SCENE | ND_FRAME, scene); + WM_event_add_notifier(C, NC_OBJECT | ND_POINTCACHE, ob); + } + + return OPERATOR_FINISHED; } static int ptcache_remove_exec(bContext *C, wmOperator *UNUSED(op)) { - PointerRNA ptr= CTX_data_pointer_get_type(C, "point_cache", &RNA_PointCache); - Scene *scene= CTX_data_scene(C); - Object *ob= ptr.id.data; - PointCache *cache= ptr.data; - PTCacheID pid = BKE_ptcache_id_find(ob, scene, cache); - - /* don't delete last cache */ - if (pid.cache && pid.ptcaches->first != pid.ptcaches->last) { - BLI_remlink(pid.ptcaches, pid.cache); - BKE_ptcache_free(pid.cache); - *(pid.cache_ptr) = pid.ptcaches->first; - - DEG_id_tag_update(&ob->id, ID_RECALC_COPY_ON_WRITE); - WM_event_add_notifier(C, NC_OBJECT|ND_POINTCACHE, ob); - } - - return OPERATOR_FINISHED; + PointerRNA ptr = CTX_data_pointer_get_type(C, "point_cache", &RNA_PointCache); + Scene *scene = CTX_data_scene(C); + Object *ob = ptr.id.data; + PointCache *cache = ptr.data; + PTCacheID pid = BKE_ptcache_id_find(ob, scene, cache); + + /* don't delete last cache */ + if (pid.cache && pid.ptcaches->first != pid.ptcaches->last) { + BLI_remlink(pid.ptcaches, pid.cache); + BKE_ptcache_free(pid.cache); + *(pid.cache_ptr) = pid.ptcaches->first; + + DEG_id_tag_update(&ob->id, ID_RECALC_COPY_ON_WRITE); + WM_event_add_notifier(C, NC_OBJECT | ND_POINTCACHE, ob); + } + + return OPERATOR_FINISHED; } void PTCACHE_OT_add(wmOperatorType *ot) { - /* identifiers */ - ot->name = "Add New Cache"; - ot->description = "Add new cache"; - ot->idname = "PTCACHE_OT_add"; + /* identifiers */ + ot->name = "Add New Cache"; + ot->description = "Add new cache"; + ot->idname = "PTCACHE_OT_add"; - /* api callbacks */ - ot->exec = ptcache_add_new_exec; - ot->poll = ptcache_poll; + /* api callbacks */ + ot->exec = ptcache_add_new_exec; + ot->poll = ptcache_poll; - /* flags */ - ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO; + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } void PTCACHE_OT_remove(wmOperatorType *ot) { - /* identifiers */ - ot->name = "Delete Current Cache"; - ot->description = "Delete current cache"; - ot->idname = "PTCACHE_OT_remove"; + /* identifiers */ + ot->name = "Delete Current Cache"; + ot->description = "Delete current cache"; + ot->idname = "PTCACHE_OT_remove"; - /* api callbacks */ - ot->exec = ptcache_remove_exec; - ot->poll = ptcache_poll; + /* api callbacks */ + ot->exec = ptcache_remove_exec; + ot->poll = ptcache_poll; - /* flags */ - ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO; + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } diff --git a/source/blender/editors/physics/rigidbody_constraint.c b/source/blender/editors/physics/rigidbody_constraint.c index 499a1d0e2e5..2d2c90f9391 100644 --- a/source/blender/editors/physics/rigidbody_constraint.c +++ b/source/blender/editors/physics/rigidbody_constraint.c @@ -56,54 +56,55 @@ static bool ED_operator_rigidbody_con_active_poll(bContext *C) { - if (ED_operator_object_active_editable(C)) { - Object *ob = CTX_data_active_object(C); - return (ob && ob->rigidbody_constraint); - } - else - return 0; + if (ED_operator_object_active_editable(C)) { + Object *ob = CTX_data_active_object(C); + return (ob && ob->rigidbody_constraint); + } + else + return 0; } - -bool ED_rigidbody_constraint_add(Main *bmain, Scene *scene, Object *ob, int type, ReportList *reports) +bool ED_rigidbody_constraint_add( + Main *bmain, Scene *scene, Object *ob, int type, ReportList *reports) { - RigidBodyWorld *rbw = BKE_rigidbody_get_world(scene); - - /* check that object doesn't already have a constraint */ - if (ob->rigidbody_constraint) { - BKE_reportf(reports, RPT_INFO, "Object '%s' already has a Rigid Body Constraint", ob->id.name + 2); - return false; - } - /* create constraint group if it doesn't already exits */ - if (rbw->constraints == NULL) { - rbw->constraints = BKE_collection_add(bmain, NULL, "RigidBodyConstraints"); - id_fake_user_set(&rbw->constraints->id); - } - /* make rigidbody constraint settings */ - ob->rigidbody_constraint = BKE_rigidbody_create_constraint(scene, ob, type); - - /* add constraint to rigid body constraint group */ - BKE_collection_object_add(bmain, rbw->constraints, ob); - - DEG_relations_tag_update(bmain); - DEG_id_tag_update(&ob->id, ID_RECALC_TRANSFORM); - DEG_id_tag_update(&rbw->constraints->id, ID_RECALC_COPY_ON_WRITE); - - return true; + RigidBodyWorld *rbw = BKE_rigidbody_get_world(scene); + + /* check that object doesn't already have a constraint */ + if (ob->rigidbody_constraint) { + BKE_reportf( + reports, RPT_INFO, "Object '%s' already has a Rigid Body Constraint", ob->id.name + 2); + return false; + } + /* create constraint group if it doesn't already exits */ + if (rbw->constraints == NULL) { + rbw->constraints = BKE_collection_add(bmain, NULL, "RigidBodyConstraints"); + id_fake_user_set(&rbw->constraints->id); + } + /* make rigidbody constraint settings */ + ob->rigidbody_constraint = BKE_rigidbody_create_constraint(scene, ob, type); + + /* add constraint to rigid body constraint group */ + BKE_collection_object_add(bmain, rbw->constraints, ob); + + DEG_relations_tag_update(bmain); + DEG_id_tag_update(&ob->id, ID_RECALC_TRANSFORM); + DEG_id_tag_update(&rbw->constraints->id, ID_RECALC_COPY_ON_WRITE); + + return true; } void ED_rigidbody_constraint_remove(Main *bmain, Scene *scene, Object *ob) { - RigidBodyWorld *rbw = BKE_rigidbody_get_world(scene); + RigidBodyWorld *rbw = BKE_rigidbody_get_world(scene); - BKE_rigidbody_remove_constraint(scene, ob); - if (rbw) { - BKE_collection_object_remove(bmain, rbw->constraints, ob, false); - DEG_id_tag_update(&rbw->constraints->id, ID_RECALC_COPY_ON_WRITE); - } + BKE_rigidbody_remove_constraint(scene, ob); + if (rbw) { + BKE_collection_object_remove(bmain, rbw->constraints, ob, false); + DEG_id_tag_update(&rbw->constraints->id, ID_RECALC_COPY_ON_WRITE); + } - DEG_relations_tag_update(bmain); - DEG_id_tag_update(&ob->id, ID_RECALC_TRANSFORM); + DEG_relations_tag_update(bmain); + DEG_id_tag_update(&ob->id, ID_RECALC_TRANSFORM); } /* ********************************************** */ @@ -113,88 +114,93 @@ void ED_rigidbody_constraint_remove(Main *bmain, Scene *scene, Object *ob) static int rigidbody_con_add_exec(bContext *C, wmOperator *op) { - Main *bmain = CTX_data_main(C); - Scene *scene = CTX_data_scene(C); - ViewLayer *view_layer = CTX_data_view_layer(C); - RigidBodyWorld *rbw = BKE_rigidbody_get_world(scene); - Object *ob = OBACT(view_layer); - int type = RNA_enum_get(op->ptr, "type"); - bool changed; - - /* sanity checks */ - if (ELEM(NULL, scene, rbw)) { - BKE_report(op->reports, RPT_ERROR, "No Rigid Body World to add Rigid Body Constraint to"); - return OPERATOR_CANCELLED; - } - /* apply to active object */ - changed = ED_rigidbody_constraint_add(bmain, scene, ob, type, op->reports); - - if (changed) { - /* send updates */ - WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL); - - /* done */ - return OPERATOR_FINISHED; - } - else { - return OPERATOR_CANCELLED; - } + Main *bmain = CTX_data_main(C); + Scene *scene = CTX_data_scene(C); + ViewLayer *view_layer = CTX_data_view_layer(C); + RigidBodyWorld *rbw = BKE_rigidbody_get_world(scene); + Object *ob = OBACT(view_layer); + int type = RNA_enum_get(op->ptr, "type"); + bool changed; + + /* sanity checks */ + if (ELEM(NULL, scene, rbw)) { + BKE_report(op->reports, RPT_ERROR, "No Rigid Body World to add Rigid Body Constraint to"); + return OPERATOR_CANCELLED; + } + /* apply to active object */ + changed = ED_rigidbody_constraint_add(bmain, scene, ob, type, op->reports); + + if (changed) { + /* send updates */ + WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL); + + /* done */ + return OPERATOR_FINISHED; + } + else { + return OPERATOR_CANCELLED; + } } void RIGIDBODY_OT_constraint_add(wmOperatorType *ot) { - /* identifiers */ - ot->idname = "RIGIDBODY_OT_constraint_add"; - ot->name = "Add Rigid Body Constraint"; - ot->description = "Add Rigid Body Constraint to active object"; - - /* callbacks */ - ot->exec = rigidbody_con_add_exec; - ot->poll = ED_operator_object_active_editable; - - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; - - /* properties */ - ot->prop = RNA_def_enum(ot->srna, "type", rna_enum_rigidbody_constraint_type_items, RBC_TYPE_FIXED, "Rigid Body Constraint Type", ""); + /* identifiers */ + ot->idname = "RIGIDBODY_OT_constraint_add"; + ot->name = "Add Rigid Body Constraint"; + ot->description = "Add Rigid Body Constraint to active object"; + + /* callbacks */ + ot->exec = rigidbody_con_add_exec; + ot->poll = ED_operator_object_active_editable; + + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + + /* properties */ + ot->prop = RNA_def_enum(ot->srna, + "type", + rna_enum_rigidbody_constraint_type_items, + RBC_TYPE_FIXED, + "Rigid Body Constraint Type", + ""); } /* ************ Remove Rigid Body Constraint ************** */ static int rigidbody_con_remove_exec(bContext *C, wmOperator *op) { - Main *bmain = CTX_data_main(C); - Scene *scene = CTX_data_scene(C); - ViewLayer *view_layer = CTX_data_view_layer(C); - Object *ob = OBACT(view_layer); - - /* apply to active object */ - if (ELEM(NULL, ob, ob->rigidbody_constraint)) { - BKE_report(op->reports, RPT_ERROR, "Object has no Rigid Body Constraint to remove"); - return OPERATOR_CANCELLED; - } - else { - ED_rigidbody_constraint_remove(bmain, scene, ob); - } - - /* send updates */ - WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL); - - /* done */ - return OPERATOR_FINISHED; + Main *bmain = CTX_data_main(C); + Scene *scene = CTX_data_scene(C); + ViewLayer *view_layer = CTX_data_view_layer(C); + Object *ob = OBACT(view_layer); + + /* apply to active object */ + if (ELEM(NULL, ob, ob->rigidbody_constraint)) { + BKE_report(op->reports, RPT_ERROR, "Object has no Rigid Body Constraint to remove"); + return OPERATOR_CANCELLED; + } + else { + ED_rigidbody_constraint_remove(bmain, scene, ob); + } + + /* send updates */ + WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL); + + /* done */ + return OPERATOR_FINISHED; } void RIGIDBODY_OT_constraint_remove(wmOperatorType *ot) { - /* identifiers */ - ot->idname = "RIGIDBODY_OT_constraint_remove"; - ot->name = "Remove Rigid Body Constraint"; - ot->description = "Remove Rigid Body Constraint from Object"; + /* identifiers */ + ot->idname = "RIGIDBODY_OT_constraint_remove"; + ot->name = "Remove Rigid Body Constraint"; + ot->description = "Remove Rigid Body Constraint from Object"; - /* callbacks */ - ot->exec = rigidbody_con_remove_exec; - ot->poll = ED_operator_rigidbody_con_active_poll; + /* callbacks */ + ot->exec = rigidbody_con_remove_exec; + ot->poll = ED_operator_rigidbody_con_active_poll; - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } diff --git a/source/blender/editors/physics/rigidbody_object.c b/source/blender/editors/physics/rigidbody_object.c index fd76a1b18f4..2914127f8d8 100644 --- a/source/blender/editors/physics/rigidbody_object.c +++ b/source/blender/editors/physics/rigidbody_object.c @@ -25,7 +25,6 @@ #include #include - #include "DNA_object_types.h" #include "DNA_rigidbody_types.h" #include "DNA_scene_types.h" @@ -63,73 +62,73 @@ static bool ED_operator_rigidbody_active_poll(bContext *C) { - if (ED_operator_object_active_editable(C)) { - Object *ob = ED_object_active_context(C); - return (ob && ob->rigidbody_object); - } - else - return 0; + if (ED_operator_object_active_editable(C)) { + Object *ob = ED_object_active_context(C); + return (ob && ob->rigidbody_object); + } + else + return 0; } static bool ED_operator_rigidbody_add_poll(bContext *C) { - if (ED_operator_object_active_editable(C)) { - Object *ob = ED_object_active_context(C); - return (ob && ob->type == OB_MESH); - } - else - return 0; + if (ED_operator_object_active_editable(C)) { + Object *ob = ED_object_active_context(C); + return (ob && ob->type == OB_MESH); + } + else + return 0; } /* ----------------- */ bool ED_rigidbody_object_add(Main *bmain, Scene *scene, Object *ob, int type, ReportList *reports) { - RigidBodyWorld *rbw = BKE_rigidbody_get_world(scene); - - if (ob->type != OB_MESH) { - BKE_report(reports, RPT_ERROR, "Can't add Rigid Body to non mesh object"); - return false; - } - - /* Add rigid body world and group if they don't exist for convenience */ - if (rbw == NULL) { - rbw = BKE_rigidbody_create_world(scene); - if (rbw == NULL) { - BKE_report(reports, RPT_ERROR, "Can't create Rigid Body world"); - return false; - } - BKE_rigidbody_validate_sim_world(scene, rbw, false); - scene->rigidbody_world = rbw; - } - if (rbw->group == NULL) { - rbw->group = BKE_collection_add(bmain, NULL, "RigidBodyWorld"); - id_fake_user_set(&rbw->group->id); - } - - /* make rigidbody object settings */ - if (ob->rigidbody_object == NULL) { - ob->rigidbody_object = BKE_rigidbody_create_object(scene, ob, type); - } - ob->rigidbody_object->type = type; - ob->rigidbody_object->flag |= RBO_FLAG_NEEDS_VALIDATE; - - /* add object to rigid body group */ - BKE_collection_object_add(bmain, rbw->group, ob); - - DEG_relations_tag_update(bmain); - DEG_id_tag_update(&ob->id, ID_RECALC_TRANSFORM); - DEG_id_tag_update(&rbw->group->id, ID_RECALC_COPY_ON_WRITE); - - return true; + RigidBodyWorld *rbw = BKE_rigidbody_get_world(scene); + + if (ob->type != OB_MESH) { + BKE_report(reports, RPT_ERROR, "Can't add Rigid Body to non mesh object"); + return false; + } + + /* Add rigid body world and group if they don't exist for convenience */ + if (rbw == NULL) { + rbw = BKE_rigidbody_create_world(scene); + if (rbw == NULL) { + BKE_report(reports, RPT_ERROR, "Can't create Rigid Body world"); + return false; + } + BKE_rigidbody_validate_sim_world(scene, rbw, false); + scene->rigidbody_world = rbw; + } + if (rbw->group == NULL) { + rbw->group = BKE_collection_add(bmain, NULL, "RigidBodyWorld"); + id_fake_user_set(&rbw->group->id); + } + + /* make rigidbody object settings */ + if (ob->rigidbody_object == NULL) { + ob->rigidbody_object = BKE_rigidbody_create_object(scene, ob, type); + } + ob->rigidbody_object->type = type; + ob->rigidbody_object->flag |= RBO_FLAG_NEEDS_VALIDATE; + + /* add object to rigid body group */ + BKE_collection_object_add(bmain, rbw->group, ob); + + DEG_relations_tag_update(bmain); + DEG_id_tag_update(&ob->id, ID_RECALC_TRANSFORM); + DEG_id_tag_update(&rbw->group->id, ID_RECALC_COPY_ON_WRITE); + + return true; } void ED_rigidbody_object_remove(Main *bmain, Scene *scene, Object *ob) { - BKE_rigidbody_remove_object(bmain, scene, ob); + BKE_rigidbody_remove_object(bmain, scene, ob); - DEG_relations_tag_update(bmain); - DEG_id_tag_update(&ob->id, ID_RECALC_TRANSFORM); + DEG_relations_tag_update(bmain); + DEG_id_tag_update(&ob->id, ID_RECALC_TRANSFORM); } /* ********************************************** */ @@ -139,88 +138,93 @@ void ED_rigidbody_object_remove(Main *bmain, Scene *scene, Object *ob) static int rigidbody_object_add_exec(bContext *C, wmOperator *op) { - Main *bmain = CTX_data_main(C); - Scene *scene = CTX_data_scene(C); - Object *ob = ED_object_active_context(C); - int type = RNA_enum_get(op->ptr, "type"); - bool changed; - - /* apply to active object */ - changed = ED_rigidbody_object_add(bmain, scene, ob, type, op->reports); - - if (changed) { - /* send updates */ - WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL); - WM_event_add_notifier(C, NC_OBJECT | ND_POINTCACHE, NULL); - - /* done */ - return OPERATOR_FINISHED; - } - else { - return OPERATOR_CANCELLED; - } + Main *bmain = CTX_data_main(C); + Scene *scene = CTX_data_scene(C); + Object *ob = ED_object_active_context(C); + int type = RNA_enum_get(op->ptr, "type"); + bool changed; + + /* apply to active object */ + changed = ED_rigidbody_object_add(bmain, scene, ob, type, op->reports); + + if (changed) { + /* send updates */ + WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL); + WM_event_add_notifier(C, NC_OBJECT | ND_POINTCACHE, NULL); + + /* done */ + return OPERATOR_FINISHED; + } + else { + return OPERATOR_CANCELLED; + } } void RIGIDBODY_OT_object_add(wmOperatorType *ot) { - /* identifiers */ - ot->idname = "RIGIDBODY_OT_object_add"; - ot->name = "Add Rigid Body"; - ot->description = "Add active object as Rigid Body"; - - /* callbacks */ - ot->exec = rigidbody_object_add_exec; - ot->poll = ED_operator_rigidbody_add_poll; - - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; - - /* properties */ - ot->prop = RNA_def_enum(ot->srna, "type", rna_enum_rigidbody_object_type_items, RBO_TYPE_ACTIVE, "Rigid Body Type", ""); + /* identifiers */ + ot->idname = "RIGIDBODY_OT_object_add"; + ot->name = "Add Rigid Body"; + ot->description = "Add active object as Rigid Body"; + + /* callbacks */ + ot->exec = rigidbody_object_add_exec; + ot->poll = ED_operator_rigidbody_add_poll; + + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + + /* properties */ + ot->prop = RNA_def_enum(ot->srna, + "type", + rna_enum_rigidbody_object_type_items, + RBO_TYPE_ACTIVE, + "Rigid Body Type", + ""); } /* ************ Remove Rigid Body ************** */ static int rigidbody_object_remove_exec(bContext *C, wmOperator *op) { - Main *bmain = CTX_data_main(C); - Scene *scene = CTX_data_scene(C); - Object *ob = ED_object_active_context(C); - bool changed = false; - - /* apply to active object */ - if (!ELEM(NULL, ob, ob->rigidbody_object)) { - ED_rigidbody_object_remove(bmain, scene, ob); - changed = true; - } - - if (changed) { - /* send updates */ - WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL); - WM_event_add_notifier(C, NC_OBJECT | ND_POINTCACHE, NULL); - - /* done */ - return OPERATOR_FINISHED; - } - else { - BKE_report(op->reports, RPT_ERROR, "Object has no Rigid Body settings to remove"); - return OPERATOR_CANCELLED; - } + Main *bmain = CTX_data_main(C); + Scene *scene = CTX_data_scene(C); + Object *ob = ED_object_active_context(C); + bool changed = false; + + /* apply to active object */ + if (!ELEM(NULL, ob, ob->rigidbody_object)) { + ED_rigidbody_object_remove(bmain, scene, ob); + changed = true; + } + + if (changed) { + /* send updates */ + WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL); + WM_event_add_notifier(C, NC_OBJECT | ND_POINTCACHE, NULL); + + /* done */ + return OPERATOR_FINISHED; + } + else { + BKE_report(op->reports, RPT_ERROR, "Object has no Rigid Body settings to remove"); + return OPERATOR_CANCELLED; + } } void RIGIDBODY_OT_object_remove(wmOperatorType *ot) { - /* identifiers */ - ot->idname = "RIGIDBODY_OT_object_remove"; - ot->name = "Remove Rigid Body"; - ot->description = "Remove Rigid Body settings from Object"; + /* identifiers */ + ot->idname = "RIGIDBODY_OT_object_remove"; + ot->name = "Remove Rigid Body"; + ot->description = "Remove Rigid Body settings from Object"; - /* callbacks */ - ot->exec = rigidbody_object_remove_exec; - ot->poll = ED_operator_rigidbody_active_poll; + /* callbacks */ + ot->exec = rigidbody_object_remove_exec; + ot->poll = ED_operator_rigidbody_active_poll; - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } /* ********************************************** */ @@ -230,92 +234,96 @@ void RIGIDBODY_OT_object_remove(wmOperatorType *ot) static int rigidbody_objects_add_exec(bContext *C, wmOperator *op) { - Main *bmain = CTX_data_main(C); - Scene *scene = CTX_data_scene(C); - int type = RNA_enum_get(op->ptr, "type"); - bool changed = false; - - /* create rigid body objects and add them to the world's group */ - CTX_DATA_BEGIN(C, Object *, ob, selected_objects) { - changed |= ED_rigidbody_object_add(bmain, scene, ob, type, op->reports); - } - CTX_DATA_END; - - if (changed) { - /* send updates */ - WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL); - WM_event_add_notifier(C, NC_OBJECT | ND_POINTCACHE, NULL); - - /* done */ - return OPERATOR_FINISHED; - } - else { - return OPERATOR_CANCELLED; - } + Main *bmain = CTX_data_main(C); + Scene *scene = CTX_data_scene(C); + int type = RNA_enum_get(op->ptr, "type"); + bool changed = false; + + /* create rigid body objects and add them to the world's group */ + CTX_DATA_BEGIN (C, Object *, ob, selected_objects) { + changed |= ED_rigidbody_object_add(bmain, scene, ob, type, op->reports); + } + CTX_DATA_END; + + if (changed) { + /* send updates */ + WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL); + WM_event_add_notifier(C, NC_OBJECT | ND_POINTCACHE, NULL); + + /* done */ + return OPERATOR_FINISHED; + } + else { + return OPERATOR_CANCELLED; + } } void RIGIDBODY_OT_objects_add(wmOperatorType *ot) { - /* identifiers */ - ot->idname = "RIGIDBODY_OT_objects_add"; - ot->name = "Add Rigid Bodies"; - ot->description = "Add selected objects as Rigid Bodies"; - - /* callbacks */ - ot->exec = rigidbody_objects_add_exec; - ot->poll = ED_operator_rigidbody_add_poll; - - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; - - /* properties */ - ot->prop = RNA_def_enum(ot->srna, "type", rna_enum_rigidbody_object_type_items, RBO_TYPE_ACTIVE, "Rigid Body Type", ""); + /* identifiers */ + ot->idname = "RIGIDBODY_OT_objects_add"; + ot->name = "Add Rigid Bodies"; + ot->description = "Add selected objects as Rigid Bodies"; + + /* callbacks */ + ot->exec = rigidbody_objects_add_exec; + ot->poll = ED_operator_rigidbody_add_poll; + + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + + /* properties */ + ot->prop = RNA_def_enum(ot->srna, + "type", + rna_enum_rigidbody_object_type_items, + RBO_TYPE_ACTIVE, + "Rigid Body Type", + ""); } /* ************ Remove Rigid Bodies ************** */ static int rigidbody_objects_remove_exec(bContext *C, wmOperator *UNUSED(op)) { - Main *bmain = CTX_data_main(C); - Scene *scene = CTX_data_scene(C); - bool changed = false; - - /* apply this to all selected objects... */ - CTX_DATA_BEGIN(C, Object *, ob, selected_objects) - { - if (ob->rigidbody_object) { - ED_rigidbody_object_remove(bmain, scene, ob); - changed = true; - } - } - CTX_DATA_END; - - if (changed) { - /* send updates */ - WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL); - WM_event_add_notifier(C, NC_OBJECT | ND_POINTCACHE, NULL); - - /* done */ - return OPERATOR_FINISHED; - } - else { - return OPERATOR_CANCELLED; - } + Main *bmain = CTX_data_main(C); + Scene *scene = CTX_data_scene(C); + bool changed = false; + + /* apply this to all selected objects... */ + CTX_DATA_BEGIN (C, Object *, ob, selected_objects) { + if (ob->rigidbody_object) { + ED_rigidbody_object_remove(bmain, scene, ob); + changed = true; + } + } + CTX_DATA_END; + + if (changed) { + /* send updates */ + WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL); + WM_event_add_notifier(C, NC_OBJECT | ND_POINTCACHE, NULL); + + /* done */ + return OPERATOR_FINISHED; + } + else { + return OPERATOR_CANCELLED; + } } void RIGIDBODY_OT_objects_remove(wmOperatorType *ot) { - /* identifiers */ - ot->idname = "RIGIDBODY_OT_objects_remove"; - ot->name = "Remove Rigid Bodies"; - ot->description = "Remove selected objects from Rigid Body simulation"; + /* identifiers */ + ot->idname = "RIGIDBODY_OT_objects_remove"; + ot->name = "Remove Rigid Bodies"; + ot->description = "Remove selected objects from Rigid Body simulation"; - /* callbacks */ - ot->exec = rigidbody_objects_remove_exec; - ot->poll = ED_operator_scene_editable; + /* callbacks */ + ot->exec = rigidbody_objects_remove_exec; + ot->poll = ED_operator_scene_editable; - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } /* ********************************************** */ @@ -325,64 +333,68 @@ void RIGIDBODY_OT_objects_remove(wmOperatorType *ot) static int rigidbody_objects_shape_change_exec(bContext *C, wmOperator *op) { - int shape = RNA_enum_get(op->ptr, "type"); - bool changed = false; - - /* apply this to all selected objects... */ - CTX_DATA_BEGIN(C, Object *, ob, selected_objects) - { - if (ob->rigidbody_object) { - PointerRNA ptr; - - /* use RNA-system to change the property and perform all necessary changes */ - RNA_pointer_create(&ob->id, &RNA_RigidBodyObject, ob->rigidbody_object, &ptr); - RNA_enum_set(&ptr, "collision_shape", shape); - - DEG_id_tag_update(&ob->id, ID_RECALC_TRANSFORM); - - changed = true; - } - } - CTX_DATA_END; - - if (changed) { - /* send updates */ - WM_event_add_notifier(C, NC_OBJECT | ND_POINTCACHE, NULL); - WM_event_add_notifier(C, NC_SPACE | ND_SPACE_VIEW3D, NULL); - - /* done */ - return OPERATOR_FINISHED; - } - else { - return OPERATOR_CANCELLED; - } + int shape = RNA_enum_get(op->ptr, "type"); + bool changed = false; + + /* apply this to all selected objects... */ + CTX_DATA_BEGIN (C, Object *, ob, selected_objects) { + if (ob->rigidbody_object) { + PointerRNA ptr; + + /* use RNA-system to change the property and perform all necessary changes */ + RNA_pointer_create(&ob->id, &RNA_RigidBodyObject, ob->rigidbody_object, &ptr); + RNA_enum_set(&ptr, "collision_shape", shape); + + DEG_id_tag_update(&ob->id, ID_RECALC_TRANSFORM); + + changed = true; + } + } + CTX_DATA_END; + + if (changed) { + /* send updates */ + WM_event_add_notifier(C, NC_OBJECT | ND_POINTCACHE, NULL); + WM_event_add_notifier(C, NC_SPACE | ND_SPACE_VIEW3D, NULL); + + /* done */ + return OPERATOR_FINISHED; + } + else { + return OPERATOR_CANCELLED; + } } void RIGIDBODY_OT_shape_change(wmOperatorType *ot) { - /* identifiers */ - ot->idname = "RIGIDBODY_OT_shape_change"; - ot->name = "Change Collision Shape"; - ot->description = "Change collision shapes for selected Rigid Body Objects"; - - /* callbacks */ - ot->invoke = WM_menu_invoke; - ot->exec = rigidbody_objects_shape_change_exec; - ot->poll = ED_operator_scene_editable; - - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; - - /* properties */ - ot->prop = RNA_def_enum(ot->srna, "type", rna_enum_rigidbody_object_shape_items, RB_SHAPE_TRIMESH, "Rigid Body Shape", ""); + /* identifiers */ + ot->idname = "RIGIDBODY_OT_shape_change"; + ot->name = "Change Collision Shape"; + ot->description = "Change collision shapes for selected Rigid Body Objects"; + + /* callbacks */ + ot->invoke = WM_menu_invoke; + ot->exec = rigidbody_objects_shape_change_exec; + ot->poll = ED_operator_scene_editable; + + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + + /* properties */ + ot->prop = RNA_def_enum(ot->srna, + "type", + rna_enum_rigidbody_object_shape_items, + RB_SHAPE_TRIMESH, + "Rigid Body Shape", + ""); } /* ************ Calculate Mass ************** */ /* Entry in material density table */ typedef struct rbMaterialDensityItem { - const char *name; /* Name of material */ - float density; /* Density (kg/m^3) */ + const char *name; /* Name of material */ + float density; /* Density (kg/m^3) */ } rbMaterialDensityItem; /* Preset density values for materials (kg/m^3) @@ -392,184 +404,194 @@ typedef struct rbMaterialDensityItem { * 3) http://www.avlandesign.com/density_metal.htm */ static rbMaterialDensityItem RB_MATERIAL_DENSITY_TABLE[] = { - {N_("Air"), 1.0f}, /* not quite; adapted from 1.43 for oxygen for use as default */ - {N_("Acrylic"), 1400.0f}, - {N_("Asphalt (Crushed)"), 721.0f}, - {N_("Bark"), 240.0f}, - {N_("Beans (Cocoa)"), 593.0f}, - {N_("Beans (Soy)"), 721.0f}, - {N_("Brick (Pressed)"), 2400.0f}, - {N_("Brick (Common)"), 2000.0f}, - {N_("Brick (Soft)"), 1600.0f}, - {N_("Brass"), 8216.0f}, - {N_("Bronze"), 8860.0f}, - {N_("Carbon (Solid)"), 2146.0f}, - {N_("Cardboard"), 689.0f}, - {N_("Cast Iron"), 7150.0f}, - /* {N_("Cement"), 1442.0f}, */ - {N_("Chalk (Solid)"), 2499.0f}, - /* {N_("Coffee (Fresh/Roast)"), ~500}, */ - {N_("Concrete"), 2320.0f}, - {N_("Charcoal"), 208.0f}, - {N_("Cork"), 240.0f}, - {N_("Copper"), 8933.0f}, - {N_("Garbage"), 481.0f}, - {N_("Glass (Broken)"), 1940.0f}, - {N_("Glass (Solid)"), 2190.0f}, - {N_("Gold"), 19282.0f}, - {N_("Granite (Broken)"), 1650.0f}, - {N_("Granite (Solid)"), 2691.0f}, - {N_("Gravel"), 2780.0f}, - {N_("Ice (Crushed)"), 593.0f}, - {N_("Ice (Solid)"), 919.0f}, - {N_("Iron"), 7874.0f}, - {N_("Lead"), 11342.0f}, - {N_("Limestone (Broken)"), 1554.0f}, - {N_("Limestone (Solid)"), 2611.0f}, - {N_("Marble (Broken)"), 1570.0f}, - {N_("Marble (Solid)"), 2563.0f}, - {N_("Paper"), 1201.0f}, - {N_("Peanuts (Shelled)"), 641.0f}, - {N_("Peanuts (Not Shelled)"), 272.0f}, - {N_("Plaster"), 849.0f}, - {N_("Plastic"), 1200.0f}, - {N_("Polystyrene"), 1050.0f}, - {N_("Rubber"), 1522.0f}, - {N_("Silver"), 10501.0f}, - {N_("Steel"), 7860.0f}, - {N_("Stone"), 2515.0f}, - {N_("Stone (Crushed)"), 1602.0f}, - {N_("Timber"), 610.0f}, + {N_("Air"), 1.0f}, /* not quite; adapted from 1.43 for oxygen for use as default */ + {N_("Acrylic"), 1400.0f}, + {N_("Asphalt (Crushed)"), 721.0f}, + {N_("Bark"), 240.0f}, + {N_("Beans (Cocoa)"), 593.0f}, + {N_("Beans (Soy)"), 721.0f}, + {N_("Brick (Pressed)"), 2400.0f}, + {N_("Brick (Common)"), 2000.0f}, + {N_("Brick (Soft)"), 1600.0f}, + {N_("Brass"), 8216.0f}, + {N_("Bronze"), 8860.0f}, + {N_("Carbon (Solid)"), 2146.0f}, + {N_("Cardboard"), 689.0f}, + {N_("Cast Iron"), 7150.0f}, + /* {N_("Cement"), 1442.0f}, */ + {N_("Chalk (Solid)"), 2499.0f}, + /* {N_("Coffee (Fresh/Roast)"), ~500}, */ + {N_("Concrete"), 2320.0f}, + {N_("Charcoal"), 208.0f}, + {N_("Cork"), 240.0f}, + {N_("Copper"), 8933.0f}, + {N_("Garbage"), 481.0f}, + {N_("Glass (Broken)"), 1940.0f}, + {N_("Glass (Solid)"), 2190.0f}, + {N_("Gold"), 19282.0f}, + {N_("Granite (Broken)"), 1650.0f}, + {N_("Granite (Solid)"), 2691.0f}, + {N_("Gravel"), 2780.0f}, + {N_("Ice (Crushed)"), 593.0f}, + {N_("Ice (Solid)"), 919.0f}, + {N_("Iron"), 7874.0f}, + {N_("Lead"), 11342.0f}, + {N_("Limestone (Broken)"), 1554.0f}, + {N_("Limestone (Solid)"), 2611.0f}, + {N_("Marble (Broken)"), 1570.0f}, + {N_("Marble (Solid)"), 2563.0f}, + {N_("Paper"), 1201.0f}, + {N_("Peanuts (Shelled)"), 641.0f}, + {N_("Peanuts (Not Shelled)"), 272.0f}, + {N_("Plaster"), 849.0f}, + {N_("Plastic"), 1200.0f}, + {N_("Polystyrene"), 1050.0f}, + {N_("Rubber"), 1522.0f}, + {N_("Silver"), 10501.0f}, + {N_("Steel"), 7860.0f}, + {N_("Stone"), 2515.0f}, + {N_("Stone (Crushed)"), 1602.0f}, + {N_("Timber"), 610.0f}, }; -static const int NUM_RB_MATERIAL_PRESETS = sizeof(RB_MATERIAL_DENSITY_TABLE) / sizeof(rbMaterialDensityItem); - +static const int NUM_RB_MATERIAL_PRESETS = sizeof(RB_MATERIAL_DENSITY_TABLE) / + sizeof(rbMaterialDensityItem); /* dynamically generate list of items * - Although there is a runtime cost, this has a lower maintenance cost * in the long run than other two-list solutions... */ -static const EnumPropertyItem *rigidbody_materials_itemf(bContext *UNUSED(C), PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free) +static const EnumPropertyItem *rigidbody_materials_itemf(bContext *UNUSED(C), + PointerRNA *UNUSED(ptr), + PropertyRNA *UNUSED(prop), + bool *r_free) { - EnumPropertyItem item_tmp = {0}; - EnumPropertyItem *item = NULL; - int totitem = 0; - int i = 0; - - /* add each preset to the list */ - for (i = 0; i < NUM_RB_MATERIAL_PRESETS; i++) { - rbMaterialDensityItem *preset = &RB_MATERIAL_DENSITY_TABLE[i]; - - item_tmp.identifier = preset->name; - item_tmp.name = IFACE_(preset->name); - item_tmp.value = i; - RNA_enum_item_add(&item, &totitem, &item_tmp); - } - - /* add special "custom" entry to the end of the list */ - { - item_tmp.identifier = "Custom"; - item_tmp.name = IFACE_("Custom"); - item_tmp.value = -1; - RNA_enum_item_add(&item, &totitem, &item_tmp); - } - - RNA_enum_item_end(&item, &totitem); - *r_free = true; - - return item; + EnumPropertyItem item_tmp = {0}; + EnumPropertyItem *item = NULL; + int totitem = 0; + int i = 0; + + /* add each preset to the list */ + for (i = 0; i < NUM_RB_MATERIAL_PRESETS; i++) { + rbMaterialDensityItem *preset = &RB_MATERIAL_DENSITY_TABLE[i]; + + item_tmp.identifier = preset->name; + item_tmp.name = IFACE_(preset->name); + item_tmp.value = i; + RNA_enum_item_add(&item, &totitem, &item_tmp); + } + + /* add special "custom" entry to the end of the list */ + { + item_tmp.identifier = "Custom"; + item_tmp.name = IFACE_("Custom"); + item_tmp.value = -1; + RNA_enum_item_add(&item, &totitem, &item_tmp); + } + + RNA_enum_item_end(&item, &totitem); + *r_free = true; + + return item; } /* ------------------------------------------ */ static int rigidbody_objects_calc_mass_exec(bContext *C, wmOperator *op) { - Depsgraph *depsgraph = CTX_data_depsgraph(C); - int material = RNA_enum_get(op->ptr, "material"); - float density; - bool changed = false; - - /* get density (kg/m^3) to apply */ - if (material >= 0) { - /* get density from table, and store in props for later repeating */ - if (material >= NUM_RB_MATERIAL_PRESETS) - material = 0; - - density = RB_MATERIAL_DENSITY_TABLE[material].density; - RNA_float_set(op->ptr, "density", density); - } - else { - /* custom - grab from whatever value is set */ - density = RNA_float_get(op->ptr, "density"); - } - - /* apply this to all selected objects (with rigidbodies)... */ - CTX_DATA_BEGIN(C, Object *, ob, selected_objects) - { - if (ob->rigidbody_object) { - PointerRNA ptr; - - float volume; /* m^3 */ - float mass; /* kg */ - - /* mass is calculated from the approximate volume of the object, - * and the density of the material we're simulating - */ - Object *ob_eval = DEG_get_evaluated_object(depsgraph, ob); - BKE_rigidbody_calc_volume(ob_eval, &volume); - mass = volume * density; - - /* use RNA-system to change the property and perform all necessary changes */ - RNA_pointer_create(&ob->id, &RNA_RigidBodyObject, ob->rigidbody_object, &ptr); - RNA_float_set(&ptr, "mass", mass); - - DEG_id_tag_update(&ob->id, ID_RECALC_TRANSFORM); - - changed = true; - } - } - CTX_DATA_END; - - if (changed) { - /* send updates */ - WM_event_add_notifier(C, NC_OBJECT | ND_POINTCACHE, NULL); - - /* done */ - return OPERATOR_FINISHED; - } - else { - return OPERATOR_CANCELLED; - } + Depsgraph *depsgraph = CTX_data_depsgraph(C); + int material = RNA_enum_get(op->ptr, "material"); + float density; + bool changed = false; + + /* get density (kg/m^3) to apply */ + if (material >= 0) { + /* get density from table, and store in props for later repeating */ + if (material >= NUM_RB_MATERIAL_PRESETS) + material = 0; + + density = RB_MATERIAL_DENSITY_TABLE[material].density; + RNA_float_set(op->ptr, "density", density); + } + else { + /* custom - grab from whatever value is set */ + density = RNA_float_get(op->ptr, "density"); + } + + /* apply this to all selected objects (with rigidbodies)... */ + CTX_DATA_BEGIN (C, Object *, ob, selected_objects) { + if (ob->rigidbody_object) { + PointerRNA ptr; + + float volume; /* m^3 */ + float mass; /* kg */ + + /* mass is calculated from the approximate volume of the object, + * and the density of the material we're simulating + */ + Object *ob_eval = DEG_get_evaluated_object(depsgraph, ob); + BKE_rigidbody_calc_volume(ob_eval, &volume); + mass = volume * density; + + /* use RNA-system to change the property and perform all necessary changes */ + RNA_pointer_create(&ob->id, &RNA_RigidBodyObject, ob->rigidbody_object, &ptr); + RNA_float_set(&ptr, "mass", mass); + + DEG_id_tag_update(&ob->id, ID_RECALC_TRANSFORM); + + changed = true; + } + } + CTX_DATA_END; + + if (changed) { + /* send updates */ + WM_event_add_notifier(C, NC_OBJECT | ND_POINTCACHE, NULL); + + /* done */ + return OPERATOR_FINISHED; + } + else { + return OPERATOR_CANCELLED; + } } void RIGIDBODY_OT_mass_calculate(wmOperatorType *ot) { - PropertyRNA *prop; - - /* identifiers */ - ot->idname = "RIGIDBODY_OT_mass_calculate"; - ot->name = "Calculate Mass"; - ot->description = "Automatically calculate mass values for Rigid Body Objects based on volume"; - - /* callbacks */ - ot->invoke = WM_menu_invoke; // XXX - ot->exec = rigidbody_objects_calc_mass_exec; - ot->poll = ED_operator_scene_editable; - - /* flags */ - ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_USE_EVAL_DATA; - - /* properties */ - ot->prop = prop = RNA_def_enum(ot->srna, "material", - DummyRNA_DEFAULT_items, 0, - "Material Preset", - "Type of material that objects are made of (determines material density)"); - RNA_def_enum_funcs(prop, rigidbody_materials_itemf); - RNA_def_property_flag(prop, PROP_ENUM_NO_TRANSLATE); - - RNA_def_float(ot->srna, "density", 1.0, FLT_MIN, FLT_MAX, - "Density", - "Custom density value (kg/m^3) to use instead of material preset", - 1.0f, 2500.0f); + PropertyRNA *prop; + + /* identifiers */ + ot->idname = "RIGIDBODY_OT_mass_calculate"; + ot->name = "Calculate Mass"; + ot->description = "Automatically calculate mass values for Rigid Body Objects based on volume"; + + /* callbacks */ + ot->invoke = WM_menu_invoke; // XXX + ot->exec = rigidbody_objects_calc_mass_exec; + ot->poll = ED_operator_scene_editable; + + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_USE_EVAL_DATA; + + /* properties */ + ot->prop = prop = RNA_def_enum( + ot->srna, + "material", + DummyRNA_DEFAULT_items, + 0, + "Material Preset", + "Type of material that objects are made of (determines material density)"); + RNA_def_enum_funcs(prop, rigidbody_materials_itemf); + RNA_def_property_flag(prop, PROP_ENUM_NO_TRANSLATE); + + RNA_def_float(ot->srna, + "density", + 1.0, + FLT_MIN, + FLT_MAX, + "Density", + "Custom density value (kg/m^3) to use instead of material preset", + 1.0f, + 2500.0f); } /* ********************************************** */ diff --git a/source/blender/editors/physics/rigidbody_world.c b/source/blender/editors/physics/rigidbody_world.c index b9049f79d0c..179a5a513f4 100644 --- a/source/blender/editors/physics/rigidbody_world.c +++ b/source/blender/editors/physics/rigidbody_world.c @@ -56,13 +56,13 @@ /* check if there is an active rigid body world */ static bool ED_rigidbody_world_active_poll(bContext *C) { - Scene *scene = CTX_data_scene(C); - return (scene && scene->rigidbody_world); + Scene *scene = CTX_data_scene(C); + return (scene && scene->rigidbody_world); } static bool ED_rigidbody_world_add_poll(bContext *C) { - Scene *scene = CTX_data_scene(C); - return (scene && scene->rigidbody_world == NULL); + Scene *scene = CTX_data_scene(C); + return (scene && scene->rigidbody_world == NULL); } /* ********************************************** */ @@ -72,73 +72,73 @@ static bool ED_rigidbody_world_add_poll(bContext *C) static int rigidbody_world_add_exec(bContext *C, wmOperator *UNUSED(op)) { - Main *bmain = CTX_data_main(C); - Scene *scene = CTX_data_scene(C); - RigidBodyWorld *rbw; + Main *bmain = CTX_data_main(C); + Scene *scene = CTX_data_scene(C); + RigidBodyWorld *rbw; - rbw = BKE_rigidbody_create_world(scene); -// BKE_rigidbody_validate_sim_world(scene, rbw, false); - scene->rigidbody_world = rbw; + rbw = BKE_rigidbody_create_world(scene); + // BKE_rigidbody_validate_sim_world(scene, rbw, false); + scene->rigidbody_world = rbw; - /* Full rebuild of DEG! */ - DEG_relations_tag_update(bmain); - DEG_id_tag_update_ex(bmain, &scene->id, ID_RECALC_ANIMATION); + /* Full rebuild of DEG! */ + DEG_relations_tag_update(bmain); + DEG_id_tag_update_ex(bmain, &scene->id, ID_RECALC_ANIMATION); - return OPERATOR_FINISHED; + return OPERATOR_FINISHED; } void RIGIDBODY_OT_world_add(wmOperatorType *ot) { - /* identifiers */ - ot->idname = "RIGIDBODY_OT_world_add"; - ot->name = "Add Rigid Body World"; - ot->description = "Add Rigid Body simulation world to the current scene"; + /* identifiers */ + ot->idname = "RIGIDBODY_OT_world_add"; + ot->name = "Add Rigid Body World"; + ot->description = "Add Rigid Body simulation world to the current scene"; - /* callbacks */ - ot->exec = rigidbody_world_add_exec; - ot->poll = ED_rigidbody_world_add_poll; + /* callbacks */ + ot->exec = rigidbody_world_add_exec; + ot->poll = ED_rigidbody_world_add_poll; - /* flags */ - ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO; + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } /* ********** Remove RigidBody World ************* */ static int rigidbody_world_remove_exec(bContext *C, wmOperator *op) { - Main *bmain = CTX_data_main(C); - Scene *scene = CTX_data_scene(C); - RigidBodyWorld *rbw = scene->rigidbody_world; + Main *bmain = CTX_data_main(C); + Scene *scene = CTX_data_scene(C); + RigidBodyWorld *rbw = scene->rigidbody_world; - /* sanity checks */ - if (ELEM(NULL, scene, rbw)) { - BKE_report(op->reports, RPT_ERROR, "No Rigid Body World to remove"); - return OPERATOR_CANCELLED; - } + /* sanity checks */ + if (ELEM(NULL, scene, rbw)) { + BKE_report(op->reports, RPT_ERROR, "No Rigid Body World to remove"); + return OPERATOR_CANCELLED; + } - BKE_rigidbody_free_world(scene); + BKE_rigidbody_free_world(scene); - /* Full rebuild of DEG! */ - DEG_relations_tag_update(bmain); - DEG_id_tag_update_ex(bmain, &scene->id, ID_RECALC_ANIMATION); + /* Full rebuild of DEG! */ + DEG_relations_tag_update(bmain); + DEG_id_tag_update_ex(bmain, &scene->id, ID_RECALC_ANIMATION); - /* done */ - return OPERATOR_FINISHED; + /* done */ + return OPERATOR_FINISHED; } void RIGIDBODY_OT_world_remove(wmOperatorType *ot) { - /* identifiers */ - ot->idname = "RIGIDBODY_OT_world_remove"; - ot->name = "Remove Rigid Body World"; - ot->description = "Remove Rigid Body simulation world from the current scene"; + /* identifiers */ + ot->idname = "RIGIDBODY_OT_world_remove"; + ot->name = "Remove Rigid Body World"; + ot->description = "Remove Rigid Body simulation world from the current scene"; - /* callbacks */ - ot->exec = rigidbody_world_remove_exec; - ot->poll = ED_rigidbody_world_active_poll; + /* callbacks */ + ot->exec = rigidbody_world_remove_exec; + ot->poll = ED_rigidbody_world_active_poll; - /* flags */ - ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO; + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; } /* ********************************************** */ @@ -148,59 +148,65 @@ void RIGIDBODY_OT_world_remove(wmOperatorType *ot) static int rigidbody_world_export_exec(bContext *C, wmOperator *op) { - Scene *scene = CTX_data_scene(C); - RigidBodyWorld *rbw = scene->rigidbody_world; - char path[FILE_MAX]; - - /* sanity checks */ - if (ELEM(NULL, scene, rbw)) { - BKE_report(op->reports, RPT_ERROR, "No Rigid Body World to export"); - return OPERATOR_CANCELLED; - } - if (rbw->shared->physics_world == NULL) { - BKE_report(op->reports, RPT_ERROR, "Rigid Body World has no associated physics data to export"); - return OPERATOR_CANCELLED; - } - - RNA_string_get(op->ptr, "filepath", path); + Scene *scene = CTX_data_scene(C); + RigidBodyWorld *rbw = scene->rigidbody_world; + char path[FILE_MAX]; + + /* sanity checks */ + if (ELEM(NULL, scene, rbw)) { + BKE_report(op->reports, RPT_ERROR, "No Rigid Body World to export"); + return OPERATOR_CANCELLED; + } + if (rbw->shared->physics_world == NULL) { + BKE_report( + op->reports, RPT_ERROR, "Rigid Body World has no associated physics data to export"); + return OPERATOR_CANCELLED; + } + + RNA_string_get(op->ptr, "filepath", path); #ifdef WITH_BULLET - RB_dworld_export(rbw->shared->physics_world, path); + RB_dworld_export(rbw->shared->physics_world, path); #endif - return OPERATOR_FINISHED; + return OPERATOR_FINISHED; } static int rigidbody_world_export_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event)) { - if (!RNA_struct_property_is_set(op->ptr, "relative_path")) - RNA_boolean_set(op->ptr, "relative_path", (U.flag & USER_RELPATHS) != 0); + if (!RNA_struct_property_is_set(op->ptr, "relative_path")) + RNA_boolean_set(op->ptr, "relative_path", (U.flag & USER_RELPATHS) != 0); - if (RNA_struct_property_is_set(op->ptr, "filepath")) - return rigidbody_world_export_exec(C, op); + if (RNA_struct_property_is_set(op->ptr, "filepath")) + return rigidbody_world_export_exec(C, op); - // TODO: use the actual rigidbody world's name + .bullet instead of this temp crap - RNA_string_set(op->ptr, "filepath", "rigidbodyworld_export.bullet"); - WM_event_add_fileselect(C, op); + // TODO: use the actual rigidbody world's name + .bullet instead of this temp crap + RNA_string_set(op->ptr, "filepath", "rigidbodyworld_export.bullet"); + WM_event_add_fileselect(C, op); - return OPERATOR_RUNNING_MODAL; + return OPERATOR_RUNNING_MODAL; } void RIGIDBODY_OT_world_export(wmOperatorType *ot) { - /* identifiers */ - ot->idname = "RIGIDBODY_OT_world_export"; - ot->name = "Export Rigid Body World"; - ot->description = "Export Rigid Body world to simulator's own fileformat (i.e. '.bullet' for Bullet Physics)"; - - /* callbacks */ - ot->invoke = rigidbody_world_export_invoke; - ot->exec = rigidbody_world_export_exec; - ot->poll = ED_rigidbody_world_active_poll; - - /* flags */ - ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO; - - /* properties */ - WM_operator_properties_filesel( - ot, FILE_TYPE_FOLDER, FILE_SPECIAL, FILE_SAVE, - FILE_RELPATH, FILE_DEFAULTDISPLAY, FILE_SORT_ALPHA); + /* identifiers */ + ot->idname = "RIGIDBODY_OT_world_export"; + ot->name = "Export Rigid Body World"; + ot->description = + "Export Rigid Body world to simulator's own fileformat (i.e. '.bullet' for Bullet Physics)"; + + /* callbacks */ + ot->invoke = rigidbody_world_export_invoke; + ot->exec = rigidbody_world_export_exec; + ot->poll = ED_rigidbody_world_active_poll; + + /* flags */ + ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO; + + /* properties */ + WM_operator_properties_filesel(ot, + FILE_TYPE_FOLDER, + FILE_SPECIAL, + FILE_SAVE, + FILE_RELPATH, + FILE_DEFAULTDISPLAY, + FILE_SORT_ALPHA); } -- cgit v1.2.3