diff options
author | Rohan Rathi <rohanrathi08@gmail.com> | 2018-06-20 19:59:44 +0300 |
---|---|---|
committer | Rohan Rathi <rohanrathi08@gmail.com> | 2018-06-20 19:59:44 +0300 |
commit | c73a6b0d42f5ee16bb2af7d585035463854f4024 (patch) | |
tree | c366aeac74491653e0ba516b745116bfa6475f94 /source/blender/blenkernel | |
parent | dd752476b97aa3b35d1359422ca42e33d99ac851 (diff) | |
parent | 82dc5f91e86351e1a26769ec86d9054437eb77d6 (diff) |
Merge branch 'blender2.8' into soc-2018-bevel
Diffstat (limited to 'source/blender/blenkernel')
138 files changed, 6389 insertions, 5610 deletions
diff --git a/source/blender/blenkernel/BKE_DerivedMesh.h b/source/blender/blenkernel/BKE_DerivedMesh.h index 79b0e5eb95f..02410f624da 100644 --- a/source/blender/blenkernel/BKE_DerivedMesh.h +++ b/source/blender/blenkernel/BKE_DerivedMesh.h @@ -264,12 +264,12 @@ struct DerivedMesh { CustomData *(*getTessFaceDataLayout)(DerivedMesh * dm); CustomData *(*getLoopDataLayout)(DerivedMesh * dm); CustomData *(*getPolyDataLayout)(DerivedMesh * dm); - + /** Copies all customdata for an element source into dst at index dest */ void (*copyFromVertCData)(DerivedMesh *dm, int source, CustomData *dst, int dest); void (*copyFromEdgeCData)(DerivedMesh *dm, int source, CustomData *dst, int dest); void (*copyFromFaceCData)(DerivedMesh *dm, int source, CustomData *dst, int dest); - + /** Optional grid access for subsurf */ int (*getNumGrids)(DerivedMesh *dm); int (*getGridSize)(DerivedMesh *dm); @@ -278,7 +278,7 @@ struct DerivedMesh { void (*getGridKey)(DerivedMesh *dm, struct CCGKey *key); DMFlagMat *(*getGridFlagMats)(DerivedMesh * dm); unsigned int **(*getGridHidden)(DerivedMesh * dm); - + /** Iterate over each mapped vertex in the derived mesh, calling the * given function with the original vert and the mapped vert's new diff --git a/source/blender/blenkernel/BKE_action.h b/source/blender/blenkernel/BKE_action.h index 8ec75bda538..7567adc50dc 100644 --- a/source/blender/blenkernel/BKE_action.h +++ b/source/blender/blenkernel/BKE_action.h @@ -69,7 +69,7 @@ void BKE_action_make_local(struct Main *bmain, struct bAction *act, const bool l /* Action API ----------------- */ -/* types of transforms applied to the given item +/* types of transforms applied to the given item * - these are the return falgs for action_get_item_transforms() */ typedef enum eAction_TransformFlags { @@ -79,21 +79,21 @@ typedef enum eAction_TransformFlags { ACT_TRANS_ROT = (1 << 1), /* scaling */ ACT_TRANS_SCALE = (1 << 2), - + /* bbone shape - for all the parameters, provided one is set */ ACT_TRANS_BBONE = (1 << 3), - + /* strictly not a transform, but custom properties are also * quite often used in modern rigs */ ACT_TRANS_PROP = (1 << 4), - + /* all flags */ ACT_TRANS_ONLY = (ACT_TRANS_LOC | ACT_TRANS_ROT | ACT_TRANS_SCALE), ACT_TRANS_ALL = (ACT_TRANS_ONLY | ACT_TRANS_PROP) } eAction_TransformFlags; -/* Return flags indicating which transforms the given object/posechannel has +/* Return flags indicating which transforms the given object/posechannel has * - if 'curves' is provided, a list of links to these curves are also returned * whose nodes WILL NEED FREEING */ @@ -132,7 +132,7 @@ struct bActionGroup *BKE_action_group_find_name(struct bAction *act, const char /* Clear all 'temp' flags on all groups */ void action_groups_clear_tempflags(struct bAction *act); -/* Pose API ----------------- */ +/* Pose API ----------------- */ void BKE_pose_channel_free(struct bPoseChannel *pchan); void BKE_pose_channel_free_ex(struct bPoseChannel *pchan, bool do_id_user); @@ -185,7 +185,7 @@ bool BKE_pose_channel_in_IK_chain(struct Object *ob, struct bPoseChannel *pchan) // XXX to be deprecated for a more general solution in animsys... void framechange_poses_clear_unkeyed(struct Main *bmain); -/* Bone Groups API --------------------- */ +/* Bone Groups API --------------------- */ /* Adds a new bone-group */ struct bActionGroup *BKE_pose_add_group(struct bPose *pose, const char *name); @@ -195,7 +195,7 @@ void BKE_pose_remove_group(struct bPose *pose, struct bActionGroup *grp, const i /* Remove the matching bone-group from its index */ void BKE_pose_remove_group_index(struct bPose *pose, const int index); -/* Assorted Evaluation ----------------- */ +/* Assorted Evaluation ----------------- */ /* Used for the Action Constraint */ void what_does_obaction(struct Object *ob, struct Object *workob, struct bPose *pose, struct bAction *act, char groupname[], float cframe); diff --git a/source/blender/blenkernel/BKE_addon.h b/source/blender/blenkernel/BKE_addon.h index e631d1d6537..3af6d3b61bf 100644 --- a/source/blender/blenkernel/BKE_addon.h +++ b/source/blender/blenkernel/BKE_addon.h @@ -51,7 +51,8 @@ void BKE_addon_pref_type_init(void); void BKE_addon_pref_type_free(void); struct bAddon *BKE_addon_new(void); -struct bAddon *BKE_addon_ensure(struct ListBase *addons, const char *module); +struct bAddon *BKE_addon_find(struct ListBase *addon_list, const char *module); +struct bAddon *BKE_addon_ensure(struct ListBase *addon_list, const char *module); void BKE_addon_free(struct bAddon *addon); #endif /* __BKE_ADDON_H__ */ diff --git a/source/blender/blenkernel/BKE_animsys.h b/source/blender/blenkernel/BKE_animsys.h index 326c25e8899..b16e8c17a12 100644 --- a/source/blender/blenkernel/BKE_animsys.h +++ b/source/blender/blenkernel/BKE_animsys.h @@ -76,21 +76,23 @@ struct AnimData *BKE_animdata_copy(struct Main *bmain, struct AnimData *adt, con bool BKE_animdata_copy_id(struct Main *bmain, struct ID *id_to, struct ID *id_from, const bool do_action, const bool do_id_user); /* Copy AnimData Actions */ -void BKE_animdata_copy_id_action(struct ID *id, const bool set_newid); +void BKE_animdata_copy_id_action(struct Main *bmain, struct ID *id, const bool set_newid); /* Merge copies of data from source AnimData block */ typedef enum eAnimData_MergeCopy_Modes { /* Keep destination action */ ADT_MERGECOPY_KEEP_DST = 0, - + /* Use src action (make a new copy) */ ADT_MERGECOPY_SRC_COPY = 1, - + /* Use src action (but just reference the existing version) */ ADT_MERGECOPY_SRC_REF = 2 } eAnimData_MergeCopy_Modes; -void BKE_animdata_merge_copy(struct ID *dst_id, struct ID *src_id, eAnimData_MergeCopy_Modes action_mode, bool fix_drivers); +void BKE_animdata_merge_copy( + struct Main *bmain, struct ID *dst_id, struct ID *src_id, + eAnimData_MergeCopy_Modes action_mode, bool fix_drivers); /* ************************************* */ /* KeyingSets API */ @@ -141,7 +143,8 @@ void BKE_animdata_fix_paths_remove(struct ID *id, const char *path); /* -------------------------------------- */ /* Move animation data from src to destination if it's paths are based on basepaths */ -void BKE_animdata_separate_by_basepath(struct ID *srcID, struct ID *dstID, struct ListBase *basepaths); +void BKE_animdata_separate_by_basepath( + struct Main *bmain, struct ID *srcID, struct ID *dstID, struct ListBase *basepaths); /* Move F-Curves from src to destination if it's path is based on basepath */ void action_move_fcurves_by_basepath(struct bAction *srcAct, struct bAction *dstAct, const char basepath[]); diff --git a/source/blender/blenkernel/BKE_armature.h b/source/blender/blenkernel/BKE_armature.h index 57d70afcb8b..23014accc3f 100644 --- a/source/blender/blenkernel/BKE_armature.h +++ b/source/blender/blenkernel/BKE_armature.h @@ -55,10 +55,10 @@ typedef struct PoseTarget { typedef struct PoseTree { struct PoseTree *next, *prev; - + int type; /* type of IK that this serves (CONSTRAINT_TYPE_KINEMATIC or ..._SPLINEIK) */ int totchannel; /* number of pose channels */ - + struct ListBase targets; /* list of targets of the tree */ struct bPoseChannel **pchan; /* array of pose channels */ int *parent; /* and their parents */ diff --git a/source/blender/blenkernel/BKE_blender_version.h b/source/blender/blenkernel/BKE_blender_version.h index a1212322983..def7dfd753b 100644 --- a/source/blender/blenkernel/BKE_blender_version.h +++ b/source/blender/blenkernel/BKE_blender_version.h @@ -28,10 +28,10 @@ * and keep comment above the defines. * Use STRINGIFY() rather than defining with quotes */ #define BLENDER_VERSION 280 -#define BLENDER_SUBVERSION 17 -/* Several breakages with 270, e.g. constraint deg vs rad */ -#define BLENDER_MINVERSION 270 -#define BLENDER_MINSUBVERSION 6 +#define BLENDER_SUBVERSION 19 +/* Several breakages with 280, e.g. collections vs layers */ +#define BLENDER_MINVERSION 280 +#define BLENDER_MINSUBVERSION 0 /* used by packaging tools */ /* can be left blank, otherwise a,b,c... etc with no quotes */ diff --git a/source/blender/blenkernel/BKE_cloth.h b/source/blender/blenkernel/BKE_cloth.h index d598923edbc..f0d8e1a1d84 100644 --- a/source/blender/blenkernel/BKE_cloth.h +++ b/source/blender/blenkernel/BKE_cloth.h @@ -68,7 +68,7 @@ typedef struct ClothHairData { typedef struct ClothSolverResult { int status; - + int max_iterations, min_iterations; float avg_iterations; float max_error, min_error, avg_error; @@ -139,7 +139,7 @@ typedef struct ClothSpring { int flags; /* defined in BKE_cloth.h, e.g. deactivated due to tearing */ float stiffness; /* stiffness factor from the vertex groups */ float editrestlen; - + /* angular bending spring target and derivatives */ float target[3]; } @@ -204,7 +204,7 @@ struct CollPair; typedef struct ColliderContacts { struct Object *ob; struct CollisionModifierData *collmd; - + struct CollPair *collisions; int totcollisions; } ColliderContacts; diff --git a/source/blender/blenkernel/BKE_collection.h b/source/blender/blenkernel/BKE_collection.h index fc5b19ccb4f..7dce3b2c703 100644 --- a/source/blender/blenkernel/BKE_collection.h +++ b/source/blender/blenkernel/BKE_collection.h @@ -90,14 +90,13 @@ void BKE_collections_child_remove_nulls(struct Main *bmain, struct Collection *o bool BKE_collection_is_in_scene(struct Collection *collection); void BKE_collections_after_lib_link(struct Main *bmain); bool BKE_collection_object_cyclic_check(struct Main *bmain, struct Object *object, struct Collection *collection); -bool BKE_collection_is_animated(struct Collection *collection, struct Object *parent); /* Object list cache. */ struct ListBase BKE_collection_object_cache_get(struct Collection *collection); void BKE_collection_object_cache_free(struct Collection *collection); -struct Base *BKE_collection_or_layer_objects(struct Depsgraph *depsgraph, +struct Base *BKE_collection_or_layer_objects(const struct Depsgraph *depsgraph, const struct Scene *scene, const struct ViewLayer *view_layer, struct Collection *collection); @@ -139,13 +138,21 @@ void BKE_scene_objects_callback(struct Scene *scene, BKE_scene_objects_Cb callba /* Iteratorion over objects in collection. */ -#define FOREACH_COLLECTION_BASE_RECURSIVE_BEGIN(_collection, _base) \ - for (Base *_base = (Base*)BKE_collection_object_cache_get(_collection).first; \ - _base; \ - _base = _base->next) \ - { - -#define FOREACH_COLLECTION_BASE_RECURSIVE_END \ +#define FOREACH_COLLECTION_VISIBLE_OBJECT_RECURSIVE_BEGIN(_collection, _object, _mode) \ + { \ + int _base_flag = (_mode == DAG_EVAL_VIEWPORT) ? \ + BASE_VISIBLE_VIEWPORT : BASE_VISIBLE_RENDER; \ + int _base_id = 0; \ + for (Base *_base = (Base*)BKE_collection_object_cache_get(_collection).first; \ + _base; \ + _base = _base->next, _base_id++) \ + { \ + if (_base->flag & _base_flag) { \ + Object *_object = _base->object; \ + +#define FOREACH_COLLECTION_VISIBLE_OBJECT_RECURSIVE_END \ + } \ + } \ } #define FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(_collection, _object) \ diff --git a/source/blender/blenkernel/BKE_constraint.h b/source/blender/blenkernel/BKE_constraint.h index 98ba0f6f2a4..2bc71c114b7 100644 --- a/source/blender/blenkernel/BKE_constraint.h +++ b/source/blender/blenkernel/BKE_constraint.h @@ -53,10 +53,10 @@ typedef struct bConstraintOb { struct Scene *scene; /* for system time, part of deglobalization, code nicer later with local time (ton) */ struct Object *ob; /* if pchan, then armature that it comes from, otherwise constraint owner */ struct bPoseChannel *pchan; /* pose channel that owns the constraints being evaluated */ - + float matrix[4][4]; /* matrix where constraints are accumulated + solved */ float startmat[4][4]; /* original matrix (before constraint solving) */ - + short type; /* type of owner */ short rotOrder; /* rotation order for constraint owner (as defined in eEulerRotationOrders in BLI_math.h) */ } bConstraintOb; @@ -85,7 +85,7 @@ typedef struct bConstraintTypeInfo { short size; /* size in bytes of the struct */ char name[32]; /* name of constraint in interface */ char structName[32]; /* name of struct for SDNA */ - + /* data management function pointers - special handling */ /* free any data that is allocated separately (optional) */ void (*free_data)(struct bConstraint *con); @@ -95,13 +95,13 @@ typedef struct bConstraintTypeInfo { void (*copy_data)(struct bConstraint *con, struct bConstraint *src); /* set settings for data that will be used for bConstraint.data (memory already allocated using MEM_callocN) */ void (*new_data)(void *cdata); - + /* target handling function pointers */ /* for multi-target constraints: return that list; otherwise make a temporary list (returns number of targets) */ int (*get_constraint_targets)(struct bConstraint *con, struct ListBase *list); /* for single-target constraints only: flush data back to source data, and the free memory used */ void (*flush_constraint_targets)(struct bConstraint *con, struct ListBase *list, bool no_copy); - + /* evaluation */ /* set the ct->matrix for the given constraint target (at the given ctime) */ void (*get_target_matrix)(struct Depsgraph *depsgraph, struct bConstraint *con, struct bConstraintOb *cob, struct bConstraintTarget *ct, float ctime); diff --git a/source/blender/blenkernel/BKE_context.h b/source/blender/blenkernel/BKE_context.h index e224863a27f..2ea940b8fee 100644 --- a/source/blender/blenkernel/BKE_context.h +++ b/source/blender/blenkernel/BKE_context.h @@ -330,6 +330,6 @@ struct Depsgraph *CTX_data_depsgraph_on_load(const bContext *C); #ifdef __cplusplus } #endif - + #endif diff --git a/source/blender/blenkernel/BKE_customdata.h b/source/blender/blenkernel/BKE_customdata.h index 85c894864d5..dc9bbf9336e 100644 --- a/source/blender/blenkernel/BKE_customdata.h +++ b/source/blender/blenkernel/BKE_customdata.h @@ -227,8 +227,8 @@ void CustomData_copy_data_named(const struct CustomData *source, struct CustomData *dest, int source_index, int dest_index, int count); void CustomData_copy_elements(int type, void *src_data_ofs, void *dst_data_ofs, int count); -void CustomData_bmesh_copy_data(const struct CustomData *source, - struct CustomData *dest, void *src_block, +void CustomData_bmesh_copy_data(const struct CustomData *source, + struct CustomData *dest, void *src_block, void **dest_block); /* frees data in a CustomData object @@ -354,9 +354,9 @@ void CustomData_bmesh_free_block_data(struct CustomData *data, void *block); /* copy custom data to/from layers as in mesh/derivedmesh, to editmesh * blocks of data. the CustomData's must not be compatible */ -void CustomData_to_bmesh_block(const struct CustomData *source, +void CustomData_to_bmesh_block(const struct CustomData *source, struct CustomData *dest, int src_index, void **dest_block, bool use_default_init); -void CustomData_from_bmesh_block(const struct CustomData *source, +void CustomData_from_bmesh_block(const struct CustomData *source, struct CustomData *dest, void *src_block, int dest_index); void CustomData_file_write_prepare( diff --git a/source/blender/blenkernel/BKE_displist.h b/source/blender/blenkernel/BKE_displist.h index 6dd40b7a651..034f9b2b6a8 100644 --- a/source/blender/blenkernel/BKE_displist.h +++ b/source/blender/blenkernel/BKE_displist.h @@ -1,4 +1,4 @@ -/* +/* * ***** BEGIN GPL LICENSE BLOCK ***** * * This program is free software; you can redistribute it and/or diff --git a/source/blender/blenkernel/BKE_dynamicpaint.h b/source/blender/blenkernel/BKE_dynamicpaint.h index 0a759629930..acb5e63d32f 100644 --- a/source/blender/blenkernel/BKE_dynamicpaint.h +++ b/source/blender/blenkernel/BKE_dynamicpaint.h @@ -55,7 +55,7 @@ typedef struct PaintPoint { } PaintPoint; /* heigh field waves */ -typedef struct PaintWavePoint { +typedef struct PaintWavePoint { float height; float velocity; diff --git a/source/blender/blenkernel/BKE_editmesh.h b/source/blender/blenkernel/BKE_editmesh.h index 39986129c61..690a42894f2 100644 --- a/source/blender/blenkernel/BKE_editmesh.h +++ b/source/blender/blenkernel/BKE_editmesh.h @@ -57,7 +57,7 @@ typedef struct BMEditMesh { /*this is for undoing failed operations*/ struct BMEditMesh *emcopy; int emcopyusers; - + /* we store tessellations as triplets of three loops, * which each define a triangle.*/ struct BMLoop *(*looptris)[3]; diff --git a/source/blender/blenkernel/BKE_effect.h b/source/blender/blenkernel/BKE_effect.h index d45ecf9e3d8..379ab3e81b5 100644 --- a/source/blender/blenkernel/BKE_effect.h +++ b/source/blender/blenkernel/BKE_effect.h @@ -99,7 +99,7 @@ typedef struct EffectorCache { struct Object *ob; struct ParticleSystem *psys; struct SurfaceModifierData *surmd; - + struct PartDeflect *pd; /* precalculated for guides */ @@ -171,10 +171,10 @@ unsigned int BKE_sim_debug_data_hash_combine(unsigned int kx, unsigned int ky); typedef struct SimDebugElement { unsigned int category_hash; unsigned int hash; - + int type; float color[3]; - + float v1[3], v2[3]; char str[64]; } SimDebugElement; diff --git a/source/blender/blenkernel/BKE_fcurve.h b/source/blender/blenkernel/BKE_fcurve.h index 09f5ecce050..c0bbf146afd 100644 --- a/source/blender/blenkernel/BKE_fcurve.h +++ b/source/blender/blenkernel/BKE_fcurve.h @@ -66,7 +66,7 @@ void bezt_add_to_cfra_elem(ListBase *lb, struct BezTriple *bezt); /* ************** F-Curve Drivers ***************** */ -/* With these iterators for convenience, the variables "tarIndex" and "dtar" can be +/* With these iterators for convenience, the variables "tarIndex" and "dtar" can be * accessed directly from the code using them, but it is not recommended that their * values be changed to point at other slots... */ @@ -77,14 +77,14 @@ void bezt_add_to_cfra_elem(ListBase *lb, struct BezTriple *bezt); DriverTarget *dtar = &dvar->targets[0]; \ int tarIndex = 0; \ for (; tarIndex < MAX_DRIVER_TARGETS; tarIndex++, dtar++) - + /* convenience looper over USED driver targets only */ #define DRIVER_TARGETS_USED_LOOPER(dvar) \ { \ DriverTarget *dtar = &dvar->targets[0]; \ int tarIndex = 0; \ for (; tarIndex < dvar->num_targets; tarIndex++, dtar++) - + /* tidy up for driver targets loopers */ #define DRIVER_TARGETS_LOOPER_END \ } @@ -108,7 +108,8 @@ bool driver_get_variable_property( struct ChannelDriver *driver, struct DriverTarget *dtar, struct PointerRNA *r_ptr, struct PropertyRNA **r_prop, int *r_index); -float evaluate_driver(struct PathResolvedRNA *anim_rna, struct ChannelDriver *driver, const float evaltime); +float evaluate_driver(struct PathResolvedRNA *anim_rna, struct ChannelDriver *driver, + struct ChannelDriver *driver_orig, const float evaltime); /* ************** F-Curve Modifiers *************** */ @@ -133,7 +134,7 @@ typedef struct FModifierTypeInfo { short requires; /* eFMI_Requirement_Flags */ char name[64]; /* name of modifier in interface */ char structName[64]; /* name of struct for SDNA */ - + /* data management function pointers - special handling */ /* free any data that is allocated separately (optional) */ void (*free_data)(struct FModifier *fcm); @@ -143,7 +144,7 @@ typedef struct FModifierTypeInfo { void (*new_data)(void *mdata); /* verifies that the modifier settings are valid */ void (*verify_data)(struct FModifier *fcm); - + /* evaluation */ /* evaluate time that the modifier requires the F-Curve to be evaluated at */ float (*evaluate_modifier_time)(struct FCurve *fcu, struct FModifier *fcm, float cvalue, float evaltime); @@ -229,7 +230,7 @@ struct FCurve *iter_step_fcurve(struct FCurve *fcu_iter, const char rna_path[]); /* high level function to get an fcurve from C without having the rna */ struct FCurve *id_data_find_fcurve(ID *id, void *data, struct StructRNA *type, const char *prop_name, int index, bool *r_driven); -/* Get list of LinkData's containing pointers to the F-Curves which control the types of data indicated +/* Get list of LinkData's containing pointers to the F-Curves which control the types of data indicated * e.g. numMatches = list_find_data_fcurves(matches, &act->curves, "pose.bones[", "MyFancyBone"); */ int list_find_data_fcurves(ListBase *dst, ListBase *src, const char *dataPrefix, const char *dataName); @@ -282,7 +283,8 @@ void correct_bezpart(float v1[2], float v2[2], float v3[2], float v4[2]); /* evaluate fcurve */ float evaluate_fcurve(struct FCurve *fcu, float evaltime); -float evaluate_fcurve_driver(struct PathResolvedRNA *anim_rna, struct FCurve *fcu, float evaltime); +float evaluate_fcurve_driver(struct PathResolvedRNA *anim_rna, struct FCurve *fcu, + struct ChannelDriver *driver_orig, float evaltime); /* evaluate fcurve and store value */ float calculate_fcurve(struct PathResolvedRNA *anim_rna, struct FCurve *fcu, float evaltime); @@ -290,7 +292,7 @@ float calculate_fcurve(struct PathResolvedRNA *anim_rna, struct FCurve *fcu, flo /* -------- Defines -------- */ -/* Basic signature for F-Curve sample-creation function +/* Basic signature for F-Curve sample-creation function * - fcu: the F-Curve being operated on * - data: pointer to some specific data that may be used by one of the callbacks */ @@ -303,7 +305,7 @@ float fcurve_samplingcb_evalcurve(struct FCurve *fcu, void *data, float evaltime /* -------- Main Methods -------- */ -/* Main API function for creating a set of sampled curve data, given some callback function +/* Main API function for creating a set of sampled curve data, given some callback function * used to retrieve the values to store. */ void fcurve_store_samples(struct FCurve *fcu, void *data, int start, int end, FcuSampleFunc sample_cb); diff --git a/source/blender/blenkernel/BKE_font.h b/source/blender/blenkernel/BKE_font.h index e5eea4423c9..d13cd4adff9 100644 --- a/source/blender/blenkernel/BKE_font.h +++ b/source/blender/blenkernel/BKE_font.h @@ -58,7 +58,7 @@ typedef struct EditFontSelBox { typedef struct EditFont { wchar_t *textbuf; struct CharInfo *textbufinfo; - + /* array of rectangles & rotation */ float textcurs[4][2]; EditFontSelBox *selboxes; @@ -68,7 +68,7 @@ typedef struct EditFont { * a copy of these is kept in Curve, but use these in editmode */ int len, pos; int selstart, selend; - + } EditFont; @@ -76,7 +76,7 @@ bool BKE_vfont_is_builtin(struct VFont *vfont); void BKE_vfont_builtin_register(void *mem, int size); void BKE_vfont_free_data(struct VFont *vfont); -void BKE_vfont_free(struct VFont *sc); +void BKE_vfont_free(struct VFont *sc); void BKE_vfont_init(struct VFont *vfont); void BKE_vfont_copy_data(struct Main *bmain, struct VFont *vfont_dst, const struct VFont *vfont_src, const int flag); struct VFont *BKE_vfont_builtin_get(void); @@ -86,13 +86,13 @@ struct VFont *BKE_vfont_load_exists(struct Main *bmain, const char *filepath); void BKE_vfont_make_local(struct Main *bmain, struct VFont *vfont, const bool lib_local); -bool BKE_vfont_to_curve_ex(struct Main *bmain, struct Object *ob, struct Curve *cu, int mode, +bool BKE_vfont_to_curve_ex(struct Object *ob, struct Curve *cu, int mode, struct ListBase *r_nubase, const wchar_t **r_text, int *r_text_len, bool *r_text_free, struct CharTrans **r_chartransdata); -bool BKE_vfont_to_curve_nubase(struct Main *bmain, struct Object *ob, int mode, +bool BKE_vfont_to_curve_nubase(struct Object *ob, int mode, struct ListBase *r_nubase); -bool BKE_vfont_to_curve(struct Main *bmain, struct Object *ob, int mode); +bool BKE_vfont_to_curve(struct Object *ob, int mode); int BKE_vfont_select_get(struct Object *ob, int *r_start, int *r_end); void BKE_vfont_select_clamp(struct Object *ob); diff --git a/source/blender/blenkernel/BKE_global.h b/source/blender/blenkernel/BKE_global.h index c5ad91c81fd..82afbdefeab 100644 --- a/source/blender/blenkernel/BKE_global.h +++ b/source/blender/blenkernel/BKE_global.h @@ -50,7 +50,7 @@ typedef struct Global { /* active pointers */ struct Main *main; - + /* strings: lastsaved */ char ima[1024], lib[1024]; /* 1024 = FILE_MAX */ @@ -218,5 +218,5 @@ extern Global G; #ifdef __cplusplus } #endif - + #endif diff --git a/source/blender/blenkernel/BKE_gpencil.h b/source/blender/blenkernel/BKE_gpencil.h index b6de922c245..3a951b7860d 100644 --- a/source/blender/blenkernel/BKE_gpencil.h +++ b/source/blender/blenkernel/BKE_gpencil.h @@ -56,7 +56,7 @@ void BKE_gpencil_stroke_sync_selection(struct bGPDstroke *gps); struct bGPDframe *BKE_gpencil_frame_addnew(struct bGPDlayer *gpl, int cframe); struct bGPDframe *BKE_gpencil_frame_addcopy(struct bGPDlayer *gpl, int cframe); struct bGPDlayer *BKE_gpencil_layer_addnew(struct bGPdata *gpd, const char *name, bool setactive); -struct bGPdata *BKE_gpencil_data_addnew(const char name[]); +struct bGPdata *BKE_gpencil_data_addnew(struct Main *bmain, const char name[]); struct bGPDframe *BKE_gpencil_frame_duplicate(const struct bGPDframe *gpf_src); struct bGPDlayer *BKE_gpencil_layer_duplicate(const struct bGPDlayer *gpl_src); @@ -88,7 +88,7 @@ bool gpencil_layer_is_editable(const struct bGPDlayer *gpl); typedef enum eGP_GetFrame_Mode { /* Use the preceeding gp-frame (i.e. don't add anything) */ GP_GETFRAME_USE_PREV = 0, - + /* Add a new empty/blank frame */ GP_GETFRAME_ADD_NEW = 1, /* Make a copy of the active frame */ diff --git a/source/blender/blenkernel/BKE_idprop.h b/source/blender/blenkernel/BKE_idprop.h index 94630eaa7b0..6df31db7b83 100644 --- a/source/blender/blenkernel/BKE_idprop.h +++ b/source/blender/blenkernel/BKE_idprop.h @@ -19,7 +19,7 @@ * * ***** END GPL LICENSE BLOCK ***** */ - + #ifndef __BKE_IDPROP_H__ #define __BKE_IDPROP_H__ diff --git a/source/blender/blenkernel/BKE_image.h b/source/blender/blenkernel/BKE_image.h index fc018dbfe81..badcd5012de 100644 --- a/source/blender/blenkernel/BKE_image.h +++ b/source/blender/blenkernel/BKE_image.h @@ -216,7 +216,7 @@ void BKE_image_verify_viewer_views(const struct RenderData *rd, struct Image *im void BKE_image_user_frame_calc(struct ImageUser *iuser, int cfra, int fieldnr); void BKE_image_user_check_frame_calc(struct ImageUser *iuser, int cfra, int fieldnr); int BKE_image_user_frame_get(const struct ImageUser *iuser, int cfra, int fieldnr, bool *r_is_in_range); -void BKE_image_user_file_path(struct ImageUser *iuser, struct Image *ima, char *path); +void BKE_image_user_file_path(struct ImageUser *iuser, struct Image *ima, char *path); void BKE_image_update_frame(const struct Main *bmain, int cfra); /* sets index offset for multilayer files */ @@ -271,7 +271,7 @@ bool BKE_image_scale(struct Image *image, int width, int height); bool BKE_image_has_alpha(struct Image *image); /* check if texture has gpu texture code */ -bool BKE_image_has_bindcode(struct Image *ima); +bool BKE_image_has_opengl_texture(struct Image *ima); void BKE_image_get_size(struct Image *image, struct ImageUser *iuser, int *width, int *height); void BKE_image_get_size_fl(struct Image *image, struct ImageUser *iuser, float size[2]); @@ -296,6 +296,12 @@ void BKE_image_file_format_set(struct Image *image, int ftype, const struct ImbF bool BKE_image_has_loaded_ibuf(struct Image *image); struct ImBuf *BKE_image_get_ibuf_with_name(struct Image *image, const char *name); struct ImBuf *BKE_image_get_first_ibuf(struct Image *image); + +struct RenderSlot *BKE_image_add_renderslot(struct Image *ima, const char *name); +bool BKE_image_remove_renderslot(struct Image *ima, struct ImageUser *iuser, int slot); +struct RenderSlot *BKE_image_get_renderslot(struct Image *ima, int slot); +bool BKE_image_clear_renderslot(struct Image *ima, struct ImageUser *iuser, int slot); + #ifdef __cplusplus } #endif diff --git a/source/blender/blenkernel/BKE_key.h b/source/blender/blenkernel/BKE_key.h index 5eef44ef896..2f953e57d71 100644 --- a/source/blender/blenkernel/BKE_key.h +++ b/source/blender/blenkernel/BKE_key.h @@ -50,7 +50,7 @@ extern "C" { void BKE_key_free(struct Key *sc); void BKE_key_free_nolib(struct Key *key); -struct Key *BKE_key_add(struct ID *id); +struct Key *BKE_key_add(struct Main *bmain, struct ID *id); void BKE_key_copy_data(struct Main *bmain, struct Key *key_dst, const struct Key *key_src, const int flag); struct Key *BKE_key_copy(struct Main *bmain, const struct Key *key); struct Key *BKE_key_copy_nolib(struct Key *key); diff --git a/source/blender/blenkernel/BKE_lattice.h b/source/blender/blenkernel/BKE_lattice.h index b722b7da6a0..c2ac5e98f76 100644 --- a/source/blender/blenkernel/BKE_lattice.h +++ b/source/blender/blenkernel/BKE_lattice.h @@ -41,7 +41,6 @@ struct Main; struct Mesh; struct Object; struct Scene; -struct DerivedMesh; struct BPoint; struct MDeformVert; struct Depsgraph; diff --git a/source/blender/blenkernel/BKE_layer.h b/source/blender/blenkernel/BKE_layer.h index 60204d177f2..9e89033894d 100644 --- a/source/blender/blenkernel/BKE_layer.h +++ b/source/blender/blenkernel/BKE_layer.h @@ -104,8 +104,15 @@ bool BKE_view_layer_has_collection( bool BKE_scene_has_object( struct Scene *scene, struct Object *ob); +/* selection and hiding */ + bool BKE_layer_collection_objects_select( struct ViewLayer *view_layer, struct LayerCollection *lc, bool deselect); +bool BKE_layer_collection_has_selected_objects( + struct ViewLayer *view_layer, struct LayerCollection *lc); + +void BKE_base_set_visible(struct Scene *scene, struct ViewLayer *view_layer, struct Base *base, bool extend); +void BKE_layer_collection_set_visible(struct Scene *scene, struct ViewLayer *view_layer, struct LayerCollection *lc, bool extend); /* override */ diff --git a/source/blender/blenkernel/BKE_mesh.h b/source/blender/blenkernel/BKE_mesh.h index 3d70ef75a7c..1fd6fe1adae 100644 --- a/source/blender/blenkernel/BKE_mesh.h +++ b/source/blender/blenkernel/BKE_mesh.h @@ -64,7 +64,6 @@ struct MDeformVert; struct MDisps; struct Object; struct CustomData; -struct DerivedMesh; struct Scene; struct MLoopUV; struct ReportList; diff --git a/source/blender/blenkernel/BKE_mesh_iterators.h b/source/blender/blenkernel/BKE_mesh_iterators.h new file mode 100644 index 00000000000..cbf156b8052 --- /dev/null +++ b/source/blender/blenkernel/BKE_mesh_iterators.h @@ -0,0 +1,65 @@ +/* + * ***** BEGIN GPL LICENSE BLOCK ***** + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * The Original Code is: all of this file. + * + * Contributor(s): Blender Foundation + * + * ***** END GPL LICENSE BLOCK ***** + */ +#ifndef __BKE_MESH_ITERATORS_H__ +#define __BKE_MESH_ITERATORS_H__ + +/** \file BKE_MESH_ITERATORS.h + * \ingroup bke + */ + +struct Mesh; +struct MVert; +struct MEdge; +struct MPoly; +struct MLoop; +struct MLoopUV; +struct MLoopTri; + +typedef enum MeshForeachFlag { + MESH_FOREACH_NOP = 0, + MESH_FOREACH_USE_NORMAL = (1 << 0), /* foreachMappedVert, foreachMappedLoop, foreachMappedFaceCenter */ +} MeshForeachFlag; + + +void BKE_mesh_foreach_mapped_vert( + struct Mesh *mesh, + void (*func)(void *userData, int index, const float co[3], const float no_f[3], const short no_s[3]), + void *userData, + MeshForeachFlag flag); +void BKE_mesh_foreach_mapped_edge( + struct Mesh *mesh, + void (*func)(void *userData, int index, const float v0co[3], const float v1co[3]), + void *userData); +void BKE_mesh_foreach_mapped_loop( + struct Mesh *mesh, + void (*func)(void *userData, int vertex_index, int face_index, const float co[3], const float no[3]), + void *userData, + MeshForeachFlag flag); +void BKE_mesh_foreach_mapped_face_center( + struct Mesh *mesh, + void (*func)(void *userData, int index, const float cent[3], const float no[3]), + void *userData, + MeshForeachFlag flag); + +#endif /* __BKE_MESH_ITERATORS_H__ */ diff --git a/source/blender/blenkernel/BKE_modifier.h b/source/blender/blenkernel/BKE_modifier.h index b40d32203f6..8a9e2f44604 100644 --- a/source/blender/blenkernel/BKE_modifier.h +++ b/source/blender/blenkernel/BKE_modifier.h @@ -202,7 +202,7 @@ typedef struct ModifierTypeInfo { * * The derivedData argument should always be non-NULL; the modifier * should read the object data from the derived object instead of the - * actual object data. + * actual object data. * * The modifier may reuse the derivedData argument (i.e. return it in * modified form), but must not release it. @@ -212,7 +212,7 @@ typedef struct ModifierTypeInfo { /* Like applyModifier but called during editmode (for supporting * modifiers). - * + * * The derived object that is returned must support the operations that * are expected from editmode objects. The same qualifications regarding * derivedData apply as for applyModifier. @@ -253,7 +253,7 @@ typedef struct ModifierTypeInfo { * * The mesh argument should always be non-NULL; the modifier * should read the object data from the mesh object instead of the - * actual object data. + * actual object data. * * The modifier may reuse the mesh argument (i.e. return it in * modified form), but must not release it. @@ -263,7 +263,7 @@ typedef struct ModifierTypeInfo { /* Like applyModifier but called during editmode (for supporting * modifiers). - * + * * The mesh object that is returned must support the operations that * are expected from editmode objects. The same qualifications regarding * mesh apply as for applyModifier. @@ -277,7 +277,7 @@ typedef struct ModifierTypeInfo { /* Initialize new instance data for this modifier type, this function * should set modifier variables to their default values. - * + * * This function is optional. */ void (*initData)(struct ModifierData *md); @@ -323,7 +323,7 @@ typedef struct ModifierTypeInfo { */ void (*updateDepsgraph)(struct ModifierData *md, const ModifierUpdateDepsgraphContext *ctx); - + /* Should return true if the modifier needs to be recalculated on time * changes. * @@ -335,7 +335,7 @@ typedef struct ModifierTypeInfo { /* True when a deform modifier uses normals, the requiredDataMask * cant be used here because that refers to a normal layer where as * in this case we need to know if the deform modifier uses normals. - * + * * this is needed because applying 2 deform modifiers will give the * second modifier bogus normals. * */ diff --git a/source/blender/blenkernel/BKE_multires.h b/source/blender/blenkernel/BKE_multires.h index 851f2360f51..cecea927e8a 100644 --- a/source/blender/blenkernel/BKE_multires.h +++ b/source/blender/blenkernel/BKE_multires.h @@ -97,14 +97,6 @@ int multiresModifier_reshapeFromDeformMod(struct Depsgraph *depsgraph, struct Sc void multires_stitch_grids(struct Object *); -/*switch mdisp data in dm between tangent and object space*/ -enum { - MULTIRES_SPACE_TANGENT, - MULTIRES_SPACE_OBJECT, - MULTIRES_SPACE_ABSOLUTE -}; -void multires_set_space(struct DerivedMesh *dm, struct Object *ob, int from, int to); - /* Related to the old multires */ void multires_free(struct Multires *mr); void multires_load_old(struct Object *ob, struct Mesh *me); diff --git a/source/blender/blenkernel/BKE_nla.h b/source/blender/blenkernel/BKE_nla.h index 4509d374b02..6f0b6d59984 100644 --- a/source/blender/blenkernel/BKE_nla.h +++ b/source/blender/blenkernel/BKE_nla.h @@ -34,6 +34,7 @@ */ struct AnimData; +struct Main; struct NlaStrip; struct NlaTrack; struct bAction; @@ -50,9 +51,9 @@ void BKE_nlastrip_free(ListBase *strips, struct NlaStrip *strip); void BKE_nlatrack_free(ListBase *tracks, struct NlaTrack *nlt); void BKE_nla_tracks_free(ListBase *tracks); -struct NlaStrip *BKE_nlastrip_copy(struct NlaStrip *strip, const bool use_same_action); -struct NlaTrack *BKE_nlatrack_copy(struct NlaTrack *nlt, const bool use_same_actions); -void BKE_nla_tracks_copy(ListBase *dst, ListBase *src); +struct NlaStrip *BKE_nlastrip_copy(struct Main *bmain, struct NlaStrip *strip, const bool use_same_action); +struct NlaTrack *BKE_nlatrack_copy(struct Main *bmain, struct NlaTrack *nlt, const bool use_same_actions); +void BKE_nla_tracks_copy(struct Main *bmain, ListBase *dst, ListBase *src); struct NlaTrack *BKE_nlatrack_add(struct AnimData *adt, struct NlaTrack *prev); struct NlaStrip *BKE_nlastrip_new(struct bAction *act); diff --git a/source/blender/blenkernel/BKE_node.h b/source/blender/blenkernel/BKE_node.h index d271252ceef..63398ec9f5e 100644 --- a/source/blender/blenkernel/BKE_node.h +++ b/source/blender/blenkernel/BKE_node.h @@ -100,7 +100,7 @@ typedef struct bNodeSocketTemplate { float min, max; int subtype; /* would use PropertySubType but this is a bad level include to use RNA */ int flag; - + /* after this line is used internal only */ struct bNodeSocket *sock; /* used to hold verified socket */ char identifier[64]; /* generated from name */ @@ -111,21 +111,21 @@ typedef struct bNodeSocketTemplate { */ typedef struct bNodeSocketType { char idname[64]; /* identifier name */ - + void (*draw)(struct bContext *C, struct uiLayout *layout, struct PointerRNA *ptr, struct PointerRNA *node_ptr, const char *text); void (*draw_color)(struct bContext *C, struct PointerRNA *ptr, struct PointerRNA *node_ptr, float *r_color); - + void (*interface_draw)(struct bContext *C, struct uiLayout *layout, struct PointerRNA *ptr); void (*interface_draw_color)(struct bContext *C, struct PointerRNA *ptr, float *r_color); void (*interface_register_properties)(struct bNodeTree *ntree, struct bNodeSocket *stemp, struct StructRNA *data_srna); void (*interface_init_socket)(struct bNodeTree *ntree, struct bNodeSocket *stemp, struct bNode *node, struct bNodeSocket *sock, const char *data_path); void (*interface_verify_socket)(struct bNodeTree *ntree, struct bNodeSocket *stemp, struct bNode *node, struct bNodeSocket *sock, const char *data_path); void (*interface_from_socket)(struct bNodeTree *ntree, struct bNodeSocket *stemp, struct bNode *node, struct bNodeSocket *sock); - + /* RNA integration */ ExtensionRNA ext_socket; ExtensionRNA ext_interface; - + /* for standard socket types in C */ int type, subtype; } bNodeSocketType; @@ -142,23 +142,23 @@ typedef int (*NodeGPUExecFunction)(struct GPUMaterial *mat, struct bNode *node, typedef struct bNodeType { void *next, *prev; short needs_free; /* set for allocated types that need to be freed */ - + char idname[64]; /* identifier name */ int type; char ui_name[64]; /* MAX_NAME */ char ui_description[256]; int ui_icon; - + float width, minwidth, maxwidth; float height, minheight, maxheight; short nclass, flag, compatibility; - + /* templates for static sockets */ bNodeSocketTemplate *inputs, *outputs; - + char storagename[64]; /* struct name for DNA */ - + /* Main draw function for the node */ void (*draw_nodetype)(const struct bContext *C, struct ARegion *ar, struct SpaceNode *snode, struct bNodeTree *ntree, struct bNode *node, bNodeInstanceKey key); @@ -184,41 +184,41 @@ typedef struct bNodeType { int (*select_area_func)(struct bNode *node, int x, int y); /// Optional tweak area polling (for grabbing). int (*tweak_area_func)(struct bNode *node, int x, int y); - + /// Called when the node is updated in the editor. void (*updatefunc)(struct bNodeTree *ntree, struct bNode *node); /// Check and update if internal ID data has changed. void (*verifyfunc)(struct bNodeTree *ntree, struct bNode *node, struct ID *id); - + /// Initialize a new node instance of this type after creation. void (*initfunc)(struct bNodeTree *ntree, struct bNode *node); /// Free the node instance. void (*freefunc)(struct bNode *node); /// Make a copy of the node instance. void (*copyfunc)(struct bNodeTree *dest_ntree, struct bNode *dest_node, struct bNode *src_node); - + /* Registerable API callback versions, called in addition to C callbacks */ void (*initfunc_api)(const struct bContext *C, struct PointerRNA *ptr); void (*freefunc_api)(struct PointerRNA *ptr); void (*copyfunc_api)(struct PointerRNA *ptr, struct bNode *src_node); - + /* can this node type be added to a node tree */ int (*poll)(struct bNodeType *ntype, struct bNodeTree *nodetree); /* can this node be added to a node tree */ int (*poll_instance)(struct bNode *node, struct bNodeTree *nodetree); - + /* optional handling of link insertion */ void (*insert_link)(struct bNodeTree *ntree, struct bNode *node, struct bNodeLink *link); /* Update the internal links list, for muting and disconnect operators. */ void (*update_internal_links)(struct bNodeTree *, struct bNode *node); - + /* **** execution callbacks **** */ NodeInitExecFunction initexecfunc; NodeFreeExecFunction freeexecfunc; NodeExecFunction execfunc; /* gpu */ NodeGPUExecFunction gpufunc; - + /* RNA integration */ ExtensionRNA ext; } bNodeType; @@ -279,7 +279,7 @@ typedef struct bNodeTreeType { char ui_name[64]; char ui_description[256]; int ui_icon; - + /* callbacks */ void (*free_cache)(struct bNodeTree *ntree); void (*free_node_cache)(struct bNodeTree *ntree, struct bNode *node); @@ -297,11 +297,11 @@ typedef struct bNodeTreeType { /* Tree update. Overrides nodetype->updatetreefunc! */ void (*update)(struct bNodeTree *ntree); - + int (*validate_link)(struct bNodeTree *ntree, struct bNodeLink *link); void (*node_add_init)(struct bNodeTree *ntree, struct bNode *bnode); - + /* RNA integration */ ExtensionRNA ext; } bNodeTreeType; diff --git a/source/blender/blenkernel/BKE_object.h b/source/blender/blenkernel/BKE_object.h index 482d39b5e68..ab8327d354a 100644 --- a/source/blender/blenkernel/BKE_object.h +++ b/source/blender/blenkernel/BKE_object.h @@ -279,7 +279,7 @@ struct Mesh *BKE_object_get_original_mesh(struct Object *object); int BKE_object_insert_ptcache(struct Object *ob); void BKE_object_delete_ptcache(struct Object *ob, int index); -struct KeyBlock *BKE_object_shapekey_insert(struct Object *ob, const char *name, const bool from_mix); +struct KeyBlock *BKE_object_shapekey_insert(struct Main *bmain, struct Object *ob, const char *name, const bool from_mix); bool BKE_object_shapekey_remove(struct Main *bmain, struct Object *ob, struct KeyBlock *kb); bool BKE_object_shapekey_free(struct Main *bmain, struct Object *ob); diff --git a/source/blender/blenkernel/BKE_ocean.h b/source/blender/blenkernel/BKE_ocean.h index 7a4c7d67040..3ea104e656a 100644 --- a/source/blender/blenkernel/BKE_ocean.h +++ b/source/blender/blenkernel/BKE_ocean.h @@ -1,4 +1,4 @@ -/* +/* * ***** BEGIN GPL LICENSE BLOCK ***** * * This program is free software; you can redistribute it and/or @@ -35,7 +35,7 @@ typedef struct OceanResult { float disp[3]; float normal[3]; float foam; - + /* raw eigenvalues/vectors */ float Jminus; float Jplus; @@ -47,25 +47,25 @@ typedef struct OceanCache { struct ImBuf **ibufs_disp; struct ImBuf **ibufs_foam; struct ImBuf **ibufs_norm; - + const char *bakepath; const char *relbase; - + /* precalculated for time range */ float *time; - + /* constant for time range */ float wave_scale; float chop_amount; float foam_coverage; float foam_fade; - + int start; int end; int duration; int resolution_x; int resolution_y; - + int baked; } OceanCache; @@ -93,7 +93,7 @@ struct OceanCache *BKE_ocean_init_cache( int start, int end, float wave_scale, float chop_amount, float foam_coverage, float foam_fade, int resolution); void BKE_ocean_simulate_cache(struct OceanCache *och, int frame); - + void BKE_ocean_bake(struct Ocean *o, struct OceanCache *och, void (*update_cb)(void *, float progress, int *cancel), void *update_cb_data); void BKE_ocean_cache_eval_uv(struct OceanCache *och, struct OceanResult *ocr, int f, float u, float v); void BKE_ocean_cache_eval_ij(struct OceanCache *och, struct OceanResult *ocr, int f, int i, int j); diff --git a/source/blender/blenkernel/BKE_paint.h b/source/blender/blenkernel/BKE_paint.h index 2ba6446c18f..6ade14b275c 100644 --- a/source/blender/blenkernel/BKE_paint.h +++ b/source/blender/blenkernel/BKE_paint.h @@ -184,7 +184,7 @@ typedef struct SculptSession { int totvert, totpoly; struct KeyBlock *kb; float *vmask; - + /* Mesh connectivity */ struct MeshElemMap *pmap; int *pmap_mem; @@ -210,7 +210,7 @@ typedef struct SculptSession { /* Partial redraw */ bool partial_redraw; - + /* Used to cache the render of the active texture */ unsigned int texcache_side, *texcache, texcache_actual; struct ImagePool *tex_pool; diff --git a/source/blender/blenkernel/BKE_particle.h b/source/blender/blenkernel/BKE_particle.h index d87d63454f0..11aa67d7f25 100644 --- a/source/blender/blenkernel/BKE_particle.h +++ b/source/blender/blenkernel/BKE_particle.h @@ -61,7 +61,7 @@ struct LinkNode; struct KDTree; struct RNG; struct BVHTreeRay; -struct BVHTreeRayHit; +struct BVHTreeRayHit; struct EdgeHash; struct Depsgraph; struct ViewLayer; @@ -90,6 +90,8 @@ typedef struct ParticleSimulationData { * maximum value per time step is important. Only sph_integrate makes use of * this at the moment. Other solvers could, too. */ float courant_num; + /* Only valid during dynamics_step(). */ + struct RNG *rng; } ParticleSimulationData; typedef struct SPHData { @@ -196,7 +198,7 @@ typedef struct ParticleCollisionElement { /* values interpolated from original data*/ float x0[3], x1[3], x2[3], p[3]; - + /* results for found intersection point */ float nor[3], vel[3], uv[2]; @@ -316,6 +318,9 @@ void BKE_particlesettings_free(struct ParticleSettings *part); void psys_free_path_cache(struct ParticleSystem *psys, struct PTCacheEdit *edit); void psys_free(struct Object *ob, struct ParticleSystem *psys); +/* Copy. */ +void psys_copy_particles(struct ParticleSystem *psys_dst, struct ParticleSystem *psys_src); + bool psys_render_simplify_params(struct ParticleSystem *psys, struct ChildParticle *cpa, float *params); void psys_interpolate_uvs(const struct MTFace *tface, int quad, const float w[4], float uvco[2]); @@ -329,9 +334,10 @@ void psys_particle_on_emitter(struct ParticleSystemModifierData *psmd, int distr float utan[3], float vtan[3], float orco[3]); struct ParticleSystemModifierData *psys_get_modifier(struct Object *ob, struct ParticleSystem *psys); -struct ModifierData *object_add_particle_system(struct Scene *scene, struct Object *ob, const char *name); -void object_remove_particle_system(struct Scene *scene, struct Object *ob); -struct ParticleSettings *BKE_particlesettings_add(struct Main *main, const char *name); +struct ModifierData *object_add_particle_system( + struct Main *bmain, struct Scene *scene, struct Object *ob, const char *name); +void object_remove_particle_system(struct Main *bmain, struct Scene *scene, struct Object *ob); +struct ParticleSettings *BKE_particlesettings_add(struct Main *bmain, const char *name); void BKE_particlesettings_copy_data( struct Main *bmain, struct ParticleSettings *part_dst, const struct ParticleSettings *part_src, const int flag); diff --git a/source/blender/blenkernel/BKE_pointcache.h b/source/blender/blenkernel/BKE_pointcache.h index 89f1aa5eadd..21673213db1 100644 --- a/source/blender/blenkernel/BKE_pointcache.h +++ b/source/blender/blenkernel/BKE_pointcache.h @@ -185,7 +185,7 @@ typedef struct PTCacheID { } PTCacheID; typedef struct PTCacheBaker { - struct Main *main; + struct Main *bmain; struct Scene *scene; struct ViewLayer *view_layer; struct Depsgraph *depsgraph; @@ -246,13 +246,25 @@ typedef struct PTCacheUndo { size_t undo_size; } PTCacheUndo; +enum { + /* Modifier stack got evaluated during particle edit mode, need to copy + * new evaluated particles to the edit struct. + */ + PT_CACHE_EDIT_UPDATE_PARTICLE_FROM_EVAL = (1 << 0), +}; + typedef struct PTCacheEdit { + int flags; + PTCacheEditPoint *points; struct PTCacheID pid; /* particles stuff */ struct ParticleSystem *psys; + struct ParticleSystem *psys_eval; + struct ParticleSystemModifierData *psmd; + struct ParticleSystemModifierData *psmd_eval; struct KDTree *emitter_field; float *emitter_cosnos; /* localspace face centers and normals (average of its verts), from the derived mesh */ int *mirror_cache; @@ -278,7 +290,8 @@ void BKE_ptcache_id_from_dynamicpaint(PTCacheID *pid, struct Object *ob, struct void BKE_ptcache_id_from_rigidbody(PTCacheID *pid, struct Object *ob, struct RigidBodyWorld *rbw); PTCacheID BKE_ptcache_id_find(struct Object *ob, struct Scene *scene, struct PointCache *cache); -void BKE_ptcache_ids_from_object(struct ListBase *lb, struct Object *ob, struct Scene *scene, int duplis); +void BKE_ptcache_ids_from_object( + struct ListBase *lb, struct Object *ob, struct Scene *scene, int duplis); /***************** Global funcs ****************************/ void BKE_ptcache_remove(void); diff --git a/source/blender/blenkernel/BKE_report.h b/source/blender/blenkernel/BKE_report.h index 70feff17151..2a79c7f5d58 100644 --- a/source/blender/blenkernel/BKE_report.h +++ b/source/blender/blenkernel/BKE_report.h @@ -74,6 +74,6 @@ bool BKE_report_write_file(const char *filepath, ReportList *reports, const char #ifdef __cplusplus } #endif - + #endif diff --git a/source/blender/blenkernel/BKE_rigidbody.h b/source/blender/blenkernel/BKE_rigidbody.h index 016a531db95..b7d27cc7101 100644 --- a/source/blender/blenkernel/BKE_rigidbody.h +++ b/source/blender/blenkernel/BKE_rigidbody.h @@ -29,7 +29,7 @@ * \ingroup blenkernel * \brief API for Blender-side Rigid Body stuff */ - + #ifndef __BKE_RIGIDBODY_H__ #define __BKE_RIGIDBODY_H__ @@ -80,7 +80,7 @@ void BKE_rigidbody_calc_center_of_mass(struct Object *ob, float r_center[3]); /* Utilities */ struct RigidBodyWorld *BKE_rigidbody_get_world(struct Scene *scene); -void BKE_rigidbody_remove_object(struct Scene *scene, struct Object *ob); +void BKE_rigidbody_remove_object(struct Main *bmain, struct Scene *scene, struct Object *ob); void BKE_rigidbody_remove_constraint(struct Scene *scene, struct Object *ob); /* -------------- */ diff --git a/source/blender/blenkernel/BKE_scene.h b/source/blender/blenkernel/BKE_scene.h index 0606108a23b..270ab60c02b 100644 --- a/source/blender/blenkernel/BKE_scene.h +++ b/source/blender/blenkernel/BKE_scene.h @@ -83,7 +83,7 @@ void BKE_scene_free(struct Scene *sce); void BKE_scene_init(struct Scene *sce); struct Scene *BKE_scene_add(struct Main *bmain, const char *name); -void BKE_scene_remove_rigidbody_object(struct Scene *scene, struct Object *ob); +void BKE_scene_remove_rigidbody_object(struct Main *bmain, struct Scene *scene, struct Object *ob); bool BKE_scene_object_find(struct Scene *scene, struct Object *ob); struct Object *BKE_scene_object_find_by_name(struct Scene *scene, const char *name); diff --git a/source/blender/blenkernel/BKE_screen.h b/source/blender/blenkernel/BKE_screen.h index 0b95152ad8e..1b42ce97940 100644 --- a/source/blender/blenkernel/BKE_screen.h +++ b/source/blender/blenkernel/BKE_screen.h @@ -216,6 +216,8 @@ typedef struct PanelType { int (*poll)(const struct bContext *C, struct PanelType *pt); /* draw header (optional) */ void (*draw_header)(const struct bContext *C, struct Panel *pa); + /* draw header preset (optional) */ + void (*draw_header_preset)(const struct bContext *C, struct Panel *pa); /* draw entirely, view changes should be handled here */ void (*draw)(const struct bContext *C, struct Panel *pa); @@ -305,6 +307,7 @@ typedef struct Menu { /* spacetypes */ struct SpaceType *BKE_spacetype_from_id(int spaceid); +struct ARegionType *BKE_regiontype_from_id_or_first(struct SpaceType *st, int regionid); struct ARegionType *BKE_regiontype_from_id(struct SpaceType *st, int regionid); const struct ListBase *BKE_spacetypes_list(void); void BKE_spacetype_register(struct SpaceType *st); diff --git a/source/blender/blenkernel/BKE_sequencer.h b/source/blender/blenkernel/BKE_sequencer.h index 63c91ef9635..51f61c8352c 100644 --- a/source/blender/blenkernel/BKE_sequencer.h +++ b/source/blender/blenkernel/BKE_sequencer.h @@ -138,38 +138,38 @@ struct SeqEffectHandle { /* constructors & destructor */ /* init is _only_ called on first creation */ void (*init)(struct Sequence *seq); - - /* number of input strips needed + + /* number of input strips needed * (called directly after construction) */ int (*num_inputs)(void); - + /* load is called first time after readblenfile in * get_sequence_effect automatically */ void (*load)(struct Sequence *seq); - + /* duplicate */ void (*copy)(struct Sequence *dst, struct Sequence *src); - + /* destruct */ void (*free)(struct Sequence *seq); - + /* returns: -1: no input needed, * 0: no early out, * 1: out = ibuf1, * 2: out = ibuf2 */ - int (*early_out)(struct Sequence *seq, float facf0, float facf1); - + int (*early_out)(struct Sequence *seq, float facf0, float facf1); + /* stores the y-range of the effect IPO */ void (*store_icu_yrange)(struct Sequence *seq, short adrcode, float *ymin, float *ymax); - + /* stores the default facf0 and facf1 if no IPO is present */ void (*get_default_fac)(struct Sequence *seq, float cfra, float *facf0, float *facf1); - + /* execute the effect * sequence effects are only required to either support * float-rects or byte-rects * (mixed cases are handled one layer up...) */ - + struct ImBuf * (*execute)(const SeqRenderData *context, struct Sequence *seq, float cfra, float facf0, float facf1, struct ImBuf *ibuf1, struct ImBuf *ibuf2, struct ImBuf *ibuf3); @@ -276,7 +276,7 @@ void BKE_sequencer_cache_cleanup(void); /* returned ImBuf is properly refed and has to be freed */ struct ImBuf *BKE_sequencer_cache_get(const SeqRenderData *context, struct Sequence *seq, float cfra, eSeqStripElemIBuf type); -/* passed ImBuf is properly refed, so ownership is *not* +/* passed ImBuf is properly refed, so ownership is *not* * transferred to the cache. * you can pass the same ImBuf multiple times to the cache without problems. */ @@ -495,6 +495,6 @@ struct ImBuf *BKE_sequencer_render_mask_input( int cfra, int fra_offset, bool make_float); void BKE_sequencer_color_balance_apply(struct StripColorBalance *cb, struct ImBuf *ibuf, float mul, bool make_float, struct ImBuf *mask_input); -void BKE_sequencer_all_free_anim_ibufs(int cfra); +void BKE_sequencer_all_free_anim_ibufs(struct Main *bmain, int cfra); #endif /* __BKE_SEQUENCER_H__ */ diff --git a/source/blender/blenkernel/BKE_shrinkwrap.h b/source/blender/blenkernel/BKE_shrinkwrap.h index 8a809b606f1..c92b0fd1272 100644 --- a/source/blender/blenkernel/BKE_shrinkwrap.h +++ b/source/blender/blenkernel/BKE_shrinkwrap.h @@ -47,7 +47,6 @@ */ struct Object; -struct DerivedMesh; struct Mesh; struct MVert; struct MDeformVert; diff --git a/source/blender/blenkernel/BKE_studiolight.h b/source/blender/blenkernel/BKE_studiolight.h index 5e386fde528..af7ef9a383e 100644 --- a/source/blender/blenkernel/BKE_studiolight.h +++ b/source/blender/blenkernel/BKE_studiolight.h @@ -34,6 +34,8 @@ * Studio lighting for the 3dview */ +#include "BKE_context.h" + #include "BLI_sys_types.h" #include "DNA_space_types.h" @@ -51,13 +53,36 @@ #define STUDIOLIGHT_Y_NEG 3 #define STUDIOLIGHT_Z_POS 4 #define STUDIOLIGHT_Z_NEG 5 -#define STUDIOLIGHT_ICON_ID_TYPE_RADIANCE 0 -#define STUDIOLIGHT_ICON_ID_TYPE_IRRADIANCE 1 + +#define STUDIOLIGHT_ICON_ID_TYPE_RADIANCE (1 << 0) +#define STUDIOLIGHT_ICON_ID_TYPE_IRRADIANCE (1 << 1) +#define STUDIOLIGHT_ICON_ID_TYPE_MATCAP (1 << 2) +#define STUDIOLIGHT_ICON_ID_TYPE_MATCAP_FLIPPED (1 << 3) + +#define STUDIOLIGHT_ICON_SIZE 96 + +#define STUDIOLIGHT_SPHERICAL_HARMONICS_LEVEL 2 +#define STUDIOLIGHT_SPHERICAL_HARMONICS_MAX_COMPONENTS 9 + + +#if STUDIOLIGHT_SPHERICAL_HARMONICS_LEVEL == 0 +#define STUDIOLIGHT_SPHERICAL_HARMONICS_COMPONENTS 1 +#endif + +#if STUDIOLIGHT_SPHERICAL_HARMONICS_LEVEL == 1 +#define STUDIOLIGHT_SPHERICAL_HARMONICS_COMPONENTS 4 +#endif + +#if STUDIOLIGHT_SPHERICAL_HARMONICS_LEVEL == 2 +#define STUDIOLIGHT_SPHERICAL_HARMONICS_COMPONENTS 9 +#endif struct GPUTexture; +struct StudioLight; +/* StudioLight.flag */ enum StudioLightFlag { - STUDIOLIGHT_DIFFUSE_LIGHT_CALCULATED = (1 << 0), + STUDIOLIGHT_SPHERICAL_HARMONICS_COEFFICIENTS_CALCULATED = (1 << 0), STUDIOLIGHT_LIGHT_DIRECTION_CALCULATED = (1 << 1), STUDIOLIGHT_INTERNAL = (1 << 2), STUDIOLIGHT_EXTERNAL_FILE = (1 << 3), @@ -72,26 +97,43 @@ enum StudioLightFlag { STUDIOLIGHT_RADIANCE_BUFFERS_CALCULATED = (1 << 11), STUDIOLIGHT_UI_EXPANDED = (1 << 13), } StudioLightFlag; + #define STUDIOLIGHT_FLAG_ALL (STUDIOLIGHT_INTERNAL | STUDIOLIGHT_EXTERNAL_FILE) #define STUDIOLIGHT_FLAG_ORIENTATIONS (STUDIOLIGHT_ORIENTATION_CAMERA | STUDIOLIGHT_ORIENTATION_WORLD | STUDIOLIGHT_ORIENTATION_VIEWNORMAL) #define STUDIOLIGHT_ORIENTATIONS_MATERIAL_MODE (STUDIOLIGHT_INTERNAL | STUDIOLIGHT_ORIENTATION_WORLD) #define STUDIOLIGHT_ORIENTATIONS_SOLID (STUDIOLIGHT_INTERNAL | STUDIOLIGHT_ORIENTATION_CAMERA | STUDIOLIGHT_ORIENTATION_WORLD) +typedef void StudioLightFreeFunction(struct StudioLight *, void *data); + typedef struct StudioLight { struct StudioLight *next, *prev; + + int index; int flag; char name[FILE_MAXFILE]; char path[FILE_MAX]; - int irradiance_icon_id; - int radiance_icon_id; - int index; - float diffuse_light[6][3]; + char *path_irr_cache; + char *path_sh_cache; + int icon_id_irradiance; + int icon_id_radiance; + int icon_id_matcap; + int icon_id_matcap_flipped; + float spherical_harmonics_coefs[STUDIOLIGHT_SPHERICAL_HARMONICS_COMPONENTS][3]; float light_direction[3]; ImBuf *equirectangular_radiance_buffer; ImBuf *equirectangular_irradiance_buffer; ImBuf *radiance_cubemap_buffers[6]; struct GPUTexture *equirectangular_radiance_gputexture; struct GPUTexture *equirectangular_irradiance_gputexture; + float *gpu_matcap_3components; /* 3 channel buffer for GPU_R11F_G11F_B10F */ + + /* + Free function to clean up the running icons previews (wmJob) the usage is in + interface_icons. Please be aware that this was build to handle only one free function + that cleans up all icons. just to keep the code simple. + */ + StudioLightFreeFunction *free_function; + void* free_function_data; } StudioLight; void BKE_studiolight_init(void); @@ -99,9 +141,11 @@ void BKE_studiolight_free(void); struct StudioLight *BKE_studiolight_find(const char *name, int flag); struct StudioLight *BKE_studiolight_findindex(int index, int flag); struct StudioLight *BKE_studiolight_find_first(int flag); -unsigned int *BKE_studiolight_preview(StudioLight *sl, int icon_size, int icon_id_type); +void BKE_studiolight_preview(uint* icon_buffer, StudioLight *sl, int icon_id_type); struct ListBase *BKE_studiolight_listbase(void); void BKE_studiolight_ensure_flag(StudioLight *sl, int flag); void BKE_studiolight_refresh(void); +void BKE_studiolight_set_free_function(StudioLight *sl, StudioLightFreeFunction *free_function, void *data); +void BKE_studiolight_unset_icon_id(StudioLight *sl, int icon_id); #endif /* __BKE_STUDIOLIGHT_H__ */ diff --git a/source/blender/blenkernel/BKE_undo_system.h b/source/blender/blenkernel/BKE_undo_system.h index 05093deec70..a75606a17cb 100644 --- a/source/blender/blenkernel/BKE_undo_system.h +++ b/source/blender/blenkernel/BKE_undo_system.h @@ -135,6 +135,7 @@ extern const UndoType *BKE_UNDOSYS_TYPE_TEXT; UndoStack *BKE_undosys_stack_create(void); void BKE_undosys_stack_destroy(UndoStack *ustack); void BKE_undosys_stack_clear(UndoStack *ustack); +void BKE_undosys_stack_clear_active(UndoStack *ustack); bool BKE_undosys_stack_has_undo(UndoStack *ustack, const char *name); void BKE_undosys_stack_init_from_main(UndoStack *ustack, struct Main *bmain); void BKE_undosys_stack_init_from_context(UndoStack *ustack, struct bContext *C); diff --git a/source/blender/blenkernel/BKE_workspace.h b/source/blender/blenkernel/BKE_workspace.h index 5442fd43ce5..03d24ac53d1 100644 --- a/source/blender/blenkernel/BKE_workspace.h +++ b/source/blender/blenkernel/BKE_workspace.h @@ -44,6 +44,7 @@ struct WorkSpaceInstanceHook *BKE_workspace_instance_hook_create(const struct Ma void BKE_workspace_instance_hook_free(const struct Main *bmain, struct WorkSpaceInstanceHook *hook); struct WorkSpaceLayout *BKE_workspace_layout_add( + struct Main *bmain, struct WorkSpace *workspace, struct bScreen *screen, const char *name) ATTR_NONNULL(); diff --git a/source/blender/blenkernel/BKE_writeavi.h b/source/blender/blenkernel/BKE_writeavi.h index ca295c51f5d..3bd0689a93a 100644 --- a/source/blender/blenkernel/BKE_writeavi.h +++ b/source/blender/blenkernel/BKE_writeavi.h @@ -38,7 +38,7 @@ extern "C" { /* generic blender movie support, could move to own module */ -struct RenderData; +struct RenderData; struct ReportList; struct Scene; diff --git a/source/blender/blenkernel/CMakeLists.txt b/source/blender/blenkernel/CMakeLists.txt index 867b5884114..94d762214f2 100644 --- a/source/blender/blenkernel/CMakeLists.txt +++ b/source/blender/blenkernel/CMakeLists.txt @@ -140,6 +140,7 @@ set(SRC intern/mesh.c intern/mesh_convert.c intern/mesh_evaluate.c + intern/mesh_iterators.c intern/mesh_mapping.c intern/mesh_merge.c intern/mesh_remap.c @@ -272,6 +273,7 @@ set(SRC BKE_mball.h BKE_mball_tessellate.h BKE_mesh.h + BKE_mesh_iterators.h BKE_mesh_mapping.h BKE_mesh_remap.h BKE_mesh_tangent.h diff --git a/source/blender/blenkernel/intern/CCGSubSurf.c b/source/blender/blenkernel/intern/CCGSubSurf.c index 68bcfa878ac..81b1afa3621 100644 --- a/source/blender/blenkernel/intern/CCGSubSurf.c +++ b/source/blender/blenkernel/intern/CCGSubSurf.c @@ -277,7 +277,7 @@ CCGSubSurf *ccgSubSurf_new(CCGMeshIFC *ifc, int subdivLevels, CCGAllocatorIFC *a ss->fMap = ccg_ehash_new(0, &ss->allocatorIFC, ss->allocator); ss->meshIFC = *ifc; - + ss->subdivLevels = subdivLevels; ss->numGrids = 0; ss->allowEdgeCreation = 0; @@ -489,8 +489,8 @@ CCGError ccgSubSurf_initFullSync(CCGSubSurf *ss) ss->currentAge++; - ss->oldVMap = ss->vMap; - ss->oldEMap = ss->eMap; + ss->oldVMap = ss->vMap; + ss->oldEMap = ss->eMap; ss->oldFMap = ss->fMap; ss->vMap = ccg_ehash_new(0, &ss->allocatorIFC, ss->allocator); @@ -592,7 +592,7 @@ CCGError ccgSubSurf_syncVert(CCGSubSurf *ss, CCGVertHDL vHDL, const void *vertDa void **prevp; CCGVert *v = NULL; short seamflag = (seam) ? Vert_eSeam : 0; - + if (ss->syncState == eSyncState_Partial) { v = ccg_ehash_lookupWithPrev(ss->vMap, vHDL, &prevp); if (!v) { @@ -937,7 +937,7 @@ void ccgSubSurf__effectedFaceNeighbours(CCGSubSurf *ss, CCGFace **faces, int num for (j = 0; j < v->numFaces; j++) if (!(v->faces[j]->flags & Face_eEffected)) break; - + if (j == v->numFaces) { arrayV[numV++] = v; v->flags |= Vert_eEffected; @@ -952,7 +952,7 @@ void ccgSubSurf__effectedFaceNeighbours(CCGSubSurf *ss, CCGFace **faces, int num for (j = 0; j < e->numFaces; j++) if (!(e->faces[j]->flags & Face_eEffected)) break; - + if (j == e->numFaces) { e->flags |= Edge_eEffected; arrayE[numE++] = e; @@ -1550,11 +1550,11 @@ int ccgSubSurf_getNumFinalFaces(const CCGSubSurf *ss) void CCG_key(CCGKey *key, const CCGSubSurf *ss, int level) { key->level = level; - + key->elem_size = ss->meshIFC.vertDataSize; key->has_normals = ss->calcVertNormals; key->num_layers = ss->meshIFC.numLayers; - + /* if normals are present, always the last three floats of an * element */ if (key->has_normals) diff --git a/source/blender/blenkernel/intern/DerivedMesh.c b/source/blender/blenkernel/intern/DerivedMesh.c index c081bb0799f..5a4dc479c10 100644 --- a/source/blender/blenkernel/intern/DerivedMesh.c +++ b/source/blender/blenkernel/intern/DerivedMesh.c @@ -136,7 +136,7 @@ static MFace *dm_getTessFaceArray(DerivedMesh *dm) if (!mface) { int numTessFaces = dm->getNumTessFaces(dm); - + if (!numTessFaces) { /* Do not add layer if there's no elements in it, this leads to issues later when * this layer is needed with non-zero size, but currently CD stuff does not check @@ -144,7 +144,7 @@ static MFace *dm_getTessFaceArray(DerivedMesh *dm) * added (sergey) */ return NULL; } - + mface = CustomData_add_layer(&dm->faceData, CD_MFACE, CD_CALLOC, NULL, numTessFaces); CustomData_set_layer_flag(&dm->faceData, CD_MFACE, CD_FLAG_TEMPORARY); dm->copyTessFaceArray(dm, mface); @@ -346,7 +346,7 @@ void DM_init( dm->numPolyData = numPolys; DM_init_funcs(dm); - + dm->needsFree = 1; dm->dirty = 0; @@ -754,7 +754,7 @@ void DM_to_mesh(DerivedMesh *dm, Mesh *me, Object *ob, CustomDataMask mask, bool if (CustomData_has_layer(&dm->vertData, CD_SHAPEKEY)) { KeyBlock *kb; int uid; - + if (ob) { kb = BLI_findlink(&me->key->block, ob->shapenr - 1); if (kb) { @@ -780,7 +780,7 @@ void DM_to_mesh(DerivedMesh *dm, Mesh *me, Object *ob, CustomDataMask mask, bool if (ob) { BKE_mesh_texspace_copy_from_object(&tmp, ob); } - + /* not all DerivedMeshes store their verts/edges/faces in CustomData, so * we set them here in case they are missing */ if (!CustomData_has_layer(&tmp.vdata, CD_MVERT)) { @@ -861,18 +861,18 @@ void DM_to_meshkey(DerivedMesh *dm, Mesh *me, KeyBlock *kb) int a, totvert = dm->getNumVerts(dm); float *fp; MVert *mvert; - + if (totvert == 0 || me->totvert == 0 || me->totvert != totvert) { return; } - + if (kb->data) MEM_freeN(kb->data); kb->data = MEM_malloc_arrayN(me->key->elemsize, me->totvert, "kb->data"); kb->totelem = totvert; - + fp = kb->data; mvert = dm->getVertDataArray(dm, CD_MVERT); - + for (a = 0; a < kb->totelem; a++, fp += 3, mvert++) { copy_v3_v3(fp, mvert->co); } @@ -1146,10 +1146,10 @@ void DM_interp_poly_data( DerivedMesh *mesh_create_derived(Mesh *me, float (*vertCos)[3]) { DerivedMesh *dm = CDDM_from_mesh(me); - + if (!dm) return NULL; - + if (vertCos) { CDDM_apply_vert_coords(dm, vertCos); } @@ -1170,7 +1170,7 @@ DerivedMesh *mesh_create_derived_for_modifier( ModifierEvalContext mectx = {depsgraph, ob, 0}; md->scene = scene; - + if (!(md->mode & eModifierMode_Realtime)) { return NULL; } @@ -1178,11 +1178,11 @@ DerivedMesh *mesh_create_derived_for_modifier( if (mti->isDisabled && mti->isDisabled(md, 0)) { return NULL; } - + if (build_shapekey_layers && me->key && (kb = BLI_findlink(&me->key->block, ob->shapenr - 1))) { BKE_keyblock_convert_to_mesh(kb, me); } - + if (mti->type == eModifierTypeType_OnlyDeform) { int numVerts; float (*deformedVerts)[3] = BKE_mesh_vertexCos_get(me, &numVerts); @@ -1192,7 +1192,7 @@ DerivedMesh *mesh_create_derived_for_modifier( if (build_shapekey_layers) add_shapekey_layers(dm, me, ob); - + MEM_freeN(deformedVerts); } else { @@ -1200,7 +1200,7 @@ DerivedMesh *mesh_create_derived_for_modifier( if (build_shapekey_layers) add_shapekey_layers(tdm, me, ob); - + dm = modwrap_applyModifier(md, &mectx, tdm); ASSERT_IS_VALID_DM(dm); @@ -1220,13 +1220,13 @@ static float (*get_editbmesh_orco_verts(BMEditMesh *em))[3] /* these may not really be the orco's, but it's only for preview. * could be solver better once, but isn't simple */ - + orco = MEM_malloc_arrayN(em->bm->totvert, sizeof(float) * 3, "BMEditMesh Orco"); BM_ITER_MESH_INDEX (eve, &iter, em->bm, BM_VERTS_OF_MESH, i) { copy_v3_v3(orco[i], eve->co); } - + return orco; } @@ -1490,7 +1490,7 @@ static void calc_weightpaint_vert_color( const int draw_flag) { float input = 0.0f; - + bool show_alert_color = false; if ((defbase_sel_tot > 1) && (draw_flag & CALC_WP_MULTIPAINT)) { @@ -1871,35 +1871,35 @@ static void shapekey_layers_to_keyblocks(DerivedMesh *dm, Mesh *me, int actshape { KeyBlock *kb; int i, j, tot; - + if (!me->key) return; - + tot = CustomData_number_of_layers(&dm->vertData, CD_SHAPEKEY); for (i = 0; i < tot; i++) { CustomDataLayer *layer = &dm->vertData.layers[CustomData_get_layer_index_n(&dm->vertData, CD_SHAPEKEY, i)]; float (*cos)[3], (*kbcos)[3]; - + for (kb = me->key->block.first; kb; kb = kb->next) { if (kb->uid == layer->uid) break; } - + if (!kb) { kb = BKE_keyblock_add(me->key, layer->name); kb->uid = layer->uid; } - + if (kb->data) MEM_freeN(kb->data); - + cos = CustomData_get_layer_n(&dm->vertData, CD_SHAPEKEY, i); kb->totelem = dm->numVertData; kb->data = kbcos = MEM_malloc_arrayN(kb->totelem, 3 * sizeof(float), "kbcos DerivedMesh.c"); if (kb->uid == actshape_uid) { MVert *mvert = dm->getVertArray(dm); - + for (j = 0; j < dm->numVertData; j++, kbcos++, mvert++) { copy_v3_v3(*kbcos, mvert->co); } @@ -1910,12 +1910,12 @@ static void shapekey_layers_to_keyblocks(DerivedMesh *dm, Mesh *me, int actshape } } } - + for (kb = me->key->block.first; kb; kb = kb->next) { if (kb->totelem != dm->numVertData) { if (kb->data) MEM_freeN(kb->data); - + kb->totelem = dm->numVertData; kb->data = MEM_calloc_arrayN(kb->totelem, 3 * sizeof(float), "kb->data derivedmesh.c"); fprintf(stderr, "%s: lost a shapekey layer: '%s'! (bmesh internal error)\n", __func__, kb->name); @@ -2051,6 +2051,7 @@ static void mesh_calc_modifiers( ModifierApplyFlag app_flags = useRenderParams ? MOD_APPLY_RENDER : 0; ModifierApplyFlag deform_app_flags = app_flags; + BLI_assert((me->id.tag & LIB_TAG_COPIED_ON_WRITE_EVAL_RESULT) == 0); if (useCache) app_flags |= MOD_APPLY_USECACHE; @@ -2095,13 +2096,13 @@ static void mesh_calc_modifiers( if (useDeform) { if (inputVertexCos) deformedVerts = inputVertexCos; - + /* Apply all leading deforming modifiers */ for (; md; md = md->next, curr = curr->next) { const ModifierTypeInfo *mti = modifierType_getInfo(md->type); md->scene = scene; - + if (!modifier_isEnabled(scene, md, required_mode)) { continue; } @@ -2119,7 +2120,7 @@ static void mesh_calc_modifiers( else { break; } - + /* grab modifiers until index i */ if ((index != -1) && (BLI_findindex(&ob->modifiers, md) >= index)) break; @@ -2142,7 +2143,7 @@ static void mesh_calc_modifiers( BLI_assert(!build_shapekey_layers); //if (build_shapekey_layers) // add_shapekey_layers(*r_deform_mesh, me, ob); - + if (deformedVerts) { BKE_mesh_apply_vert_coords(*r_deform_mesh, deformedVerts); } @@ -2158,7 +2159,7 @@ static void mesh_calc_modifiers( /* Now apply all remaining modifiers. If useDeform is off then skip - * OnlyDeform ones. + * OnlyDeform ones. */ Mesh *mesh = NULL; Mesh *orco_mesh = NULL; @@ -2317,7 +2318,7 @@ static void mesh_calc_modifiers( } } - + /* set the Mesh to only copy needed data */ mask = curr->mask; /* needMapping check here fixes bug [#28112], otherwise it's @@ -2584,7 +2585,7 @@ bool editbmesh_modifier_is_enabled(Scene *scene, ModifierData *md, DerivedMesh * modifier_setError(md, "Modifier requires original data, bad stack position"); return false; } - + return true; } @@ -2646,7 +2647,7 @@ static void editbmesh_calc_modifiers( const ModifierTypeInfo *mti = modifierType_getInfo(md->type); md->scene = scene; - + if (!editbmesh_modifier_is_enabled(scene, md, dm)) { continue; } @@ -3016,8 +3017,9 @@ static void mesh_build_data( if ((ob->mode & OB_MODE_ALL_SCULPT) && ob->sculpt) { /* create PBVH immediately (would be created on the fly too, * but this avoids waiting on first stroke) */ - - BKE_sculpt_update_mesh_elements(depsgraph, scene, scene->toolsettings->sculpt, ob, false, false); + /* XXX Disabled for now. + * This can create horrible nasty bugs by generating re-entrant call of mesh_get_eval_final! */ +// BKE_sculpt_update_mesh_elements(depsgraph, scene, scene->toolsettings->sculpt, ob, false, false); } BLI_assert(!(ob->derivedFinal->dirty & DM_DIRTY_NORMALS)); @@ -3054,14 +3056,14 @@ static void editbmesh_build_data( static CustomDataMask object_get_datamask(const Depsgraph *depsgraph, Object *ob, bool *r_need_mapping) { ViewLayer *view_layer = DEG_get_evaluated_view_layer(depsgraph); - Object *actob = view_layer->basact ? view_layer->basact->object : NULL; + Object *actob = view_layer->basact ? DEG_get_original_object(view_layer->basact->object) : NULL; CustomDataMask mask = ob->customdata_mask; if (r_need_mapping) { *r_need_mapping = false; } - if (ob == actob) { + if (DEG_get_original_object(ob) == actob) { bool editing = BKE_paint_select_face_test(ob); /* weight paint and face select need original indices because of selection buffer drawing */ @@ -3193,7 +3195,7 @@ Mesh *mesh_get_eval_deform(struct Depsgraph *depsgraph, Scene *scene, Object *ob DerivedMesh *mesh_create_derived_render(struct Depsgraph *depsgraph, Scene *scene, Object *ob, CustomDataMask dataMask) { DerivedMesh *final; - + mesh_calc_modifiers_dm( depsgraph, scene, ob, NULL, 1, false, dataMask, -1, false, false, false, NULL, &final); @@ -3238,7 +3240,7 @@ DerivedMesh *mesh_create_derived_no_deform( float (*vertCos)[3], CustomDataMask dataMask) { DerivedMesh *final; - + mesh_calc_modifiers_dm( depsgraph, scene, ob, vertCos, 0, false, dataMask, -1, false, false, false, NULL, &final); @@ -3352,13 +3354,13 @@ DMCoNo *mesh_get_mapped_verts_nors(Scene *scene, Object *ob) Mesh *me = ob->data; DerivedMesh *dm; DMCoNo *vertexcosnos; - + /* lets prevent crashing... */ if (ob->type != OB_MESH || me->totvert == 0) return NULL; - + dm = mesh_get_derived_final(scene, ob, CD_MASK_BAREMESH | CD_MASK_ORIGINDEX); - + if (dm->foreachMappedVert) { vertexcosnos = MEM_calloc_arrayN(me->totvert, sizeof(DMCoNo), "vertexcosnos map"); dm->foreachMappedVert(dm, make_vertexcosnos__mapFunc, vertexcosnos); @@ -3371,7 +3373,7 @@ DMCoNo *mesh_get_mapped_verts_nors(Scene *scene, Object *ob) dm->getVertNo(dm, a, v_co_no->no); } } - + dm->release(dm); return vertexcosnos; } diff --git a/source/blender/blenkernel/intern/action.c b/source/blender/blenkernel/intern/action.c index 01f6eab261f..9f5b81a8915 100644 --- a/source/blender/blenkernel/intern/action.c +++ b/source/blender/blenkernel/intern/action.c @@ -32,7 +32,7 @@ #include <string.h> #include <math.h> #include <stdlib.h> -#include <stddef.h> +#include <stddef.h> #include "MEM_guardedalloc.h" @@ -88,11 +88,11 @@ bAction *BKE_action_add(Main *bmain, const char name[]) { bAction *act; - + act = BKE_libblock_alloc(bmain, ID_AC, name, 0); - + return act; -} +} /* .................................. */ @@ -106,15 +106,15 @@ void BKE_action_make_local(Main *bmain, bAction *act, const bool lib_local) /** Free (or release) any data used by this action (does not free the action itself). */ void BKE_action_free(bAction *act) -{ +{ /* No animdata here. */ /* Free F-Curves */ free_fcurves(&act->curves); - + /* Free groups */ BLI_freelistN(&act->groups); - + /* Free pose-references (aka local markers) */ BLI_freelistN(&act->markers); } @@ -179,14 +179,14 @@ bAction *BKE_action_copy(Main *bmain, const bAction *act_src) bActionGroup *get_active_actiongroup(bAction *act) { bActionGroup *agrp = NULL; - + if (act && act->groups.first) { for (agrp = act->groups.first; agrp; agrp = agrp->next) { if (agrp->flag & AGRP_ACTIVE) break; } } - + return agrp; } @@ -194,11 +194,11 @@ bActionGroup *get_active_actiongroup(bAction *act) void set_active_action_group(bAction *act, bActionGroup *agrp, short select) { bActionGroup *grp; - + /* sanity checks */ if (act == NULL) return; - + /* Deactive all others */ for (grp = act->groups.first; grp; grp = grp->next) { if ((grp == agrp) && (select)) @@ -217,7 +217,7 @@ void action_group_colors_sync(bActionGroup *grp, const bActionGroup *ref_grp) /* copy theme colors on-to group's custom color in case user tries to edit color */ bTheme *btheme = U.themes.first; ThemeWireColor *col_set = &btheme->tarm[(grp->customCol - 1)]; - + memcpy(&grp->cs, col_set, sizeof(ThemeWireColor)); } else { @@ -243,69 +243,69 @@ void action_group_colors_sync(bActionGroup *grp, const bActionGroup *ref_grp) bActionGroup *action_groups_add_new(bAction *act, const char name[]) { bActionGroup *agrp; - + /* sanity check: must have action and name */ if (ELEM(NULL, act, name)) return NULL; - + /* allocate a new one */ agrp = MEM_callocN(sizeof(bActionGroup), "bActionGroup"); - + /* make it selected, with default name */ agrp->flag = AGRP_SELECTED; BLI_strncpy(agrp->name, name[0] ? name : DATA_("Group"), sizeof(agrp->name)); - + /* add to action, and validate */ BLI_addtail(&act->groups, agrp); BLI_uniquename(&act->groups, agrp, DATA_("Group"), '.', offsetof(bActionGroup, name), sizeof(agrp->name)); - + /* return the new group */ return agrp; } -/* Add given channel into (active) group +/* Add given channel into (active) group * - assumes that channel is not linked to anything anymore * - always adds at the end of the group */ void action_groups_add_channel(bAction *act, bActionGroup *agrp, FCurve *fcurve) -{ +{ /* sanity checks */ if (ELEM(NULL, act, agrp, fcurve)) return; - + /* if no channels anywhere, just add to two lists at the same time */ if (BLI_listbase_is_empty(&act->curves)) { fcurve->next = fcurve->prev = NULL; - + agrp->channels.first = agrp->channels.last = fcurve; act->curves.first = act->curves.last = fcurve; } - - /* if the group already has channels, the F-Curve can simply be added to the list + + /* if the group already has channels, the F-Curve can simply be added to the list * (i.e. as the last channel in the group) */ else if (agrp->channels.first) { - /* if the group's last F-Curve is the action's last F-Curve too, + /* if the group's last F-Curve is the action's last F-Curve too, * then set the F-Curve as the last for the action first so that * the lists will be in sync after linking */ if (agrp->channels.last == act->curves.last) act->curves.last = fcurve; - + /* link in the given F-Curve after the last F-Curve in the group, * which means that it should be able to fit in with the rest of the * list seamlessly */ BLI_insertlinkafter(&agrp->channels, agrp->channels.last, fcurve); } - + /* otherwise, need to find the nearest F-Curve in group before/after current to link with */ else { bActionGroup *grp; - + /* firstly, link this F-Curve to the group */ agrp->channels.first = agrp->channels.last = fcurve; - + /* step through the groups preceding this one, finding the F-Curve there to attach this one after */ for (grp = agrp->prev; grp; grp = grp->prev) { /* if this group has F-Curves, we want weave the given one in right after the last channel there, @@ -319,18 +319,18 @@ void action_groups_add_channel(bAction *act, bActionGroup *agrp, FCurve *fcurve) break; } } - + /* if grp is NULL, that means we fell through, and this F-Curve should be added as the new first - * since group is (effectively) the first group. Thus, the existing first F-Curve becomes the + * since group is (effectively) the first group. Thus, the existing first F-Curve becomes the * second in the chain, etc. etc. */ if (grp == NULL) BLI_insertlinkbefore(&act->curves, act->curves.first, fcurve); } - + /* set the F-Curve's new group */ fcurve->grp = agrp; -} +} /* Remove the given channel from all groups */ void action_groups_remove_channel(bAction *act, FCurve *fcu) @@ -338,11 +338,11 @@ void action_groups_remove_channel(bAction *act, FCurve *fcu) /* sanity checks */ if (ELEM(NULL, act, fcu)) return; - + /* check if any group used this directly */ if (fcu->grp) { bActionGroup *agrp = fcu->grp; - + if (agrp->channels.first == agrp->channels.last) { if (agrp->channels.first == fcu) { BLI_listbase_clear(&agrp->channels); @@ -360,10 +360,10 @@ void action_groups_remove_channel(bAction *act, FCurve *fcu) else agrp->channels.last = NULL; } - + fcu->grp = NULL; } - + /* now just remove from list */ BLI_remlink(&act->curves, fcu); } @@ -374,7 +374,7 @@ bActionGroup *BKE_action_group_find_name(bAction *act, const char name[]) /* sanity checks */ if (ELEM(NULL, act, act->groups.first, name) || (name[0] == 0)) return NULL; - + /* do string comparisons */ return BLI_findstring(&act->groups, name, offsetof(bActionGroup, name)); } @@ -383,11 +383,11 @@ bActionGroup *BKE_action_group_find_name(bAction *act, const char name[]) void action_groups_clear_tempflags(bAction *act) { bActionGroup *agrp; - + /* sanity checks */ if (ELEM(NULL, act, act->groups.first)) return; - + /* flag clearing loop */ for (agrp = act->groups.first; agrp; agrp = agrp->next) agrp->flag &= ~AGRP_TEMP; @@ -403,10 +403,10 @@ bPoseChannel *BKE_pose_channel_find_name(const bPose *pose, const char *name) { if (ELEM(NULL, pose, name) || (name[0] == '\0')) return NULL; - + if (pose->chanhash) return BLI_ghash_lookup(pose->chanhash, (const void *)name); - + return BLI_findstring(&((const bPose *)pose)->chanbase, name, offsetof(bPoseChannel, name)); } @@ -421,19 +421,19 @@ bPoseChannel *BKE_pose_channel_find_name(const bPose *pose, const char *name) bPoseChannel *BKE_pose_channel_verify(bPose *pose, const char *name) { bPoseChannel *chan; - + if (pose == NULL) return NULL; - + /* See if this channel exists */ - chan = BLI_findstring(&pose->chanbase, name, offsetof(bPoseChannel, name)); + chan = BKE_pose_channel_find_name(pose, name); if (chan) { return chan; } /* If not, create it and add it */ chan = MEM_callocN(sizeof(bPoseChannel), "verifyPoseChannel"); - + BLI_strncpy(chan->name, name, sizeof(chan->name)); chan->custom_scale = 1.0f; @@ -442,20 +442,22 @@ bPoseChannel *BKE_pose_channel_verify(bPose *pose, const char *name) unit_qt(chan->quat); unit_axis_angle(chan->rotAxis, &chan->rotAngle); chan->size[0] = chan->size[1] = chan->size[2] = 1.0f; - + chan->scaleIn = chan->scaleOut = 1.0f; - + chan->limitmin[0] = chan->limitmin[1] = chan->limitmin[2] = -M_PI; chan->limitmax[0] = chan->limitmax[1] = chan->limitmax[2] = M_PI; chan->stiffness[0] = chan->stiffness[1] = chan->stiffness[2] = 0.0f; chan->ikrotweight = chan->iklinweight = 0.0f; unit_m4(chan->constinv); - + chan->protectflag = OB_LOCK_ROT4D; /* lock by components by default */ - + BLI_addtail(&pose->chanbase, chan); - BKE_pose_channels_hash_free(pose); - + if (pose->chanhash) { + BLI_ghash_insert(pose->chanhash, chan->name, chan); + } + return chan; } @@ -495,7 +497,7 @@ bPoseChannel *BKE_pose_channel_active(Object *ob) if ((pchan->bone) && (pchan->bone == arm->act_bone) && (pchan->bone->layer & arm->layer)) return pchan; } - + return NULL; } @@ -544,11 +546,11 @@ void BKE_pose_copy_data_ex(bPose **dst, const bPose *src, const int flag, const *dst = NULL; return; } - + outPose = MEM_callocN(sizeof(bPose), "pose"); - + BLI_duplicatelist(&outPose->chanbase, &src->chanbase); - + /* Rebuild ghash here too, so that name lookups below won't be too bad... * BUT this will have the penalty that the ghash will be built twice * if BKE_pose_rebuild() gets called after this... @@ -557,12 +559,12 @@ void BKE_pose_copy_data_ex(bPose **dst, const bPose *src, const int flag, const outPose->chanhash = NULL; BKE_pose_channels_hash_make(outPose); } - + outPose->iksolver = src->iksolver; outPose->ikdata = NULL; outPose->ikparam = MEM_dupallocN(src->ikparam); outPose->avs = src->avs; - + for (pchan = outPose->chanbase.first; pchan; pchan = pchan->next) { if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) { id_us_plus((ID *)pchan->custom); @@ -586,7 +588,7 @@ void BKE_pose_copy_data_ex(bPose **dst, const bPose *src, const int flag, const /* XXX: This is needed for motionpath drawing to work. Dunno why it was setting to null before... */ pchan->mpath = animviz_copy_motionpath(pchan->mpath); } - + if (pchan->prop) { pchan->prop = IDP_CopyProperty_ex(pchan->prop, flag); } @@ -598,7 +600,7 @@ void BKE_pose_copy_data_ex(bPose **dst, const bPose *src, const int flag, const if (copy_constraints) { BLI_duplicatelist(&outPose->agroups, &src->agroups); } - + *dst = outPose; } @@ -646,7 +648,7 @@ static bool pose_channel_in_IK_chain(Object *ob, bPoseChannel *pchan, int level) { bConstraint *con; Bone *bone; - + /* No need to check if constraint is active (has influence), * since all constraints with CONSTRAINT_IK_AUTO are active */ for (con = pchan->constraints.first; con; con = con->next) { @@ -675,18 +677,18 @@ bool BKE_pose_channel_in_IK_chain(Object *ob, bPoseChannel *pchan) * Removes the hash for quick lookup of channels, must * be done when adding/removing channels. */ -void BKE_pose_channels_hash_make(bPose *pose) +void BKE_pose_channels_hash_make(bPose *pose) { if (!pose->chanhash) { bPoseChannel *pchan; - + pose->chanhash = BLI_ghash_str_new("make_pose_chan gh"); for (pchan = pose->chanbase.first; pchan; pchan = pchan->next) BLI_ghash_insert(pose->chanhash, pchan->name, pchan); } } -void BKE_pose_channels_hash_free(bPose *pose) +void BKE_pose_channels_hash_free(bPose *pose) { if (pose->chanhash) { BLI_ghash_free(pose->chanhash, NULL, NULL); @@ -742,7 +744,7 @@ void BKE_pose_channels_remove( cti->flush_constraint_targets(con, &targets, 0); } } - + if (pchan->bbone_prev) { if (filter_fn(pchan->bbone_prev->name, user_data)) pchan->bbone_prev = NULL; @@ -751,7 +753,7 @@ void BKE_pose_channels_remove( if (filter_fn(pchan->bbone_next->name, user_data)) pchan->bbone_next = NULL; } - + if (pchan->custom_tx) { if (filter_fn(pchan->custom_tx->name, user_data)) pchan->custom_tx = NULL; @@ -780,7 +782,7 @@ void BKE_pose_channel_free_ex(bPoseChannel *pchan, bool do_id_user) } BKE_constraints_free_ex(&pchan->constraints, do_id_user); - + if (pchan->prop) { IDP_FreeProperty(pchan->prop); MEM_freeN(pchan->prop); @@ -802,11 +804,11 @@ void BKE_pose_channel_free(bPoseChannel *pchan) void BKE_pose_channels_free_ex(bPose *pose, bool do_id_user) { bPoseChannel *pchan; - + if (pose->chanbase.first) { for (pchan = pose->chanbase.first; pchan; pchan = pchan->next) BKE_pose_channel_free_ex(pchan, do_id_user); - + BLI_freelistN(&pose->chanbase); } @@ -883,7 +885,7 @@ void BKE_pose_channel_copy_data(bPoseChannel *pchan, const bPoseChannel *pchan_f pchan->ikstretch = pchan_from->ikstretch; pchan->ikrotweight = pchan_from->ikrotweight; pchan->iklinweight = pchan_from->iklinweight; - + /* bbone settings (typically not animated) */ pchan->bboneflag = pchan_from->bboneflag; pchan->bbone_next = pchan_from->bbone_next; @@ -921,31 +923,31 @@ void BKE_pose_update_constraint_flags(bPose *pose) { bPoseChannel *pchan, *parchan; bConstraint *con; - + /* clear */ for (pchan = pose->chanbase.first; pchan; pchan = pchan->next) { pchan->constflag = 0; } pose->flag &= ~POSE_CONSTRAINTS_TIMEDEPEND; - + /* detect */ for (pchan = pose->chanbase.first; pchan; pchan = pchan->next) { for (con = pchan->constraints.first; con; con = con->next) { if (con->type == CONSTRAINT_TYPE_KINEMATIC) { bKinematicConstraint *data = (bKinematicConstraint *)con->data; - + pchan->constflag |= PCHAN_HAS_IK; - + if (data->tar == NULL || (data->tar->type == OB_ARMATURE && data->subtarget[0] == 0)) pchan->constflag |= PCHAN_HAS_TARGET; - + /* negative rootbone = recalc rootbone index. used in do_versions */ if (data->rootbone < 0) { data->rootbone = 0; - + if (data->flag & CONSTRAINT_IK_TIP) parchan = pchan; else parchan = pchan->parent; - + while (parchan) { data->rootbone++; if ((parchan->bone->flag & BONE_CONNECTED) == 0) @@ -956,10 +958,10 @@ void BKE_pose_update_constraint_flags(bPose *pose) } else if (con->type == CONSTRAINT_TYPE_FOLLOWPATH) { bFollowPathConstraint *data = (bFollowPathConstraint *)con->data; - + /* for drawing constraint colors when color set allows this */ pchan->constflag |= PCHAN_HAS_CONST; - + /* if we have a valid target, make sure that this will get updated on frame-change * (needed for when there is no anim-data for this pose) */ @@ -968,7 +970,7 @@ void BKE_pose_update_constraint_flags(bPose *pose) } else if (con->type == CONSTRAINT_TYPE_SPLINEIK) pchan->constflag |= PCHAN_HAS_SPLINEIK; - else + else pchan->constflag |= PCHAN_HAS_CONST; } } @@ -980,7 +982,7 @@ void BKE_pose_tag_update_constraint_flags(bPose *pose) pose->flag |= POSE_CONSTRAINTS_NEED_UPDATE_FLAGS; } -/* Clears all BONE_UNKEYED flags for every pose channel in every pose +/* Clears all BONE_UNKEYED flags for every pose channel in every pose * This should only be called on frame changing, when it is acceptable to * do this. Otherwise, these flags should not get cleared as poses may get lost. */ @@ -989,14 +991,14 @@ void framechange_poses_clear_unkeyed(Main *bmain) Object *ob; bPose *pose; bPoseChannel *pchan; - + /* This needs to be done for each object that has a pose */ /* TODO: proxies may/may not be correctly handled here... (this needs checking) */ for (ob = bmain->object.first; ob; ob = ob->id.next) { /* we only need to do this on objects with a pose */ if ((pose = ob->pose)) { for (pchan = pose->chanbase.first; pchan; pchan = pchan->next) { - if (pchan->bone) + if (pchan->bone) pchan->bone->flag &= ~BONE_UNKEYED; } } @@ -1009,18 +1011,18 @@ void framechange_poses_clear_unkeyed(Main *bmain) bActionGroup *BKE_pose_add_group(bPose *pose, const char *name) { bActionGroup *grp; - + if (!name) { name = DATA_("Group"); } - + grp = MEM_callocN(sizeof(bActionGroup), "PoseGroup"); BLI_strncpy(grp->name, name, sizeof(grp->name)); BLI_addtail(&pose->agroups, grp); BLI_uniquename(&pose->agroups, grp, name, '.', offsetof(bActionGroup, name), sizeof(grp->name)); - + pose->active_group = BLI_listbase_count(&pose->agroups); - + return grp; } @@ -1030,13 +1032,13 @@ void BKE_pose_remove_group(bPose *pose, bActionGroup *grp, const int index) { bPoseChannel *pchan; int idx = index; - + if (idx < 1) { idx = BLI_findindex(&pose->agroups, grp) + 1; } - + BLI_assert(idx > 0); - + /* adjust group references (the trouble of using indices!): * - firstly, make sure nothing references it * - also, make sure that those after this item get corrected @@ -1066,7 +1068,7 @@ void BKE_pose_remove_group(bPose *pose, bActionGroup *grp, const int index) void BKE_pose_remove_group_index(bPose *pose, const int index) { bActionGroup *grp = NULL; - + /* get group to remove */ grp = BLI_findlink(&pose->agroups, index - 1); if (grp) { @@ -1080,7 +1082,7 @@ void BKE_pose_remove_group_index(bPose *pose, const int index) bool action_has_motion(const bAction *act) { FCurve *fcu; - + /* return on the first F-Curve that has some keyframes/samples defined */ if (act) { for (fcu = act->curves.first; fcu; fcu = fcu->next) { @@ -1088,7 +1090,7 @@ bool action_has_motion(const bAction *act) return true; } } - + /* nothing found */ return false; } @@ -1105,7 +1107,7 @@ void calc_action_range(const bAction *act, float *start, float *end, short incl_ /* if curve has keyframes, consider them first */ if (fcu->totvert) { float nmin, nmax; - + /* get extents for this curve * - no "selected only", since this is often used in the backend * - no "minimum length" (we will apply this later), otherwise @@ -1113,26 +1115,26 @@ void calc_action_range(const bAction *act, float *start, float *end, short incl_ * a phantom frame (T50354) */ calc_fcurve_range(fcu, &nmin, &nmax, false, false); - + /* compare to the running tally */ min = min_ff(min, nmin); max = max_ff(max, nmax); - + foundvert = 1; } - + /* if incl_modifiers is enabled, need to consider modifiers too * - only really care about the last modifier */ if ((incl_modifiers) && (fcu->modifiers.last)) { FModifier *fcm = fcu->modifiers.last; - + /* only use the maximum sensible limits of the modifiers if they are more extreme */ switch (fcm->type) { case FMODIFIER_TYPE_LIMITS: /* Limits F-Modifier */ { FMod_Limits *fmd = (FMod_Limits *)fcm->data; - + if (fmd->flag & FCM_LIMIT_XMIN) { min = min_ff(min, fmd->rect.xmin); } @@ -1144,7 +1146,7 @@ void calc_action_range(const bAction *act, float *start, float *end, short incl_ case FMODIFIER_TYPE_CYCLES: /* Cycles F-Modifier */ { FMod_Cycles *fmd = (FMod_Cycles *)fcm->data; - + if (fmd->before_mode != FCM_EXTRAPOLATE_NONE) min = MINAFRAMEF; if (fmd->after_mode != FCM_EXTRAPOLATE_NONE) @@ -1152,22 +1154,22 @@ void calc_action_range(const bAction *act, float *start, float *end, short incl_ break; } /* TODO: function modifier may need some special limits */ - + default: /* all other standard modifiers are on the infinite range... */ min = MINAFRAMEF; max = MAXFRAMEF; break; } - + foundmod = 1; } } } - + if (foundvert || foundmod) { /* ensure that action is at least 1 frame long (for NLA strips to have a valid length) */ if (min == max) max += 1.0f; - + *start = min; *end = max; } @@ -1177,7 +1179,7 @@ void calc_action_range(const bAction *act, float *start, float *end, short incl_ } } -/* Return flags indicating which transforms the given object/posechannel has +/* Return flags indicating which transforms the given object/posechannel has * - if 'curves' is provided, a list of links to these curves are also returned */ short action_get_item_transforms(bAction *act, Object *ob, bPoseChannel *pchan, ListBase *curves) @@ -1186,7 +1188,7 @@ short action_get_item_transforms(bAction *act, Object *ob, bPoseChannel *pchan, FCurve *fcu; char *basePath = NULL; short flags = 0; - + /* build PointerRNA from provided data to obtain the paths to use */ if (pchan) RNA_pointer_create((ID *)ob, &RNA_PoseBone, pchan, &ptr); @@ -1194,37 +1196,37 @@ short action_get_item_transforms(bAction *act, Object *ob, bPoseChannel *pchan, RNA_id_pointer_create((ID *)ob, &ptr); else return 0; - + /* get the basic path to the properties of interest */ basePath = RNA_path_from_ID_to_struct(&ptr); if (basePath == NULL) return 0; - - /* search F-Curves for the given properties + + /* search F-Curves for the given properties * - we cannot use the groups, since they may not be grouped in that way... */ for (fcu = act->curves.first; fcu; fcu = fcu->next) { const char *bPtr = NULL, *pPtr = NULL; - + /* if enough flags have been found, we can stop checking unless we're also getting the curves */ if ((flags == ACT_TRANS_ALL) && (curves == NULL)) break; - + /* just in case... */ if (fcu->rna_path == NULL) continue; - + /* step 1: check for matching base path */ bPtr = strstr(fcu->rna_path, basePath); - + if (bPtr) { - /* we must add len(basePath) bytes to the match so that we are at the end of the + /* we must add len(basePath) bytes to the match so that we are at the end of the * base path so that we don't get false positives with these strings in the names */ bPtr += strlen(basePath); - - /* step 2: check for some property with transforms - * - to speed things up, only check for the ones not yet found + + /* step 2: check for some property with transforms + * - to speed things up, only check for the ones not yet found * unless we're getting the curves too * - if we're getting the curves, the BLI_genericNodeN() creates a LinkData * node wrapping the F-Curve, which then gets added to the list @@ -1234,53 +1236,53 @@ short action_get_item_transforms(bAction *act, Object *ob, bPoseChannel *pchan, pPtr = strstr(bPtr, "location"); if (pPtr) { flags |= ACT_TRANS_LOC; - - if (curves) + + if (curves) BLI_addtail(curves, BLI_genericNodeN(fcu)); continue; } } - + if ((curves) || (flags & ACT_TRANS_SCALE) == 0) { pPtr = strstr(bPtr, "scale"); if (pPtr) { flags |= ACT_TRANS_SCALE; - - if (curves) + + if (curves) BLI_addtail(curves, BLI_genericNodeN(fcu)); continue; } } - + if ((curves) || (flags & ACT_TRANS_ROT) == 0) { pPtr = strstr(bPtr, "rotation"); if (pPtr) { flags |= ACT_TRANS_ROT; - - if (curves) + + if (curves) BLI_addtail(curves, BLI_genericNodeN(fcu)); continue; } } - + if ((curves) || (flags & ACT_TRANS_BBONE) == 0) { /* bbone shape properties */ pPtr = strstr(bPtr, "bbone_"); if (pPtr) { flags |= ACT_TRANS_BBONE; - + if (curves) BLI_addtail(curves, BLI_genericNodeN(fcu)); continue; } } - + if ((curves) || (flags & ACT_TRANS_PROP) == 0) { /* custom properties only */ pPtr = strstr(bPtr, "[\""); /* extra '"' comment here to keep my texteditor functionlist working :) */ if (pPtr) { flags |= ACT_TRANS_PROP; - + if (curves) BLI_addtail(curves, BLI_genericNodeN(fcu)); continue; @@ -1288,10 +1290,10 @@ short action_get_item_transforms(bAction *act, Object *ob, bPoseChannel *pchan, } } } - + /* free basePath */ MEM_freeN(basePath); - + /* return flags found */ return flags; } @@ -1302,26 +1304,26 @@ short action_get_item_transforms(bAction *act, Object *ob, bPoseChannel *pchan, void BKE_pose_rest(bPose *pose) { bPoseChannel *pchan; - + if (!pose) return; - + memset(pose->stride_offset, 0, sizeof(pose->stride_offset)); memset(pose->cyclic_offset, 0, sizeof(pose->cyclic_offset)); - + for (pchan = pose->chanbase.first; pchan; pchan = pchan->next) { zero_v3(pchan->loc); zero_v3(pchan->eul); unit_qt(pchan->quat); unit_axis_angle(pchan->rotAxis, &pchan->rotAngle); pchan->size[0] = pchan->size[1] = pchan->size[2] = 1.0f; - + pchan->roll1 = pchan->roll2 = 0.0f; pchan->curveInX = pchan->curveInY = 0.0f; pchan->curveOutX = pchan->curveOutY = 0.0f; pchan->ease1 = pchan->ease2 = 0.0f; pchan->scaleIn = pchan->scaleOut = 1.0f; - + pchan->flag &= ~(POSE_LOC | POSE_ROT | POSE_SIZE | POSE_BBONE_SHAPE); } } @@ -1330,7 +1332,7 @@ void BKE_pose_rest(bPose *pose) bool BKE_pose_copy_result(bPose *to, bPose *from) { bPoseChannel *pchanto, *pchanfrom; - + if (to == NULL || from == NULL) { printf("Pose copy error, pose to:%p from:%p\n", (void *)to, (void *)from); /* debug temp */ return false; @@ -1347,16 +1349,16 @@ bool BKE_pose_copy_result(bPose *to, bPose *from) if (pchanto) { copy_m4_m4(pchanto->pose_mat, pchanfrom->pose_mat); copy_m4_m4(pchanto->chan_mat, pchanfrom->chan_mat); - + /* used for local constraints */ copy_v3_v3(pchanto->loc, pchanfrom->loc); copy_qt_qt(pchanto->quat, pchanfrom->quat); copy_v3_v3(pchanto->eul, pchanfrom->eul); copy_v3_v3(pchanto->size, pchanfrom->size); - + copy_v3_v3(pchanto->pose_head, pchanfrom->pose_head); copy_v3_v3(pchanto->pose_tail, pchanfrom->pose_tail); - + pchanto->roll1 = pchanfrom->roll1; pchanto->roll2 = pchanfrom->roll2; pchanto->curveInX = pchanfrom->curveInX; @@ -1367,7 +1369,7 @@ bool BKE_pose_copy_result(bPose *to, bPose *from) pchanto->ease2 = pchanfrom->ease2; pchanto->scaleIn = pchanfrom->scaleIn; pchanto->scaleOut = pchanfrom->scaleOut; - + pchanto->rotmode = pchanfrom->rotmode; pchanto->flag = pchanfrom->flag; pchanto->protectflag = pchanfrom->protectflag; @@ -1387,27 +1389,27 @@ void BKE_pose_tag_recalc(Main *bmain, bPose *pose) DEG_relations_tag_update(bmain); } -/* For the calculation of the effects of an Action at the given frame on an object +/* For the calculation of the effects of an Action at the given frame on an object * This is currently only used for the Action Constraint */ void what_does_obaction(Object *ob, Object *workob, bPose *pose, bAction *act, char groupname[], float cframe) { bActionGroup *agrp = BKE_action_group_find_name(act, groupname); - + /* clear workob */ BKE_object_workob_clear(workob); - + /* init workob */ copy_m4_m4(workob->obmat, ob->obmat); copy_m4_m4(workob->parentinv, ob->parentinv); copy_m4_m4(workob->constinv, ob->constinv); workob->parent = ob->parent; - + workob->rotmode = ob->rotmode; - + workob->trackflag = ob->trackflag; workob->upflag = ob->upflag; - + workob->partype = ob->partype; workob->par1 = ob->par1; workob->par2 = ob->par2; @@ -1415,7 +1417,7 @@ void what_does_obaction(Object *ob, Object *workob, bPose *pose, bAction *act, c workob->constraints.first = ob->constraints.first; workob->constraints.last = ob->constraints.last; - + workob->pose = pose; /* need to set pose too, since this is used for both types of Action Constraint */ if (pose) { /* This function is most likely to be used with a temporary pose with a single bone in there. @@ -1432,27 +1434,27 @@ void what_does_obaction(Object *ob, Object *workob, bPose *pose, bAction *act, c BLI_strncpy(workob->parsubstr, ob->parsubstr, sizeof(workob->parsubstr)); BLI_strncpy(workob->id.name, "OB<ConstrWorkOb>", sizeof(workob->id.name)); /* we don't use real object name, otherwise RNA screws with the real thing */ - + /* if we're given a group to use, it's likely to be more efficient (though a bit more dangerous) */ if (agrp) { /* specifically evaluate this group only */ PointerRNA id_ptr; - + /* get RNA-pointer for the workob's ID */ RNA_id_pointer_create(&workob->id, &id_ptr); - + /* execute action for this group only */ animsys_evaluate_action_group(&id_ptr, act, agrp, NULL, cframe); } else { AnimData adt = {NULL}; - + /* init animdata, and attach to workob */ workob->adt = &adt; - + adt.recalc = ADT_RECALC_ANIM; adt.action = act; - + /* execute effects of Action on to workob (or it's PoseChannels) */ BKE_animsys_evaluate_animdata(NULL, NULL, &workob->id, &adt, cframe, ADT_RECALC_ANIM); } diff --git a/source/blender/blenkernel/intern/addon.c b/source/blender/blenkernel/intern/addon.c index 689e0fb5ee6..a9bb193a7a1 100644 --- a/source/blender/blenkernel/intern/addon.c +++ b/source/blender/blenkernel/intern/addon.c @@ -53,9 +53,14 @@ bAddon *BKE_addon_new(void) return addon; } +bAddon *BKE_addon_find(ListBase *addon_list, const char *module) +{ + return BLI_findstring(addon_list, module, offsetof(bAddon, module)); +} + bAddon *BKE_addon_ensure(ListBase *addon_list, const char *module) { - bAddon *addon = BLI_findstring(addon_list, module, offsetof(bAddon, module)); + bAddon *addon = BKE_addon_find(addon_list, module); if (addon == NULL) { addon = BKE_addon_new(); BLI_strncpy(addon->module, module, sizeof(addon->module)); diff --git a/source/blender/blenkernel/intern/anim.c b/source/blender/blenkernel/intern/anim.c index c7730d8877b..07b8b69bc70 100644 --- a/source/blender/blenkernel/intern/anim.c +++ b/source/blender/blenkernel/intern/anim.c @@ -104,12 +104,12 @@ void animviz_settings_init(bAnimVizSettings *avs) /* ------------------- */ /* Free the given motion path's cache */ -void animviz_free_motionpath_cache(bMotionPath *mpath) +void animviz_free_motionpath_cache(bMotionPath *mpath) { /* sanity check */ - if (mpath == NULL) + if (mpath == NULL) return; - + /* free the path if necessary */ if (mpath->points) MEM_freeN(mpath->points); @@ -117,13 +117,13 @@ void animviz_free_motionpath_cache(bMotionPath *mpath) GWN_VERTBUF_DISCARD_SAFE(mpath->points_vbo); GWN_BATCH_DISCARD_SAFE(mpath->batch_line); GWN_BATCH_DISCARD_SAFE(mpath->batch_points); - + /* reset the relevant parameters */ mpath->points = NULL; mpath->length = 0; } -/* Free the given motion path instance and its data +/* Free the given motion path instance and its data * NOTE: this frees the motion path given! */ void animviz_free_motionpath(bMotionPath *mpath) @@ -131,10 +131,10 @@ void animviz_free_motionpath(bMotionPath *mpath) /* sanity check */ if (mpath == NULL) return; - + /* free the cache first */ animviz_free_motionpath_cache(mpath); - + /* now the instance itself */ MEM_freeN(mpath); } @@ -174,11 +174,11 @@ bMotionPath *animviz_verify_motionpaths(ReportList *reports, Scene *scene, Objec { bAnimVizSettings *avs; bMotionPath *mpath, **dst; - + /* sanity checks */ if (ELEM(NULL, scene, ob)) return NULL; - + /* get destination data */ if (pchan) { /* paths for posechannel - assume that posechannel belongs to the object */ @@ -206,9 +206,9 @@ bMotionPath *animviz_verify_motionpaths(ReportList *reports, Scene *scene, Objec */ if (*dst != NULL) { int expected_length = avs->path_ef - avs->path_sf; - + mpath = *dst; - + /* path is "valid" if length is valid, but must also be of the same length as is being requested */ if ((mpath->start_frame != mpath->end_frame) && (mpath->length > 0)) { /* outer check ensures that we have some curve data for this path */ @@ -227,13 +227,13 @@ bMotionPath *animviz_verify_motionpaths(ReportList *reports, Scene *scene, Objec mpath = MEM_callocN(sizeof(bMotionPath), "bMotionPath"); *dst = mpath; } - + /* set settings from the viz settings */ mpath->start_frame = avs->path_sf; mpath->end_frame = avs->path_ef; - + mpath->length = mpath->end_frame - mpath->start_frame; - + if (avs->path_bakeflag & MOTIONPATH_BAKE_HEADS) mpath->flag |= MOTIONPATH_FLAG_BHEAD; else @@ -249,10 +249,10 @@ bMotionPath *animviz_verify_motionpaths(ReportList *reports, Scene *scene, Objec /* allocate a cache */ mpath->points = MEM_callocN(sizeof(bMotionPathVert) * mpath->length, "bMotionPathVerts"); - + /* tag viz settings as currently having some path(s) which use it */ avs->path_bakeflag |= MOTIONPATH_BAKE_HAS_PATHS; - + /* return it */ return mpath; } @@ -262,20 +262,19 @@ bMotionPath *animviz_verify_motionpaths(ReportList *reports, Scene *scene, Objec /* Motion path needing to be baked (mpt) */ typedef struct MPathTarget { struct MPathTarget *next, *prev; - + bMotionPath *mpath; /* motion path in question */ DLRBT_Tree keys; /* temp, to know where the keyframes are */ - + /* Original (Source Objects) */ Object *ob; /* source object */ bPoseChannel *pchan; /* source posechannel (if applicable) */ - + /* "Evaluated" Copies (these come from the background COW copie * that provide all the coordinates we want to save off) */ Object *ob_eval; /* evaluated object */ - bPoseChannel *pchan_eval; /* evaluated posechannel (if applicable) */ } MPathTarget; /* ........ */ @@ -287,28 +286,28 @@ typedef struct MPathTarget { void animviz_get_object_motionpaths(Object *ob, ListBase *targets) { MPathTarget *mpt; - + /* object itself first */ if ((ob->avs.recalc & ANIMVIZ_RECALC_PATHS) && (ob->mpath)) { /* new target for object */ mpt = MEM_callocN(sizeof(MPathTarget), "MPathTarget Ob"); BLI_addtail(targets, mpt); - + mpt->mpath = ob->mpath; mpt->ob = ob; } - + /* bones */ if ((ob->pose) && (ob->pose->avs.recalc & ANIMVIZ_RECALC_PATHS)) { bArmature *arm = ob->data; bPoseChannel *pchan; - + for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) { if ((pchan->bone) && (arm->layer & pchan->bone->layer) && (pchan->mpath)) { /* new target for bone */ mpt = MEM_callocN(sizeof(MPathTarget), "MPathTarget PoseBone"); BLI_addtail(targets, mpt); - + mpt->mpath = pchan->mpath; mpt->ob = ob; mpt->pchan = pchan; @@ -342,27 +341,33 @@ static void motionpaths_calc_update_scene(Main *bmain, static void motionpaths_calc_bake_targets(Scene *scene, ListBase *targets) { MPathTarget *mpt; - + /* for each target, check if it can be baked on the current frame */ for (mpt = targets->first; mpt; mpt = mpt->next) { bMotionPath *mpath = mpt->mpath; bMotionPathVert *mpv; - - Object *ob_eval = mpt->ob_eval; - bPoseChannel *pchan_eval = mpt->pchan_eval; - - /* current frame must be within the range the cache works for + + /* current frame must be within the range the cache works for * - is inclusive of the first frame, but not the last otherwise we get buffer overruns */ if ((CFRA < mpath->start_frame) || (CFRA >= mpath->end_frame)) { continue; } - + /* get the relevant cache vert to write to */ mpv = mpath->points + (CFRA - mpath->start_frame); - + + Object *ob_eval = mpt->ob_eval; + + /* Lookup evaluated pose channel, here because the depsgraph + * evaluation can change them so they are not cached in mpt. */ + bPoseChannel *pchan_eval = NULL; + if (mpt->pchan) { + pchan_eval = BKE_pose_channel_find_name(ob_eval->pose, mpt->pchan->name); + } + /* pose-channel or object path baking? */ - if (mpt->pchan_eval) { + if (pchan_eval) { /* heads or tails */ if (mpath->flag & MOTIONPATH_FLAG_BHEAD) { copy_v3_v3(mpv->co, pchan_eval->pose_head); @@ -370,7 +375,7 @@ static void motionpaths_calc_bake_targets(Scene *scene, ListBase *targets) else { copy_v3_v3(mpv->co, pchan_eval->pose_tail); } - + /* result must be in worldspace */ mul_m4_v3(ob_eval->obmat, mpv->co); } @@ -388,7 +393,7 @@ static void motionpaths_calc_bake_targets(Scene *scene, ListBase *targets) } } -/* Perform baking of the given object's and/or its bones' transforms to motion paths +/* Perform baking of the given object's and/or its bones' transforms to motion paths * - scene: current scene * - ob: object whose flagged motionpaths should get calculated * - recalc: whether we need to @@ -399,15 +404,15 @@ static void motionpaths_calc_bake_targets(Scene *scene, ListBase *targets) MPathTarget *mpt; int sfra, efra; int cfra; - + /* sanity check */ if (ELEM(NULL, targets, targets->first)) return; - + /* set frame values */ cfra = CFRA; sfra = efra = cfra; - + /* TODO: this method could be improved... * 1) max range for standard baking * 2) minimum range for recalc baking (i.e. between keyframes, but how?) */ @@ -417,17 +422,14 @@ static void motionpaths_calc_bake_targets(Scene *scene, ListBase *targets) efra = MAX2(efra, mpt->mpath->end_frame); } if (efra <= sfra) return; - - + + /* get copies of objects/bones to get the calculated results from * (for copy-on-write evaluation), so that we actually get some results */ // TODO: Create a copy of background depsgraph that only contain these entities, and only evaluates them.. for (mpt = targets->first; mpt; mpt = mpt->next) { mpt->ob_eval = DEG_get_evaluated_object(depsgraph, mpt->ob); - if (mpt->pchan) { - mpt->pchan_eval = BKE_pose_channel_find_name(mpt->ob_eval->pose, mpt->pchan->name); - } AnimData *adt = BKE_animdata_from_id(&mpt->ob_eval->id); @@ -469,23 +471,23 @@ static void motionpaths_calc_bake_targets(Scene *scene, ListBase *targets) /* perform baking for targets */ motionpaths_calc_bake_targets(scene, targets); } - + /* reset original environment */ // XXX: Soon to be obsolete CFRA = cfra; motionpaths_calc_update_scene(bmain, depsgraph); - + /* clear recalc flags from targets */ for (mpt = targets->first; mpt; mpt = mpt->next) { bAnimVizSettings *avs; bMotionPath *mpath = mpt->mpath; - + /* get pointer to animviz settings for each target */ if (mpt->pchan) avs = &mpt->ob->pose->avs; else avs = &mpt->ob->avs; - + /* clear the flag requesting recalculation of targets */ avs->recalc &= ~ANIMVIZ_RECALC_PATHS; @@ -502,7 +504,7 @@ static void motionpaths_calc_bake_targets(Scene *scene, ListBase *targets) /* ******************************************************************** */ /* Curve Paths - for curve deforms and/or curve following */ -/* free curve path data +/* free curve path data * NOTE: frees the path itself! * NOTE: this is increasingly inaccurate with non-uniform BevPoint subdivisions [#24633] */ @@ -512,7 +514,7 @@ void free_path(Path *path) MEM_freeN(path); } -/* calculate a curve-deform path for a curve +/* calculate a curve-deform path for a curve * - only called from displist.c -> do_makeDispListCurveTypes */ void calc_curvepath(Object *ob, ListBase *nurbs) @@ -525,17 +527,17 @@ void calc_curvepath(Object *ob, ListBase *nurbs) float *fp, *dist, *maxdist, xyz[3]; float fac, d = 0, fac1, fac2; int a, tot, cycl = 0; - + /* in a path vertices are with equal differences: path->len = number of verts */ /* NOW WITH BEVELCURVE!!! */ - + if (ob == NULL || ob->type != OB_CURVE) { return; } if (ob->curve_cache->path) free_path(ob->curve_cache->path); ob->curve_cache->path = NULL; - + /* weak! can only use first curve */ bl = ob->curve_cache->bev.first; if (bl == NULL || !bl->nr) { @@ -545,18 +547,18 @@ void calc_curvepath(Object *ob, ListBase *nurbs) nu = nurbs->first; ob->curve_cache->path = path = MEM_callocN(sizeof(Path), "calc_curvepath"); - + /* if POLY: last vertice != first vertice */ cycl = (bl->poly != -1); - + tot = cycl ? bl->nr : bl->nr - 1; - + path->len = tot + 1; /* exception: vector handle paths and polygon paths should be subdivided at least a factor resolu */ if (path->len < nu->resolu * SEGMENTSU(nu)) { path->len = nu->resolu * SEGMENTSU(nu); } - + dist = (float *)MEM_mallocN(sizeof(float) * (tot + 1), "calcpathdist"); /* all lengths in *dist */ @@ -569,13 +571,13 @@ void calc_curvepath(Object *ob, ListBase *nurbs) sub_v3_v3v3(xyz, bevpfirst->vec, bevp->vec); else sub_v3_v3v3(xyz, (bevp + 1)->vec, bevp->vec); - + *fp = *(fp - 1) + len_v3(xyz); bevp++; } - + path->totdist = *fp; - + /* the path verts in path->data */ /* now also with TILT value */ pp = path->data = (PathPoint *)MEM_callocN(sizeof(PathPoint) * path->len, "pathdata"); @@ -590,11 +592,11 @@ void calc_curvepath(Object *ob, ListBase *nurbs) maxdist = dist + tot; fac = 1.0f / ((float)path->len - 1.0f); fac = fac * path->totdist; - + for (a = 0; a < path->len; a++) { - + d = ((float)a) * fac; - + /* we're looking for location (distance) 'd' in the array */ if (LIKELY(tot > 0)) { while ((fp < maxdist) && (d >= *fp)) { @@ -620,10 +622,10 @@ void calc_curvepath(Object *ob, ListBase *nurbs) pp->weight = fac1 * bevp->weight + fac2 * bevpn->weight; interp_qt_qtqt(pp->quat, bevp->quat, bevpn->quat, fac2); normalize_qt(pp->quat); - + pp++; } - + MEM_freeN(dist); } @@ -667,7 +669,7 @@ int where_on_path(Object *ob, float ctime, float vec[4], float dir[3], float qua } path = ob->curve_cache->path; pp = path->data; - + /* test for cyclic */ bl = ob->curve_cache->bev.first; if (!bl) return 0; @@ -678,7 +680,7 @@ int where_on_path(Object *ob, float ctime, float vec[4], float dir[3], float qua BLI_assert(cycl || ctime >= 0.0f); ctime *= (path->len - 1); - + s1 = (int)floor(ctime); fac = (float)(s1 + 1) - ctime; diff --git a/source/blender/blenkernel/intern/anim_sys.c b/source/blender/blenkernel/intern/anim_sys.c index e5a68fa7476..fd7497f9ba1 100644 --- a/source/blender/blenkernel/intern/anim_sys.c +++ b/source/blender/blenkernel/intern/anim_sys.c @@ -105,7 +105,7 @@ bool id_type_can_have_animdata(const short id_type) case ID_GD: case ID_CF: return true; - + /* no AnimData */ default: return false; @@ -121,13 +121,13 @@ bool id_can_have_animdata(const ID *id) return id_type_can_have_animdata(GS(id->name)); } -/* Get AnimData from the given ID-block. In order for this to work, we assume that +/* Get AnimData from the given ID-block. In order for this to work, we assume that * the AnimData pointer is stored immediately after the given ID-block in the struct, * as per IdAdtTemplate. */ AnimData *BKE_animdata_from_id(ID *id) { - /* only some ID-blocks have this info for now, so we cast the + /* only some ID-blocks have this info for now, so we cast the * types that do to be of type IdAdtTemplate, and extract the * AnimData that way */ @@ -139,33 +139,33 @@ AnimData *BKE_animdata_from_id(ID *id) return NULL; } -/* Add AnimData to the given ID-block. In order for this to work, we assume that +/* Add AnimData to the given ID-block. In order for this to work, we assume that * the AnimData pointer is stored immediately after the given ID-block in the struct, * as per IdAdtTemplate. Also note that */ AnimData *BKE_animdata_add_id(ID *id) { - /* Only some ID-blocks have this info for now, so we cast the + /* Only some ID-blocks have this info for now, so we cast the * types that do to be of type IdAdtTemplate, and add the AnimData * to it using the template */ if (id_can_have_animdata(id)) { IdAdtTemplate *iat = (IdAdtTemplate *)id; - + /* check if there's already AnimData, in which case, don't add */ if (iat->adt == NULL) { AnimData *adt; - + /* add animdata */ adt = iat->adt = MEM_callocN(sizeof(AnimData), "AnimData"); - + /* set default settings */ adt->act_influence = 1.0f; } - + return iat->adt; } - else + else return NULL; } @@ -176,14 +176,14 @@ bool BKE_animdata_set_action(ReportList *reports, ID *id, bAction *act) { AnimData *adt = BKE_animdata_from_id(id); bool ok = false; - + /* animdata validity check */ if (adt == NULL) { BKE_report(reports, RPT_WARNING, "No AnimData to set action on"); return ok; } - - /* active action is only editable when it is not a tweaking strip + + /* active action is only editable when it is not a tweaking strip * see rna_AnimData_action_editable() in rna_animation.c */ if ((adt->flag & ADT_NLA_EDIT_ON) || (adt->actstrip) || (adt->tmpact)) { @@ -191,11 +191,11 @@ bool BKE_animdata_set_action(ReportList *reports, ID *id, bAction *act) BKE_report(reports, RPT_ERROR, "Cannot change action, as it is still being edited in NLA"); return ok; } - + /* manage usercount for current action */ if (adt->action) id_us_min((ID *)adt->action); - + /* assume that AnimData's action can in fact be edited... */ if (act) { /* action must have same type as owner */ @@ -218,7 +218,7 @@ bool BKE_animdata_set_action(ReportList *reports, ID *id, bAction *act) adt->action = NULL; ok = true; } - + return ok; } @@ -227,13 +227,13 @@ bool BKE_animdata_set_action(ReportList *reports, ID *id, bAction *act) /* Free AnimData used by the nominated ID-block, and clear ID-block's AnimData pointer */ void BKE_animdata_free(ID *id, const bool do_id_user) { - /* Only some ID-blocks have this info for now, so we cast the + /* Only some ID-blocks have this info for now, so we cast the * types that do to be of type IdAdtTemplate */ if (id_can_have_animdata(id)) { IdAdtTemplate *iat = (IdAdtTemplate *)id; AnimData *adt = iat->adt; - + /* check if there's any AnimData to start with */ if (adt) { if (do_id_user) { @@ -244,19 +244,19 @@ void BKE_animdata_free(ID *id, const bool do_id_user) if (adt->tmpact) id_us_min(&adt->tmpact->id); } - + /* free nla data */ BKE_nla_tracks_free(&adt->nla_tracks); - + /* free drivers - stored as a list of F-Curves */ free_fcurves(&adt->drivers); /* free driver array cache */ MEM_SAFE_FREE(adt->driver_array); - + /* free overrides */ /* TODO... */ - + /* free animdata now */ MEM_freeN(adt); iat->adt = NULL; @@ -270,12 +270,12 @@ void BKE_animdata_free(ID *id, const bool do_id_user) AnimData *BKE_animdata_copy(Main *bmain, AnimData *adt, const bool do_action, const bool do_id_user) { AnimData *dadt; - + /* sanity check before duplicating struct */ if (adt == NULL) return NULL; dadt = MEM_dupallocN(adt); - + /* make a copy of action - at worst, user has to delete copies... */ if (do_action) { BLI_assert(bmain != NULL); @@ -288,15 +288,15 @@ AnimData *BKE_animdata_copy(Main *bmain, AnimData *adt, const bool do_action, co } /* duplicate NLA data */ - BKE_nla_tracks_copy(&dadt->nla_tracks, &adt->nla_tracks); - + BKE_nla_tracks_copy(bmain, &dadt->nla_tracks, &adt->nla_tracks); + /* duplicate drivers (F-Curves) */ copy_fcurves(&dadt->drivers, &adt->drivers); dadt->driver_array = NULL; - + /* don't copy overrides */ BLI_listbase_clear(&dadt->overrides); - + /* return */ return dadt; } @@ -319,78 +319,80 @@ bool BKE_animdata_copy_id(Main *bmain, ID *id_to, ID *id_from, const bool do_act return true; } -void BKE_animdata_copy_id_action(ID *id, const bool set_newid) +void BKE_animdata_copy_id_action(Main *bmain, ID *id, const bool set_newid) { AnimData *adt = BKE_animdata_from_id(id); if (adt) { if (adt->action) { id_us_min((ID *)adt->action); - adt->action = set_newid ? ID_NEW_SET(adt->action, BKE_action_copy(G.main, adt->action)) : - BKE_action_copy(G.main, adt->action); + adt->action = set_newid ? ID_NEW_SET(adt->action, BKE_action_copy(bmain, adt->action)) : + BKE_action_copy(bmain, adt->action); } if (adt->tmpact) { id_us_min((ID *)adt->tmpact); - adt->tmpact = set_newid ? ID_NEW_SET(adt->tmpact, BKE_action_copy(G.main, adt->tmpact)) : - BKE_action_copy(G.main, adt->tmpact); + adt->tmpact = set_newid ? ID_NEW_SET(adt->tmpact, BKE_action_copy(bmain, adt->tmpact)) : + BKE_action_copy(bmain, adt->tmpact); } } } /* Merge copies of the data from the src AnimData into the destination AnimData */ -void BKE_animdata_merge_copy(ID *dst_id, ID *src_id, eAnimData_MergeCopy_Modes action_mode, bool fix_drivers) +void BKE_animdata_merge_copy( + Main *bmain, ID *dst_id, ID *src_id, + eAnimData_MergeCopy_Modes action_mode, bool fix_drivers) { AnimData *src = BKE_animdata_from_id(src_id); AnimData *dst = BKE_animdata_from_id(dst_id); - + /* sanity checks */ if (ELEM(NULL, dst, src)) return; - + // TODO: we must unset all "tweakmode" flags if ((src->flag & ADT_NLA_EDIT_ON) || (dst->flag & ADT_NLA_EDIT_ON)) { printf("ERROR: Merging AnimData blocks while editing NLA is dangerous as it may cause data corruption\n"); return; } - + /* handle actions... */ if (action_mode == ADT_MERGECOPY_SRC_COPY) { /* make a copy of the actions */ - dst->action = BKE_action_copy(G.main, src->action); - dst->tmpact = BKE_action_copy(G.main, src->tmpact); + dst->action = BKE_action_copy(bmain, src->action); + dst->tmpact = BKE_action_copy(bmain, src->tmpact); } else if (action_mode == ADT_MERGECOPY_SRC_REF) { /* make a reference to it */ dst->action = src->action; id_us_plus((ID *)dst->action); - + dst->tmpact = src->tmpact; id_us_plus((ID *)dst->tmpact); } - + /* duplicate NLA data */ if (src->nla_tracks.first) { ListBase tracks = {NULL, NULL}; - - BKE_nla_tracks_copy(&tracks, &src->nla_tracks); + + BKE_nla_tracks_copy(bmain, &tracks, &src->nla_tracks); BLI_movelisttolist(&dst->nla_tracks, &tracks); } - + /* duplicate drivers (F-Curves) */ if (src->drivers.first) { ListBase drivers = {NULL, NULL}; - + copy_fcurves(&drivers, &src->drivers); - + /* Fix up all driver targets using the old target id * - This assumes that the src ID is being merged into the dst ID */ if (fix_drivers) { FCurve *fcu; - + for (fcu = drivers.first; fcu; fcu = fcu->next) { ChannelDriver *driver = fcu->driver; DriverVar *dvar; - + for (dvar = driver->variables.first; dvar; dvar = dvar->next) { DRIVER_TARGETS_USED_LOOPER(dvar) { @@ -402,7 +404,7 @@ void BKE_animdata_merge_copy(ID *dst_id, ID *src_id, eAnimData_MergeCopy_Modes a } } } - + BLI_movelisttolist(&dst->drivers, &drivers); } } @@ -422,7 +424,7 @@ static bool animpath_matches_basepath(const char path[], const char basepath[]) return (path && basepath) && STRPREFIX(path, basepath); } -/* Move F-Curves in src action to dst action, setting up all the necessary groups +/* Move F-Curves in src action to dst action, setting up all the necessary groups * for this to happen, but only if the F-Curves being moved have the appropriate * "base path". * - This is used when data moves from one datablock to another, causing the @@ -431,7 +433,7 @@ static bool animpath_matches_basepath(const char path[], const char basepath[]) void action_move_fcurves_by_basepath(bAction *srcAct, bAction *dstAct, const char basepath[]) { FCurve *fcu, *fcn = NULL; - + /* sanity checks */ if (ELEM(NULL, srcAct, dstAct, basepath)) { if (G.debug & G_DEBUG) { @@ -440,56 +442,56 @@ void action_move_fcurves_by_basepath(bAction *srcAct, bAction *dstAct, const cha } return; } - - /* clear 'temp' flags on all groups in src, as we'll be needing them later + + /* clear 'temp' flags on all groups in src, as we'll be needing them later * to identify groups that we've managed to empty out here */ action_groups_clear_tempflags(srcAct); - + /* iterate over all src F-Curves, moving over the ones that need to be moved */ for (fcu = srcAct->curves.first; fcu; fcu = fcn) { /* store next pointer in case we move stuff */ fcn = fcu->next; - + /* should F-Curve be moved over? * - we only need the start of the path to match basepath */ if (animpath_matches_basepath(fcu->rna_path, basepath)) { bActionGroup *agrp = NULL; - + /* if grouped... */ if (fcu->grp) { /* make sure there will be a matching group on the other side for the migrants */ agrp = BKE_action_group_find_name(dstAct, fcu->grp->name); - + if (agrp == NULL) { /* add a new one with a similar name (usually will be the same though) */ agrp = action_groups_add_new(dstAct, fcu->grp->name); } - + /* old groups should be tagged with 'temp' flags so they can be removed later * if we remove everything from them */ fcu->grp->flag |= AGRP_TEMP; } - + /* perform the migration now */ action_groups_remove_channel(srcAct, fcu); - + if (agrp) action_groups_add_channel(dstAct, agrp, fcu); else BLI_addtail(&dstAct->curves, fcu); } } - + /* cleanup groups (if present) */ if (srcAct->groups.first) { bActionGroup *agrp, *grp = NULL; - + for (agrp = srcAct->groups.first; agrp; agrp = grp) { grp = agrp->next; - + /* only tagged groups need to be considered - clearing these tags or removing them */ if (agrp->flag & AGRP_TEMP) { /* if group is empty and tagged, then we can remove as this operation @@ -508,69 +510,70 @@ void action_move_fcurves_by_basepath(bAction *srcAct, bAction *dstAct, const cha * animation data is based off "basepath", creating new AnimData and * associated data as necessary */ -void BKE_animdata_separate_by_basepath(ID *srcID, ID *dstID, ListBase *basepaths) +void BKE_animdata_separate_by_basepath( + Main *bmain, ID *srcID, ID *dstID, ListBase *basepaths) { AnimData *srcAdt = NULL, *dstAdt = NULL; LinkData *ld; - + /* sanity checks */ if (ELEM(NULL, srcID, dstID)) { if (G.debug & G_DEBUG) printf("ERROR: no source or destination ID to separate AnimData with\n"); return; } - + /* get animdata from src, and create for destination (if needed) */ srcAdt = BKE_animdata_from_id(srcID); dstAdt = BKE_animdata_add_id(dstID); - + if (ELEM(NULL, srcAdt, dstAdt)) { if (G.debug & G_DEBUG) printf("ERROR: no AnimData for this pair of ID's\n"); return; } - + /* active action */ if (srcAdt->action) { /* set up an action if necessary, and name it in a similar way so that it can be easily found again */ if (dstAdt->action == NULL) { - dstAdt->action = BKE_action_add(G.main, srcAdt->action->id.name + 2); + dstAdt->action = BKE_action_add(bmain, srcAdt->action->id.name + 2); } else if (dstAdt->action == srcAdt->action) { printf("Argh! Source and Destination share animation! ('%s' and '%s' both use '%s') Making new empty action\n", srcID->name, dstID->name, srcAdt->action->id.name); - + /* TODO: review this... */ id_us_min(&dstAdt->action->id); - dstAdt->action = BKE_action_add(G.main, dstAdt->action->id.name + 2); + dstAdt->action = BKE_action_add(bmain, dstAdt->action->id.name + 2); } - + /* loop over base paths, trying to fix for each one... */ for (ld = basepaths->first; ld; ld = ld->next) { const char *basepath = (const char *)ld->data; action_move_fcurves_by_basepath(srcAdt->action, dstAdt->action, basepath); } } - + /* drivers */ if (srcAdt->drivers.first) { FCurve *fcu, *fcn = NULL; - + /* check each driver against all the base paths to see if any should go */ for (fcu = srcAdt->drivers.first; fcu; fcu = fcn) { fcn = fcu->next; - + /* try each basepath in turn, but stop on the first one which works */ for (ld = basepaths->first; ld; ld = ld->next) { const char *basepath = (const char *)ld->data; - + if (animpath_matches_basepath(fcu->rna_path, basepath)) { /* just need to change lists */ BLI_remlink(&srcAdt->drivers, fcu); BLI_addtail(&dstAdt->drivers, fcu); - + /* TODO: add depsgraph flushing calls? */ - + /* can stop now, as moved already */ break; } @@ -628,15 +631,15 @@ static bool check_rna_path_is_valid(ID *owner_id, const char *path) { PointerRNA id_ptr, ptr; PropertyRNA *prop = NULL; - + /* make initial RNA pointer to start resolving from */ RNA_id_pointer_create(owner_id, &id_ptr); - + /* try to resolve */ - return RNA_path_resolve_property(&id_ptr, path, &ptr, &prop); + return RNA_path_resolve_property(&id_ptr, path, &ptr, &prop); } -/* Check if some given RNA Path needs fixing - free the given path and set a new one as appropriate +/* Check if some given RNA Path needs fixing - free the given path and set a new one as appropriate * NOTE: we assume that oldName and newName have [" "] padding around them */ static char *rna_path_rename_fix(ID *owner_id, const char *prefix, const char *oldName, const char *newName, char *oldpath, bool verify_paths) @@ -645,7 +648,7 @@ static char *rna_path_rename_fix(ID *owner_id, const char *prefix, const char *o char *oldNamePtr = strstr(oldpath, oldName); int prefixLen = strlen(prefix); int oldNameLen = strlen(oldName); - + /* only start fixing the path if the prefix and oldName feature in the path, * and prefix occurs immediately before oldName */ @@ -660,20 +663,20 @@ static char *rna_path_rename_fix(ID *owner_id, const char *prefix, const char *o if (prefixPtr > oldpath) { BLI_dynstr_nappend(ds, oldpath, prefixPtr - oldpath); } - + /* add the prefix */ BLI_dynstr_append(ds, prefix); - + /* add the new name (complete with brackets) */ BLI_dynstr_append(ds, newName); - + /* add the postfix */ BLI_dynstr_append(ds, postfixPtr); - + /* create new path, and cleanup old data */ newPath = BLI_dynstr_get_cstring(ds); BLI_dynstr_free(ds); - + /* check if the new path will solve our problems */ /* TODO: will need to check whether this step really helps in practice */ if (!verify_paths || check_rna_path_is_valid(owner_id, newPath)) { @@ -687,31 +690,31 @@ static char *rna_path_rename_fix(ID *owner_id, const char *prefix, const char *o } } } - + /* the old path doesn't need to be changed */ return oldpath; } /* Check RNA-Paths for a list of F-Curves */ -static void fcurves_path_rename_fix(ID *owner_id, const char *prefix, const char *oldName, const char *newName, +static void fcurves_path_rename_fix(ID *owner_id, const char *prefix, const char *oldName, const char *newName, const char *oldKey, const char *newKey, ListBase *curves, bool verify_paths) { FCurve *fcu; - + /* we need to check every curve... */ for (fcu = curves->first; fcu; fcu = fcu->next) { if (fcu->rna_path) { const char *old_path = fcu->rna_path; - + /* firstly, handle the F-Curve's own path */ fcu->rna_path = rna_path_rename_fix(owner_id, prefix, oldKey, newKey, fcu->rna_path, verify_paths); - + /* if path changed and the F-Curve is grouped, check if its group also needs renaming * (i.e. F-Curve is first of a bone's F-Curves; hence renaming this should also trigger rename) */ if (fcu->rna_path != old_path) { bActionGroup *agrp = fcu->grp; - + if ((agrp) && STREQ(oldName, agrp->name)) { BLI_strncpy(agrp->name, newName, sizeof(agrp->name)); } @@ -725,27 +728,27 @@ static void drivers_path_rename_fix(ID *owner_id, ID *ref_id, const char *prefix const char *oldKey, const char *newKey, ListBase *curves, bool verify_paths) { FCurve *fcu; - + /* we need to check every curve - drivers are F-Curves too! */ for (fcu = curves->first; fcu; fcu = fcu->next) { /* firstly, handle the F-Curve's own path */ if (fcu->rna_path) fcu->rna_path = rna_path_rename_fix(owner_id, prefix, oldKey, newKey, fcu->rna_path, verify_paths); - + /* driver? */ if (fcu->driver) { ChannelDriver *driver = fcu->driver; DriverVar *dvar; - + /* driver variables */ for (dvar = driver->variables.first; dvar; dvar = dvar->next) { /* only change the used targets, since the others will need fixing manually anyway */ - DRIVER_TARGETS_USED_LOOPER(dvar) + DRIVER_TARGETS_USED_LOOPER(dvar) { /* rename RNA path */ if (dtar->rna_path && dtar->id) dtar->rna_path = rna_path_rename_fix(dtar->id, prefix, oldKey, newKey, dtar->rna_path, verify_paths); - + /* also fix the bone-name (if applicable) */ if (strstr(prefix, "bones")) { if ( ((dtar->id) && (GS(dtar->id->name) == ID_OB) && (!ref_id || ((Object *)(dtar->id))->data == ref_id)) && @@ -762,18 +765,18 @@ static void drivers_path_rename_fix(ID *owner_id, ID *ref_id, const char *prefix } /* Fix all RNA-Paths for Actions linked to NLA Strips */ -static void nlastrips_path_rename_fix(ID *owner_id, const char *prefix, const char *oldName, const char *newName, +static void nlastrips_path_rename_fix(ID *owner_id, const char *prefix, const char *oldName, const char *newName, const char *oldKey, const char *newKey, ListBase *strips, bool verify_paths) { NlaStrip *strip; - + /* recursively check strips, fixing only actions... */ for (strip = strips->first; strip; strip = strip->next) { /* fix strip's action */ if (strip->act) fcurves_path_rename_fix(owner_id, prefix, oldName, newName, oldKey, newKey, &strip->act->curves, verify_paths); /* ignore own F-Curves, since those are local... */ - + /* check sub-strips (if metas) */ nlastrips_path_rename_fix(owner_id, prefix, oldName, newName, oldKey, newKey, &strip->strips, verify_paths); } @@ -794,13 +797,13 @@ char *BKE_animsys_fix_rna_path_rename(ID *owner_id, char *old_path, const char * { char *oldN, *newN; char *result; - + /* if no action, no need to proceed */ if (ELEM(NULL, owner_id, old_path)) { if (G.debug & G_DEBUG) printf("%s: early abort\n", __func__); return old_path; } - + /* Name sanitation logic - copied from BKE_animdata_fix_paths_rename() */ if ((oldName != NULL) && (newName != NULL)) { /* pad the names with [" "] so that only exact matches are made */ @@ -818,21 +821,21 @@ char *BKE_animsys_fix_rna_path_rename(ID *owner_id, char *old_path, const char * oldN = BLI_sprintfN("[%d]", oldSubscript); newN = BLI_sprintfN("[%d]", newSubscript); } - + /* fix given path */ if (G.debug & G_DEBUG) printf("%s | %s | oldpath = %p ", oldN, newN, old_path); result = rna_path_rename_fix(owner_id, prefix, oldN, newN, old_path, verify_paths); if (G.debug & G_DEBUG) printf("path rename result = %p\n", result); - + /* free the temp names */ MEM_freeN(oldN); MEM_freeN(newN); - + /* return the resulting path - may be the same path again if nothing changed */ return result; } -/* Fix all RNA_Paths in the given Action, relative to the given ID block +/* Fix all RNA_Paths in the given Action, relative to the given ID block * * This is just an external wrapper for the F-Curve fixing function, * with input validity checks on top of the basic method. @@ -844,11 +847,11 @@ void BKE_action_fix_paths_rename(ID *owner_id, bAction *act, const char *prefix, const char *newName, int oldSubscript, int newSubscript, bool verify_paths) { char *oldN, *newN; - + /* if no action, no need to proceed */ if (ELEM(NULL, owner_id, act)) return; - + /* Name sanitation logic - copied from BKE_animdata_fix_paths_rename() */ if ((oldName != NULL) && (newName != NULL)) { /* pad the names with [" "] so that only exact matches are made */ @@ -866,10 +869,10 @@ void BKE_action_fix_paths_rename(ID *owner_id, bAction *act, const char *prefix, oldN = BLI_sprintfN("[%d]", oldSubscript); newN = BLI_sprintfN("[%d]", newSubscript); } - + /* fix paths in action */ fcurves_path_rename_fix(owner_id, prefix, oldName, newName, oldN, newN, &act->curves, verify_paths); - + /* free the temp names */ MEM_freeN(oldN); MEM_freeN(newN); @@ -884,11 +887,11 @@ void BKE_animdata_fix_paths_rename(ID *owner_id, AnimData *adt, ID *ref_id, cons { NlaTrack *nlt; char *oldN, *newN; - + /* if no AnimData, no need to proceed */ if (ELEM(NULL, owner_id, adt)) return; - + /* Name sanitation logic - shared with BKE_action_fix_paths_rename() */ if ((oldName != NULL) && (newName != NULL)) { /* pad the names with [" "] so that only exact matches are made */ @@ -906,16 +909,16 @@ void BKE_animdata_fix_paths_rename(ID *owner_id, AnimData *adt, ID *ref_id, cons oldN = BLI_sprintfN("[%d]", oldSubscript); newN = BLI_sprintfN("[%d]", newSubscript); } - + /* Active action and temp action */ if (adt->action) fcurves_path_rename_fix(owner_id, prefix, oldName, newName, oldN, newN, &adt->action->curves, verify_paths); if (adt->tmpact) fcurves_path_rename_fix(owner_id, prefix, oldName, newName, oldN, newN, &adt->tmpact->curves, verify_paths); - + /* Drivers - Drivers are really F-Curves */ drivers_path_rename_fix(owner_id, ref_id, prefix, oldName, newName, oldN, newN, &adt->drivers, verify_paths); - + /* NLA Data - Animation Data for Strips */ for (nlt = adt->nla_tracks.first; nlt; nlt = nlt->next) nlastrips_path_rename_fix(owner_id, prefix, oldName, newName, oldN, newN, &nlt->strips, verify_paths); @@ -1005,7 +1008,7 @@ typedef struct AllFCurvesCbWrapper { static void fcurves_apply_cb(ID *id, ListBase *fcurves, ID_FCurve_Edit_Callback func, void *user_data) { FCurve *fcu; - + for (fcu = fcurves->first; fcu; fcu = fcu->next) { func(id, fcu, user_data); } @@ -1015,13 +1018,13 @@ static void fcurves_apply_cb(ID *id, ListBase *fcurves, ID_FCurve_Edit_Callback static void nlastrips_apply_all_curves_cb(ID *id, ListBase *strips, AllFCurvesCbWrapper *wrapper) { NlaStrip *strip; - + for (strip = strips->first; strip; strip = strip->next) { /* fix strip's action */ if (strip->act) { fcurves_apply_cb(id, &strip->act->curves, wrapper->func, wrapper->user_data); } - + /* check sub-strips (if metas) */ nlastrips_apply_all_curves_cb(id, &strip->strips, wrapper); } @@ -1032,18 +1035,18 @@ static void adt_apply_all_fcurves_cb(ID *id, AnimData *adt, void *wrapper_data) { AllFCurvesCbWrapper *wrapper = wrapper_data; NlaTrack *nlt; - + if (adt->action) { fcurves_apply_cb(id, &adt->action->curves, wrapper->func, wrapper->user_data); } - + if (adt->tmpact) { fcurves_apply_cb(id, &adt->tmpact->curves, wrapper->func, wrapper->user_data); } - + /* free drivers - stored as a list of F-Curves */ fcurves_apply_cb(id, &adt->drivers, wrapper->func, wrapper->user_data); - + /* NLA Data - Animation Data for Strips */ for (nlt = adt->nla_tracks.first; nlt; nlt = nlt->next) { nlastrips_apply_all_curves_cb(id, &nlt->strips, wrapper); @@ -1051,20 +1054,20 @@ static void adt_apply_all_fcurves_cb(ID *id, AnimData *adt, void *wrapper_data) } /* apply the given callback function on all F-Curves attached to data in main database */ -void BKE_fcurves_main_cb(Main *mainptr, ID_FCurve_Edit_Callback func, void *user_data) +void BKE_fcurves_main_cb(Main *bmain, ID_FCurve_Edit_Callback func, void *user_data) { /* Wrap F-Curve operation stuff to pass to the general AnimData-level func */ AllFCurvesCbWrapper wrapper = {func, user_data}; - + /* Use the AnimData-based function so that we don't have to reimplement all that stuff */ - BKE_animdata_main_cb(mainptr, adt_apply_all_fcurves_cb, &wrapper); + BKE_animdata_main_cb(bmain, adt_apply_all_fcurves_cb, &wrapper); } /* Whole Database Ops -------------------------------------------- */ /* apply the given callback function on all data in main database */ -void BKE_animdata_main_cb(Main *mainptr, ID_AnimData_Edit_Callback func, void *user_data) +void BKE_animdata_main_cb(Main *bmain, ID_AnimData_Edit_Callback func, void *user_data) { ID *id; @@ -1074,7 +1077,7 @@ void BKE_animdata_main_cb(Main *mainptr, ID_AnimData_Edit_Callback func, void *u AnimData *adt = BKE_animdata_from_id(id); \ if (adt) func(id, adt, user_data); \ } (void)0 - + /* "embedded" nodetree cases (i.e. scene/material/texture->nodetree) */ #define ANIMDATA_NODETREE_IDS_CB(first, NtId_Type) \ for (id = first; id; id = id->next) { \ @@ -1086,69 +1089,69 @@ void BKE_animdata_main_cb(Main *mainptr, ID_AnimData_Edit_Callback func, void *u } \ if (adt) func(id, adt, user_data); \ } (void)0 - + /* nodes */ - ANIMDATA_IDS_CB(mainptr->nodetree.first); - + ANIMDATA_IDS_CB(bmain->nodetree.first); + /* textures */ - ANIMDATA_NODETREE_IDS_CB(mainptr->tex.first, Tex); - + ANIMDATA_NODETREE_IDS_CB(bmain->tex.first, Tex); + /* lamps */ - ANIMDATA_NODETREE_IDS_CB(mainptr->lamp.first, Lamp); - + ANIMDATA_NODETREE_IDS_CB(bmain->lamp.first, Lamp); + /* materials */ - ANIMDATA_NODETREE_IDS_CB(mainptr->mat.first, Material); - + ANIMDATA_NODETREE_IDS_CB(bmain->mat.first, Material); + /* cameras */ - ANIMDATA_IDS_CB(mainptr->camera.first); - + ANIMDATA_IDS_CB(bmain->camera.first); + /* shapekeys */ - ANIMDATA_IDS_CB(mainptr->key.first); - + ANIMDATA_IDS_CB(bmain->key.first); + /* metaballs */ - ANIMDATA_IDS_CB(mainptr->mball.first); - + ANIMDATA_IDS_CB(bmain->mball.first); + /* curves */ - ANIMDATA_IDS_CB(mainptr->curve.first); - + ANIMDATA_IDS_CB(bmain->curve.first); + /* armatures */ - ANIMDATA_IDS_CB(mainptr->armature.first); - + ANIMDATA_IDS_CB(bmain->armature.first); + /* lattices */ - ANIMDATA_IDS_CB(mainptr->latt.first); - + ANIMDATA_IDS_CB(bmain->latt.first); + /* meshes */ - ANIMDATA_IDS_CB(mainptr->mesh.first); - + ANIMDATA_IDS_CB(bmain->mesh.first); + /* particles */ - ANIMDATA_IDS_CB(mainptr->particle.first); + ANIMDATA_IDS_CB(bmain->particle.first); /* speakers */ - ANIMDATA_IDS_CB(mainptr->speaker.first); + ANIMDATA_IDS_CB(bmain->speaker.first); /* movie clips */ - ANIMDATA_IDS_CB(mainptr->movieclip.first); + ANIMDATA_IDS_CB(bmain->movieclip.first); /* objects */ - ANIMDATA_IDS_CB(mainptr->object.first); + ANIMDATA_IDS_CB(bmain->object.first); /* masks */ - ANIMDATA_IDS_CB(mainptr->mask.first); - + ANIMDATA_IDS_CB(bmain->mask.first); + /* worlds */ - ANIMDATA_NODETREE_IDS_CB(mainptr->world.first, World); + ANIMDATA_NODETREE_IDS_CB(bmain->world.first, World); /* scenes */ - ANIMDATA_NODETREE_IDS_CB(mainptr->scene.first, Scene); + ANIMDATA_NODETREE_IDS_CB(bmain->scene.first, Scene); /* line styles */ - ANIMDATA_IDS_CB(mainptr->linestyle.first); - + ANIMDATA_IDS_CB(bmain->linestyle.first); + /* grease pencil */ - ANIMDATA_IDS_CB(mainptr->gpencil.first); + ANIMDATA_IDS_CB(bmain->gpencil.first); /* cache files */ - ANIMDATA_IDS_CB(mainptr->cachefiles.first); + ANIMDATA_IDS_CB(bmain->cachefiles.first); } /* Fix all RNA-Paths throughout the database (directly access the Global.main version) @@ -1158,11 +1161,11 @@ void BKE_animdata_main_cb(Main *mainptr, ID_AnimData_Edit_Callback func, void *u /* TODO: use BKE_animdata_main_cb for looping over all data */ void BKE_animdata_fix_paths_rename_all(ID *ref_id, const char *prefix, const char *oldName, const char *newName) { - Main *mainptr = G.main; + Main *bmain = G.main; /* XXX UGLY! */ ID *id; - - /* macro for less typing - * - whether animdata exists is checked for by the main renaming callback, though taking + + /* macro for less typing + * - whether animdata exists is checked for by the main renaming callback, though taking * this outside of the function may make things slightly faster? */ #define RENAMEFIX_ANIM_IDS(first) \ @@ -1170,7 +1173,7 @@ void BKE_animdata_fix_paths_rename_all(ID *ref_id, const char *prefix, const cha AnimData *adt = BKE_animdata_from_id(id); \ BKE_animdata_fix_paths_rename(id, adt, ref_id, prefix, oldName, newName, 0, 0, 1); \ } (void)0 - + /* another version of this macro for nodetrees */ #define RENAMEFIX_ANIM_NODETREE_IDS(first, NtId_Type) \ for (id = first; id; id = id->next) { \ @@ -1182,72 +1185,72 @@ void BKE_animdata_fix_paths_rename_all(ID *ref_id, const char *prefix, const cha } \ BKE_animdata_fix_paths_rename(id, adt, ref_id, prefix, oldName, newName, 0, 0, 1); \ } (void)0 - + /* nodes */ - RENAMEFIX_ANIM_IDS(mainptr->nodetree.first); - + RENAMEFIX_ANIM_IDS(bmain->nodetree.first); + /* textures */ - RENAMEFIX_ANIM_NODETREE_IDS(mainptr->tex.first, Tex); - + RENAMEFIX_ANIM_NODETREE_IDS(bmain->tex.first, Tex); + /* lamps */ - RENAMEFIX_ANIM_NODETREE_IDS(mainptr->lamp.first, Lamp); - + RENAMEFIX_ANIM_NODETREE_IDS(bmain->lamp.first, Lamp); + /* materials */ - RENAMEFIX_ANIM_NODETREE_IDS(mainptr->mat.first, Material); - + RENAMEFIX_ANIM_NODETREE_IDS(bmain->mat.first, Material); + /* cameras */ - RENAMEFIX_ANIM_IDS(mainptr->camera.first); - + RENAMEFIX_ANIM_IDS(bmain->camera.first); + /* shapekeys */ - RENAMEFIX_ANIM_IDS(mainptr->key.first); - + RENAMEFIX_ANIM_IDS(bmain->key.first); + /* metaballs */ - RENAMEFIX_ANIM_IDS(mainptr->mball.first); - + RENAMEFIX_ANIM_IDS(bmain->mball.first); + /* curves */ - RENAMEFIX_ANIM_IDS(mainptr->curve.first); - + RENAMEFIX_ANIM_IDS(bmain->curve.first); + /* armatures */ - RENAMEFIX_ANIM_IDS(mainptr->armature.first); - + RENAMEFIX_ANIM_IDS(bmain->armature.first); + /* lattices */ - RENAMEFIX_ANIM_IDS(mainptr->latt.first); - + RENAMEFIX_ANIM_IDS(bmain->latt.first); + /* meshes */ - RENAMEFIX_ANIM_IDS(mainptr->mesh.first); - + RENAMEFIX_ANIM_IDS(bmain->mesh.first); + /* particles */ - RENAMEFIX_ANIM_IDS(mainptr->particle.first); + RENAMEFIX_ANIM_IDS(bmain->particle.first); /* speakers */ - RENAMEFIX_ANIM_IDS(mainptr->speaker.first); + RENAMEFIX_ANIM_IDS(bmain->speaker.first); /* movie clips */ - RENAMEFIX_ANIM_IDS(mainptr->movieclip.first); + RENAMEFIX_ANIM_IDS(bmain->movieclip.first); /* objects */ - RENAMEFIX_ANIM_IDS(mainptr->object.first); + RENAMEFIX_ANIM_IDS(bmain->object.first); /* masks */ - RENAMEFIX_ANIM_IDS(mainptr->mask.first); - + RENAMEFIX_ANIM_IDS(bmain->mask.first); + /* worlds */ - RENAMEFIX_ANIM_NODETREE_IDS(mainptr->world.first, World); - + RENAMEFIX_ANIM_NODETREE_IDS(bmain->world.first, World); + /* linestyles */ - RENAMEFIX_ANIM_IDS(mainptr->linestyle.first); - + RENAMEFIX_ANIM_IDS(bmain->linestyle.first); + /* grease pencil */ - RENAMEFIX_ANIM_IDS(mainptr->gpencil.first); + RENAMEFIX_ANIM_IDS(bmain->gpencil.first); /* cache files */ - RENAMEFIX_ANIM_IDS(mainptr->cachefiles.first); - + RENAMEFIX_ANIM_IDS(bmain->cachefiles.first); + /* scenes */ - RENAMEFIX_ANIM_NODETREE_IDS(mainptr->scene.first, Scene); + RENAMEFIX_ANIM_NODETREE_IDS(bmain->scene.first, Scene); } -/* *********************************** */ +/* *********************************** */ /* KeyingSet API */ /* Finding Tools --------------------------- */ @@ -1257,50 +1260,50 @@ void BKE_animdata_fix_paths_rename_all(ID *ref_id, const char *prefix, const cha KS_Path *BKE_keyingset_find_path(KeyingSet *ks, ID *id, const char group_name[], const char rna_path[], int array_index, int UNUSED(group_mode)) { KS_Path *ksp; - + /* sanity checks */ if (ELEM(NULL, ks, rna_path, id)) return NULL; - - /* loop over paths in the current KeyingSet, finding the first one where all settings match + + /* loop over paths in the current KeyingSet, finding the first one where all settings match * (i.e. the first one where none of the checks fail and equal 0) */ for (ksp = ks->paths.first; ksp; ksp = ksp->next) { short eq_id = 1, eq_path = 1, eq_index = 1, eq_group = 1; - + /* id */ if (id != ksp->id) eq_id = 0; - + /* path */ if ((ksp->rna_path == NULL) || !STREQ(rna_path, ksp->rna_path)) eq_path = 0; - + /* index - need to compare whole-array setting too... */ if (ksp->array_index != array_index) eq_index = 0; - + /* group */ if (group_name) { /* FIXME: these checks need to be coded... for now, it's not too important though */ } - + /* if all aspects are ok, return */ if (eq_id && eq_path && eq_index && eq_group) return ksp; } - + /* none found */ return NULL; } - + /* Defining Tools --------------------------- */ /* Used to create a new 'custom' KeyingSet for the user, that will be automatically added to the stack */ KeyingSet *BKE_keyingset_add(ListBase *list, const char idname[], const char name[], short flag, short keyingflag) { KeyingSet *ks; - + /* allocate new KeyingSet */ ks = MEM_callocN(sizeof(KeyingSet), "KeyingSet"); @@ -1310,16 +1313,16 @@ KeyingSet *BKE_keyingset_add(ListBase *list, const char idname[], const char nam ks->flag = flag; ks->keyingflag = keyingflag; ks->keyingoverride = keyingflag; /* NOTE: assume that if one is set one way, the other should be too, so that it'll work */ - + /* add KeyingSet to list */ BLI_addtail(list, ks); - + /* Make sure KeyingSet has a unique idname */ BLI_uniquename(list, ks, DATA_("KeyingSet"), '.', offsetof(KeyingSet, idname), sizeof(ks->idname)); - + /* Make sure KeyingSet has a unique label (this helps with identification) */ BLI_uniquename(list, ks, DATA_("Keying Set"), '.', offsetof(KeyingSet, name), sizeof(ks->name)); - + /* return new KeyingSet for further editing */ return ks; } @@ -1330,55 +1333,55 @@ KeyingSet *BKE_keyingset_add(ListBase *list, const char idname[], const char nam KS_Path *BKE_keyingset_add_path(KeyingSet *ks, ID *id, const char group_name[], const char rna_path[], int array_index, short flag, short groupmode) { KS_Path *ksp; - + /* sanity checks */ if (ELEM(NULL, ks, rna_path)) { printf("ERROR: no Keying Set and/or RNA Path to add path with\n"); return NULL; } - + /* ID is required for all types of KeyingSets */ if (id == NULL) { printf("ERROR: No ID provided for Keying Set Path\n"); return NULL; } - + /* don't add if there is already a matching KS_Path in the KeyingSet */ if (BKE_keyingset_find_path(ks, id, group_name, rna_path, array_index, groupmode)) { if (G.debug & G_DEBUG) printf("ERROR: destination already exists in Keying Set\n"); return NULL; } - + /* allocate a new KeyingSet Path */ ksp = MEM_callocN(sizeof(KS_Path), "KeyingSet Path"); - + /* just store absolute info */ ksp->id = id; if (group_name) BLI_strncpy(ksp->group, group_name, sizeof(ksp->group)); else ksp->group[0] = '\0'; - + /* store additional info for relative paths (just in case user makes the set relative) */ if (id) ksp->idtype = GS(id->name); - + /* just copy path info */ /* TODO: should array index be checked too? */ ksp->rna_path = BLI_strdup(rna_path); ksp->array_index = array_index; - + /* store flags */ ksp->flag = flag; ksp->groupmode = groupmode; - + /* add KeyingSet path to KeyingSet */ BLI_addtail(&ks->paths, ksp); - + /* return this path */ return ksp; -} +} /* Free the given Keying Set path */ void BKE_keyingset_free_path(KeyingSet *ks, KS_Path *ksp) @@ -1400,12 +1403,12 @@ void BKE_keyingsets_copy(ListBase *newlist, const ListBase *list) { KeyingSet *ksn; KS_Path *kspn; - + BLI_duplicatelist(newlist, list); for (ksn = newlist->first; ksn; ksn = ksn->next) { BLI_duplicatelist(&ksn->paths, &ksn->paths); - + for (kspn = ksn->paths.first; kspn; kspn = kspn->next) kspn->rna_path = MEM_dupallocN(kspn->rna_path); } @@ -1417,11 +1420,11 @@ void BKE_keyingsets_copy(ListBase *newlist, const ListBase *list) void BKE_keyingset_free(KeyingSet *ks) { KS_Path *ksp, *kspn; - + /* sanity check */ if (ks == NULL) return; - + /* free each path as we go to avoid looping twice */ for (ksp = ks->paths.first; ksp; ksp = kspn) { kspn = ksp->next; @@ -1433,12 +1436,12 @@ void BKE_keyingset_free(KeyingSet *ks) void BKE_keyingsets_free(ListBase *list) { KeyingSet *ks, *ksn; - + /* sanity check */ if (list == NULL) return; - - /* loop over KeyingSets freeing them + + /* loop over KeyingSets freeing them * - BKE_keyingset_free() doesn't free the set itself, but it frees its sub-data */ for (ks = list->first; ks; ks = ksn) { @@ -1451,7 +1454,7 @@ void BKE_keyingsets_free(ListBase *list) /* ***************************************** */ /* Evaluation Data-Setting Backend */ -/* Retrieve string to act as RNA-path, adjusted using mapping-table if provided +/* Retrieve string to act as RNA-path, adjusted using mapping-table if provided * It returns whether the string needs to be freed (i.e. if it was a temp remapped one) * // FIXME: maybe it would be faster if we didn't have to alloc/free strings like this all the time, but for now it's safer * @@ -1754,14 +1757,14 @@ static void animsys_evaluate_fcurves( static void animsys_evaluate_drivers(PointerRNA *ptr, AnimData *adt, float ctime) { FCurve *fcu; - + /* drivers are stored as F-Curves, but we cannot use the standard code, as we need to check if * the depsgraph requested that this driver be evaluated... */ for (fcu = adt->drivers.first; fcu; fcu = fcu->next) { ChannelDriver *driver = fcu->driver; bool ok = false; - + /* check if this driver's curve should be skipped */ if ((fcu->flag & (FCURVE_MUTED | FCURVE_DISABLED)) == 0) { /* check if driver itself is tagged for recalculation */ @@ -1776,13 +1779,13 @@ static void animsys_evaluate_drivers(PointerRNA *ptr, AnimData *adt, float ctime const float curval = calculate_fcurve(&anim_rna, fcu, ctime); ok = animsys_write_rna_setting(&anim_rna, curval); } - + /* clear recalc flag */ driver->flag &= ~DRIVER_FLAG_RECALC; - + /* set error-flag if evaluation failed */ if (ok == 0) - driver->flag |= DRIVER_FLAG_INVALID; + driver->flag |= DRIVER_FLAG_INVALID; } } } @@ -1798,13 +1801,13 @@ static void animsys_evaluate_drivers(PointerRNA *ptr, AnimData *adt, float ctime static void action_idcode_patch_check(ID *id, bAction *act) { int idcode = 0; - + /* just in case */ if (ELEM(NULL, id, act)) return; else idcode = GS(id->name); - + /* the actual checks... hopefully not too much of a performance hit in the long run... */ if (act->idroot == 0) { /* use the current root if not set already (i.e. newly created actions and actions from 2.50-2.57 builds) @@ -1828,17 +1831,17 @@ static void action_idcode_patch_check(ID *id, bAction *act) void animsys_evaluate_action_group(PointerRNA *ptr, bAction *act, bActionGroup *agrp, AnimMapper *remap, float ctime) { FCurve *fcu; - + /* check if mapper is appropriate for use here (we set to NULL if it's inappropriate) */ if (ELEM(NULL, act, agrp)) return; if ((remap) && (remap->target != act)) remap = NULL; - + action_idcode_patch_check(ptr->id.data, act); - + /* if group is muted, don't evaluated any of the F-Curve */ if (agrp->flag & AGRP_MUTED) return; - + /* calculate then execute each curve */ for (fcu = agrp->channels.first; (fcu) && (fcu->grp == agrp); fcu = fcu->next) { /* check if this curve should be skipped */ @@ -1859,9 +1862,9 @@ static void animsys_evaluate_action_ex( /* check if mapper is appropriate for use here (we set to NULL if it's inappropriate) */ if (act == NULL) return; if ((remap) && (remap->target != act)) remap = NULL; - + action_idcode_patch_check(ptr->id.data, act); - + /* calculate then execute each curve */ animsys_evaluate_fcurves(depsgraph, ptr, &act->curves, remap, ctime); } @@ -1880,7 +1883,7 @@ static float nlastrip_get_influence(NlaStrip *strip, float cframe) /* sanity checks - normalize the blendin/out values? */ strip->blendin = fabsf(strip->blendin); strip->blendout = fabsf(strip->blendout); - + /* result depends on where frame is in respect to blendin/out values */ if (IS_EQF(strip->blendin, 0.0f) == false && (cframe <= (strip->start + strip->blendin))) { /* there is some blend-in */ @@ -1902,14 +1905,14 @@ static void nlastrip_evaluate_controls(Depsgraph *depsgraph, NlaStrip *strip, fl /* now strip's evaluate F-Curves for these settings (if applicable) */ if (strip->fcurves.first) { PointerRNA strip_ptr; - + /* create RNA-pointer needed to set values */ RNA_pointer_create(NULL, &RNA_NlaStrip, strip, &strip_ptr); - + /* execute these settings as per normal */ animsys_evaluate_fcurves(depsgraph, &strip_ptr, &strip->fcurves, NULL, ctime); } - + /* analytically generate values for influence and time (if applicable) * - we do this after the F-Curves have been evaluated to override the effects of those * in case the override has been turned off. @@ -1934,7 +1937,7 @@ NlaEvalStrip *nlastrips_ctime_get_strip(Depsgraph *depsgraph, ListBase *list, Li NlaStrip *strip, *estrip = NULL; NlaEvalStrip *nes; short side = 0; - + /* loop over strips, checking if they fall within the range */ for (strip = strips->first; strip; strip = strip->next) { /* check if current time occurs within this strip */ @@ -1944,53 +1947,53 @@ NlaEvalStrip *nlastrips_ctime_get_strip(Depsgraph *depsgraph, ListBase *list, Li side = NES_TIME_WITHIN; break; } - + /* if time occurred before current strip... */ if (ctime < strip->start) { if (strip == strips->first) { /* before first strip - only try to use it if it extends backwards in time too */ if (strip->extendmode == NLASTRIP_EXTEND_HOLD) estrip = strip; - + /* side is 'before' regardless of whether there's a useful strip */ side = NES_TIME_BEFORE; } else { - /* before next strip - previous strip has ended, but next hasn't begun, + /* before next strip - previous strip has ended, but next hasn't begun, * so blending mode depends on whether strip is being held or not... * - only occurs when no transition strip added, otherwise the transition would have * been picked up above... */ strip = strip->prev; - + if (strip->extendmode != NLASTRIP_EXTEND_NOTHING) estrip = strip; side = NES_TIME_AFTER; } break; } - + /* if time occurred after current strip... */ if (ctime > strip->end) { /* only if this is the last strip should we do anything, and only if that is being held */ if (strip == strips->last) { if (strip->extendmode != NLASTRIP_EXTEND_NOTHING) estrip = strip; - + side = NES_TIME_AFTER; break; } - + /* otherwise, skip... as the 'before' case will catch it more elegantly! */ } } - + /* check if a valid strip was found * - must not be muted (i.e. will have contribution */ - if ((estrip == NULL) || (estrip->flag & NLASTRIP_FLAG_MUTED)) + if ((estrip == NULL) || (estrip->flag & NLASTRIP_FLAG_MUTED)) return NULL; - + /* if ctime was not within the boundaries of the strip, clamp! */ switch (side) { case NES_TIME_BEFORE: /* extend first frame only */ @@ -2000,8 +2003,8 @@ NlaEvalStrip *nlastrips_ctime_get_strip(Depsgraph *depsgraph, ListBase *list, Li ctime = estrip->end; break; } - - /* evaluate strip's evaluation controls + + /* evaluate strip's evaluation controls * - skip if no influence (i.e. same effect as muting the strip) * - negative influence is not supported yet... how would that be defined? */ @@ -2009,12 +2012,12 @@ NlaEvalStrip *nlastrips_ctime_get_strip(Depsgraph *depsgraph, ListBase *list, Li nlastrip_evaluate_controls(depsgraph, estrip, ctime); if (estrip->influence <= 0.0f) return NULL; - + /* check if strip has valid data to evaluate, * and/or perform any additional type-specific actions */ switch (estrip->type) { - case NLASTRIP_TYPE_CLIP: + case NLASTRIP_TYPE_CLIP: /* clip must have some action to evaluate */ if (estrip->act == NULL) return NULL; @@ -2023,51 +2026,51 @@ NlaEvalStrip *nlastrips_ctime_get_strip(Depsgraph *depsgraph, ListBase *list, Li /* there must be strips to transition from and to (i.e. prev and next required) */ if (ELEM(NULL, estrip->prev, estrip->next)) return NULL; - + /* evaluate controls for the relevant extents of the bordering strips... */ nlastrip_evaluate_controls(depsgraph, estrip->prev, estrip->start); nlastrip_evaluate_controls(depsgraph, estrip->next, estrip->end); break; } - + /* add to list of strips we need to evaluate */ nes = MEM_callocN(sizeof(NlaEvalStrip), "NlaEvalStrip"); - + nes->strip = estrip; nes->strip_mode = side; nes->track_index = index; nes->strip_time = estrip->strip_time; - + if (list) BLI_addtail(list, nes); - + return nes; } /* ---------------------- */ -/* find an NlaEvalChannel that matches the given criteria +/* find an NlaEvalChannel that matches the given criteria * - ptr and prop are the RNA data to find a match for */ static NlaEvalChannel *nlaevalchan_find_match(ListBase *channels, PointerRNA *ptr, PropertyRNA *prop, int array_index) { NlaEvalChannel *nec; - + /* sanity check */ if (channels == NULL) return NULL; - + /* loop through existing channels, checking for a channel which affects the same property */ for (nec = channels->first; nec; nec = nec->next) { /* - comparing the PointerRNA's is done by comparing the pointers * to the actual struct the property resides in, since that all the - * other data stored in PointerRNA cannot allow us to definitively - * identify the data + * other data stored in PointerRNA cannot allow us to definitively + * identify the data */ if ((nec->ptr.data == ptr->data) && (nec->prop == prop) && (nec->index == array_index)) return nec; } - + /* not found */ return NULL; } @@ -2078,9 +2081,9 @@ static void nlaevalchan_value_init(NlaEvalChannel *nec) PointerRNA *ptr = &nec->ptr; PropertyRNA *prop = nec->prop; int index = nec->index; - - /* NOTE: while this doesn't work for all RNA properties as default values aren't in fact - * set properly for most of them, at least the common ones (which also happen to get used + + /* NOTE: while this doesn't work for all RNA properties as default values aren't in fact + * set properly for most of them, at least the common ones (which also happen to get used * in NLA strips a lot, e.g. scale) are set correctly. */ switch (RNA_property_type(prop)) { @@ -2119,15 +2122,15 @@ static NlaEvalChannel *nlaevalchan_verify(PointerRNA *ptr, ListBase *channels, N PointerRNA new_ptr; char *path = NULL; /* short free_path = 0; */ - + /* sanity checks */ if (channels == NULL) return NULL; - + /* get RNA pointer+property info from F-Curve for more convenient handling */ /* get path, remapped as appropriate to work in its new environment */ /* free_path = */ /* UNUSED */ animsys_remap_path(strip->remap, fcu->rna_path, &path); - + /* a valid property must be available, and it must be animatable */ if (RNA_path_resolve_property(ptr, path, &new_ptr, &prop) == false) { if (G.debug & G_DEBUG) printf("NLA Strip Eval: Cannot resolve path\n"); @@ -2138,27 +2141,27 @@ static NlaEvalChannel *nlaevalchan_verify(PointerRNA *ptr, ListBase *channels, N if (G.debug & G_DEBUG) printf("NLA Strip Eval: Property not animatable\n"); return NULL; } - + /* try to find a match */ nec = nlaevalchan_find_match(channels, &new_ptr, prop, fcu->array_index); - + /* allocate a new struct for this if none found */ if (nec == NULL) { nec = MEM_callocN(sizeof(NlaEvalChannel), "NlaEvalChannel"); BLI_addtail(channels, nec); - + /* store property links for writing to the property later */ nec->ptr = new_ptr; nec->prop = prop; nec->index = fcu->array_index; - + /* initialise value using default value of property [#35856] */ nlaevalchan_value_init(nec); *newChan = true; } else *newChan = false; - + /* we can now return */ return nec; } @@ -2169,7 +2172,7 @@ static void nlaevalchan_accumulate(NlaEvalChannel *nec, NlaEvalStrip *nes, float NlaStrip *strip = nes->strip; short blendmode = strip->blendmode; float inf = strip->influence; - + /* for replace blend mode, and if this is the first strip, * just replace the value regardless of the influence */ if (newChan && blendmode == NLASTRIP_MODE_REPLACE) { @@ -2180,36 +2183,36 @@ static void nlaevalchan_accumulate(NlaEvalChannel *nec, NlaEvalStrip *nes, float /* if this is being performed as part of transition evaluation, incorporate * an additional weighting factor for the influence */ - if (nes->strip_mode == NES_TIME_TRANSITION_END) + if (nes->strip_mode == NES_TIME_TRANSITION_END) inf *= nes->strip_time; - + /* optimisation: no need to try applying if there is no influence */ if (IS_EQF(inf, 0.0f)) return; - + /* perform blending */ switch (blendmode) { case NLASTRIP_MODE_ADD: /* simply add the scaled value on to the stack */ nec->value += (value * inf); break; - + case NLASTRIP_MODE_SUBTRACT: /* simply subtract the scaled value from the stack */ nec->value -= (value * inf); break; - + case NLASTRIP_MODE_MULTIPLY: /* multiply the scaled value with the stack */ - /* Formula Used: - * result = fac * (a * b) + (1 - fac) * a + /* Formula Used: + * result = fac * (a * b) + (1 - fac) * a */ nec->value = inf * (nec->value * value) + (1 - inf) * nec->value; break; - + case NLASTRIP_MODE_REPLACE: default: /* TODO: do we really want to blend by default? it seems more uses might prefer add... */ - /* do linear interpolation - * - the influence of the accumulated data (elsewhere, that is called dstweight) + /* do linear interpolation + * - the influence of the accumulated data (elsewhere, that is called dstweight) * is 1 - influence, since the strip's influence is srcweight */ nec->value = nec->value * (1.0f - inf) + (value * inf); @@ -2221,19 +2224,19 @@ static void nlaevalchan_accumulate(NlaEvalChannel *nec, NlaEvalStrip *nes, float static void nlaevalchan_buffers_accumulate(ListBase *channels, ListBase *tmp_buffer, NlaEvalStrip *nes) { NlaEvalChannel *nec, *necn, *necd; - + /* optimize - abort if no channels */ if (BLI_listbase_is_empty(tmp_buffer)) return; - + /* accumulate results in tmp_channels buffer to the accumulation buffer */ for (nec = tmp_buffer->first; nec; nec = necn) { /* get pointer to next channel in case we remove the current channel from the temp-buffer */ necn = nec->next; - + /* try to find an existing matching channel for this setting in the accumulation buffer */ necd = nlaevalchan_find_match(channels, &nec->ptr, nec->prop, nec->index); - + /* if there was a matching channel already in the buffer, accumulate to it, * otherwise, add the current channel to the buffer for efficiency */ @@ -2244,7 +2247,7 @@ static void nlaevalchan_buffers_accumulate(ListBase *channels, ListBase *tmp_buf BLI_addtail(channels, nec); } } - + /* free temp-channels that haven't been assimilated into the buffer */ BLI_freelistN(tmp_buffer); } @@ -2256,7 +2259,7 @@ static void nlaevalchan_buffers_accumulate(ListBase *channels, ListBase *tmp_buf static void nlaeval_fmodifiers_join_stacks(ListBase *result, ListBase *list1, ListBase *list2) { FModifier *fcm1, *fcm2; - + /* if list1 is invalid... */ if (ELEM(NULL, list1, list1->first)) { if (list2 && list2->first) { @@ -2270,15 +2273,15 @@ static void nlaeval_fmodifiers_join_stacks(ListBase *result, ListBase *list1, Li result->last = list1->last; } else { - /* list1 should be added first, and list2 second, with the endpoints of these being the endpoints for result + /* list1 should be added first, and list2 second, with the endpoints of these being the endpoints for result * - the original lists must be left unchanged though, as we need that fact for restoring */ result->first = list1->first; result->last = list2->last; - + fcm1 = list1->last; fcm2 = list2->first; - + fcm1->next = fcm2; fcm2->prev = fcm1; } @@ -2288,17 +2291,17 @@ static void nlaeval_fmodifiers_join_stacks(ListBase *result, ListBase *list1, Li static void nlaeval_fmodifiers_split_stacks(ListBase *list1, ListBase *list2) { FModifier *fcm1, *fcm2; - + /* if list1/2 is invalid... just skip */ if (ELEM(NULL, list1, list2)) return; if (ELEM(NULL, list1->first, list2->first)) return; - + /* get endpoints */ fcm1 = list1->last; fcm2 = list2->first; - + /* clear their links */ fcm1->next = NULL; fcm2->prev = NULL; @@ -2314,48 +2317,48 @@ static void nlastrip_evaluate_actionclip(PointerRNA *ptr, ListBase *channels, Li NlaStrip *strip = nes->strip; FCurve *fcu; float evaltime; - + /* sanity checks for action */ if (strip == NULL) return; - + if (strip->act == NULL) { printf("NLA-Strip Eval Error: Strip '%s' has no Action\n", strip->name); return; } - + action_idcode_patch_check(ptr->id.data, strip->act); - + /* join this strip's modifiers to the parent's modifiers (own modifiers first) */ nlaeval_fmodifiers_join_stacks(&tmp_modifiers, &strip->modifiers, modifiers); - + /* evaluate strip's modifiers which modify time to evaluate the base curves at */ storage = evaluate_fmodifiers_storage_new(&tmp_modifiers); evaltime = evaluate_time_fmodifiers(storage, &tmp_modifiers, NULL, 0.0f, strip->strip_time); - + /* evaluate all the F-Curves in the action, saving the relevant pointers to data that will need to be used */ for (fcu = strip->act->curves.first; fcu; fcu = fcu->next) { NlaEvalChannel *nec; float value = 0.0f; bool newChan; - + /* check if this curve should be skipped */ if (fcu->flag & (FCURVE_MUTED | FCURVE_DISABLED)) continue; if ((fcu->grp) && (fcu->grp->flag & AGRP_MUTED)) continue; - - /* evaluate the F-Curve's value for the time given in the strip - * NOTE: we use the modified time here, since strip's F-Curve Modifiers are applied on top of this + + /* evaluate the F-Curve's value for the time given in the strip + * NOTE: we use the modified time here, since strip's F-Curve Modifiers are applied on top of this */ value = evaluate_fcurve(fcu, evaltime); - - /* apply strip's F-Curve Modifiers on this value + + /* apply strip's F-Curve Modifiers on this value * NOTE: we apply the strip's original evaluation time not the modified one (as per standard F-Curve eval) */ evaluate_value_fmodifiers(storage, &tmp_modifiers, fcu, &value, strip->strip_time); - - + + /* get an NLA evaluation channel to work with, and accumulate the evaluated value with the value(s) * stored in this channel if it has been used already */ @@ -2379,11 +2382,11 @@ static void nlastrip_evaluate_transition( ListBase tmp_modifiers = {NULL, NULL}; NlaEvalStrip tmp_nes; NlaStrip *s1, *s2; - + /* join this strip's modifiers to the parent's modifiers (own modifiers first) */ nlaeval_fmodifiers_join_stacks(&tmp_modifiers, &nes->strip->modifiers, modifiers); - - /* get the two strips to operate on + + /* get the two strips to operate on * - we use the endpoints of the strips directly flanking our strip * using these as the endpoints of the transition (destination and source) * - these should have already been determined to be valid... @@ -2398,8 +2401,8 @@ static void nlastrip_evaluate_transition( s1 = nes->strip->prev; s2 = nes->strip->next; } - - /* prepare template for 'evaluation strip' + + /* prepare template for 'evaluation strip' * - based on the transition strip's evaluation strip data * - strip_mode is NES_TIME_TRANSITION_* based on which endpoint * - strip_time is the 'normalized' (i.e. in-strip) time for evaluation, @@ -2407,23 +2410,23 @@ static void nlastrip_evaluate_transition( * which allows us to appear to be 'interpolating' between the two extremes */ tmp_nes = *nes; - + /* evaluate these strips into a temp-buffer (tmp_channels) */ /* FIXME: modifier evaluation here needs some work... */ /* first strip */ tmp_nes.strip_mode = NES_TIME_TRANSITION_START; tmp_nes.strip = s1; nlastrip_evaluate(depsgraph, ptr, &tmp_channels, &tmp_modifiers, &tmp_nes); - + /* second strip */ tmp_nes.strip_mode = NES_TIME_TRANSITION_END; tmp_nes.strip = s2; nlastrip_evaluate(depsgraph, ptr, &tmp_channels, &tmp_modifiers, &tmp_nes); - - + + /* accumulate temp-buffer and full-buffer, using the 'real' strip */ nlaevalchan_buffers_accumulate(channels, &tmp_channels, nes); - + /* unlink this strip's modifiers from the parent's modifiers again */ nlaeval_fmodifiers_split_stacks(&nes->strip->modifiers, modifiers); } @@ -2436,32 +2439,32 @@ static void nlastrip_evaluate_meta( NlaStrip *strip = nes->strip; NlaEvalStrip *tmp_nes; float evaltime; - + /* meta-strip was calculated normally to have some time to be evaluated at * and here we 'look inside' the meta strip, treating it as a decorated window to - * it's child strips, which get evaluated as if they were some tracks on a strip + * it's child strips, which get evaluated as if they were some tracks on a strip * (but with some extra modifiers to apply). * * NOTE: keep this in sync with animsys_evaluate_nla() */ - + /* join this strip's modifiers to the parent's modifiers (own modifiers first) */ - nlaeval_fmodifiers_join_stacks(&tmp_modifiers, &strip->modifiers, modifiers); - + nlaeval_fmodifiers_join_stacks(&tmp_modifiers, &strip->modifiers, modifiers); + /* find the child-strip to evaluate */ evaltime = (nes->strip_time * (strip->end - strip->start)) + strip->start; tmp_nes = nlastrips_ctime_get_strip(depsgraph, NULL, &strip->strips, -1, evaltime); - - /* directly evaluate child strip into accumulation buffer... + + /* directly evaluate child strip into accumulation buffer... * - there's no need to use a temporary buffer (as it causes issues [T40082]) */ if (tmp_nes) { nlastrip_evaluate(depsgraph, ptr, channels, &tmp_modifiers, tmp_nes); - + /* free temp eval-strip */ MEM_freeN(tmp_nes); } - + /* unlink this strip's modifiers from the parent's modifiers again */ nlaeval_fmodifiers_split_stacks(&strip->modifiers, modifiers); } @@ -2470,7 +2473,7 @@ static void nlastrip_evaluate_meta( void nlastrip_evaluate(Depsgraph *depsgraph, PointerRNA *ptr, ListBase *channels, ListBase *modifiers, NlaEvalStrip *nes) { NlaStrip *strip = nes->strip; - + /* to prevent potential infinite recursion problems (i.e. transition strip, beside meta strip containing a transition * several levels deep inside it), we tag the current strip as being evaluated, and clear this when we leave */ @@ -2478,7 +2481,7 @@ void nlastrip_evaluate(Depsgraph *depsgraph, PointerRNA *ptr, ListBase *channels if (strip->flag & NLASTRIP_FLAG_EDIT_TOUCHED) return; strip->flag |= NLASTRIP_FLAG_EDIT_TOUCHED; - + /* actions to take depend on the type of strip */ switch (strip->type) { case NLASTRIP_TYPE_CLIP: /* action-clip */ @@ -2490,11 +2493,11 @@ void nlastrip_evaluate(Depsgraph *depsgraph, PointerRNA *ptr, ListBase *channels case NLASTRIP_TYPE_META: /* meta */ nlastrip_evaluate_meta(depsgraph, ptr, channels, modifiers, nes); break; - + default: /* do nothing */ break; } - + /* clear temp recursion safe-check */ strip->flag &= ~NLASTRIP_FLAG_EDIT_TOUCHED; } @@ -2503,18 +2506,18 @@ void nlastrip_evaluate(Depsgraph *depsgraph, PointerRNA *ptr, ListBase *channels void nladata_flush_channels(ListBase *channels) { NlaEvalChannel *nec; - + /* sanity checks */ if (channels == NULL) return; - + /* for each channel with accumulated values, write its value on the property it affects */ for (nec = channels->first; nec; nec = nec->next) { PointerRNA *ptr = &nec->ptr; PropertyRNA *prop = nec->prop; int array_index = nec->index; float value = nec->value; - + /* write values - see animsys_write_rna_setting() to sync the code */ switch (RNA_property_type(prop)) { case PROP_BOOLEAN: @@ -2559,19 +2562,19 @@ static void animsys_evaluate_nla(Depsgraph *depsgraph, ListBase *echannels, Poin NlaTrack *nlt; short track_index = 0; bool has_strips = false; - + ListBase estrips = {NULL, NULL}; NlaEvalStrip *nes; - + NlaStrip dummy_strip = {NULL}; /* dummy strip for active action */ - - + + /* 1. get the stack of strips to evaluate at current time (influence calculated here) */ for (nlt = adt->nla_tracks.first; nlt; nlt = nlt->next, track_index++) { /* stop here if tweaking is on and this strip is the tweaking track (it will be the first one that's 'disabled')... */ if ((adt->flag & ADT_NLA_EDIT_ON) && (nlt->flag & NLATRACK_DISABLED)) break; - + /* solo and muting are mutually exclusive... */ if (adt->flag & ADT_NLA_SOLO_TRACK) { /* skip if there is a solo track, but this isn't it */ @@ -2581,24 +2584,24 @@ static void animsys_evaluate_nla(Depsgraph *depsgraph, ListBase *echannels, Poin } else { /* no solo tracks - skip track if muted */ - if (nlt->flag & NLATRACK_MUTED) + if (nlt->flag & NLATRACK_MUTED) continue; } - - /* if this track has strips (but maybe they won't be suitable), set has_strips + + /* if this track has strips (but maybe they won't be suitable), set has_strips * - used for mainly for still allowing normal action evaluation... */ if (nlt->strips.first) has_strips = true; - + /* otherwise, get strip to evaluate for this channel */ nes = nlastrips_ctime_get_strip(depsgraph, &estrips, &nlt->strips, track_index, ctime); if (nes) nes->track = nlt; } - + /* add 'active' Action (may be tweaking track) as last strip to evaluate in NLA stack * - only do this if we're not exclusively evaluating the 'solo' NLA-track - * - however, if the 'solo' track houses the current 'tweaking' strip, + * - however, if the 'solo' track houses the current 'tweaking' strip, * then we should allow this to play, otherwise nothing happens */ if ((adt->action) && ((adt->flag & ADT_NLA_SOLO_TRACK) == 0 || (adt->flag & ADT_NLA_EDIT_ON))) { @@ -2606,9 +2609,9 @@ static void animsys_evaluate_nla(Depsgraph *depsgraph, ListBase *echannels, Poin if ((has_strips) || (adt->actstrip)) { /* make dummy NLA strip, and add that to the stack */ ListBase dummy_trackslist; - + dummy_trackslist.first = dummy_trackslist.last = &dummy_strip; - + if ((nlt) && !(adt->flag & ADT_NLA_EDIT_NOMAP)) { /* edit active action in-place according to its active strip, so copy the data */ memcpy(&dummy_strip, adt->actstrip, sizeof(NlaStrip)); @@ -2618,20 +2621,20 @@ static void animsys_evaluate_nla(Depsgraph *depsgraph, ListBase *echannels, Poin /* set settings of dummy NLA strip from AnimData settings */ dummy_strip.act = adt->action; dummy_strip.remap = adt->remap; - + /* action range is calculated taking F-Modifiers into account (which making new strips doesn't do due to the troublesome nature of that) */ calc_action_range(dummy_strip.act, &dummy_strip.actstart, &dummy_strip.actend, 1); dummy_strip.start = dummy_strip.actstart; dummy_strip.end = (IS_EQF(dummy_strip.actstart, dummy_strip.actend)) ? (dummy_strip.actstart + 1.0f) : (dummy_strip.actend); - + dummy_strip.blendmode = adt->act_blendmode; dummy_strip.extendmode = adt->act_extendmode; dummy_strip.influence = adt->act_influence; - + /* NOTE: must set this, or else the default setting overrides, and this setting doesn't work */ dummy_strip.flag |= NLASTRIP_FLAG_USR_INFLUENCE; } - + /* add this to our list of evaluation strips */ nlastrips_ctime_get_strip(depsgraph, &estrips, &dummy_trackslist, -1, ctime); } @@ -2639,27 +2642,27 @@ static void animsys_evaluate_nla(Depsgraph *depsgraph, ListBase *echannels, Poin /* special case - evaluate as if there isn't any NLA data */ /* TODO: this is really just a stop-gap measure... */ if (G.debug & G_DEBUG) printf("NLA Eval: Stopgap for active action on NLA Stack - no strips case\n"); - + animsys_evaluate_action(depsgraph, ptr, adt->action, adt->remap, ctime); BLI_freelistN(&estrips); return; } } - + /* only continue if there are strips to evaluate */ if (BLI_listbase_is_empty(&estrips)) return; - - + + /* 2. for each strip, evaluate then accumulate on top of existing channels, but don't set values yet */ for (nes = estrips.first; nes; nes = nes->next) nlastrip_evaluate(depsgraph, ptr, echannels, NULL, nes); - + /* 3. free temporary evaluation data that's not used elsewhere */ BLI_freelistN(&estrips); } -/* NLA Evaluation function (mostly for use through do_animdata) +/* NLA Evaluation function (mostly for use through do_animdata) * - All channels that will be affected are not cleared anymore. Instead, we just evaluate into * some temp channels, where values can be accumulated in one go. */ @@ -2672,15 +2675,15 @@ static void animsys_calculate_nla(Depsgraph *depsgraph, PointerRNA *ptr, AnimDat /* evaluate the NLA stack, obtaining a set of values to flush */ animsys_evaluate_nla(depsgraph, &echannels, ptr, adt, ctime); - + /* flush effects of accumulating channels in NLA to the actual data they affect */ nladata_flush_channels(&echannels); - + /* free temp data */ BLI_freelistN(&echannels); } -/* ***************************************** */ +/* ***************************************** */ /* Overrides System - Public API */ /* Clear all overrides */ @@ -2700,7 +2703,7 @@ AnimOverride *BKE_animsys_validate_override(PointerRNA *UNUSED(ptr), char *UNUSE static void animsys_evaluate_overrides(PointerRNA *ptr, AnimData *adt) { AnimOverride *aor; - + /* for each override, simply execute... */ for (aor = adt->overrides.first; aor; aor = aor->next) { PathResolvedRNA anim_rna; @@ -2744,7 +2747,7 @@ static void animsys_evaluate_overrides(PointerRNA *ptr, AnimData *adt) * However, the code for this is relatively harmless, so is left in the code for now. */ -/* Evaluation loop for evaluation animation data +/* Evaluation loop for evaluation animation data * * This assumes that the animation-data provided belongs to the ID block in question, * and that the flags for which parts of the anim-data settings need to be recalculated @@ -2753,14 +2756,14 @@ static void animsys_evaluate_overrides(PointerRNA *ptr, AnimData *adt) void BKE_animsys_evaluate_animdata(Depsgraph *depsgraph, Scene *scene, ID *id, AnimData *adt, float ctime, short recalc) { PointerRNA id_ptr; - + /* sanity checks */ if (ELEM(NULL, id, adt)) return; - + /* get pointer to ID-block for RNA to use */ RNA_id_pointer_create(id, &id_ptr); - + /* recalculate keyframe data: * - NLA before Active Action, as Active Action behaves as 'tweaking track' * that overrides 'rough' work in NLA @@ -2769,7 +2772,7 @@ void BKE_animsys_evaluate_animdata(Depsgraph *depsgraph, Scene *scene, ID *id, A if ((recalc & ADT_RECALC_ANIM) || (adt->recalc & ADT_RECALC_ANIM)) { /* evaluate NLA data */ if ((adt->nla_tracks.first) && !(adt->flag & ADT_NLA_EVAL_OFF)) { - /* evaluate NLA-stack + /* evaluate NLA-stack * - active action is evaluated as part of the NLA stack as the last item */ animsys_calculate_nla(depsgraph, &id_ptr, adt, ctime); @@ -2777,13 +2780,13 @@ void BKE_animsys_evaluate_animdata(Depsgraph *depsgraph, Scene *scene, ID *id, A /* evaluate Active Action only */ else if (adt->action) animsys_evaluate_action_ex(depsgraph, &id_ptr, adt->action, adt->remap, ctime); - + /* reset tag */ adt->recalc &= ~ADT_RECALC_ANIM; } - - /* recalculate drivers - * - Drivers need to be evaluated afterwards, as they can either override + + /* recalculate drivers + * - Drivers need to be evaluated afterwards, as they can either override * or be layered on top of existing animation data. * - Drivers should be in the appropriate order to be evaluated without problems... */ @@ -2793,22 +2796,22 @@ void BKE_animsys_evaluate_animdata(Depsgraph *depsgraph, Scene *scene, ID *id, A { animsys_evaluate_drivers(&id_ptr, adt, ctime); } - - /* always execute 'overrides' + + /* always execute 'overrides' * - Overrides allow editing, by overwriting the value(s) set from animation-data, with the - * value last set by the user (and not keyframed yet). + * value last set by the user (and not keyframed yet). * - Overrides are cleared upon frame change and/or keyframing * - It is best that we execute this every time, so that no errors are likely to occur. */ animsys_evaluate_overrides(&id_ptr, adt); - + /* execute and clear all cached property update functions */ if (scene) { Main *bmain = G.main; // xxx - to get passed in! RNA_property_update_cache_flush(bmain, scene); RNA_property_update_cache_free(); } - + /* clear recalc flag now */ adt->recalc = 0; } @@ -2826,10 +2829,10 @@ void BKE_animsys_evaluate_all_animation(Main *main, Depsgraph *depsgraph, Scene if (G.debug & G_DEBUG) printf("Evaluate all animation - %f\n", ctime); - - /* macros for less typing + + /* macros for less typing * - only evaluate animation data for id if it has users (and not just fake ones) - * - whether animdata exists is checked for by the evaluation function, though taking + * - whether animdata exists is checked for by the evaluation function, though taking * this outside of the function may make things slightly faster? */ #define EVAL_ANIM_IDS(first, aflag) \ @@ -2840,8 +2843,8 @@ void BKE_animsys_evaluate_all_animation(Main *main, Depsgraph *depsgraph, Scene } \ } (void)0 - /* another macro for the "embedded" nodetree cases - * - this is like EVAL_ANIM_IDS, but this handles the case "embedded nodetrees" + /* another macro for the "embedded" nodetree cases + * - this is like EVAL_ANIM_IDS, but this handles the case "embedded nodetrees" * (i.e. scene/material/texture->nodetree) which we need a special exception * for, otherwise they'd get skipped * - ntp = "node tree parent" = datablock where node tree stuff resides @@ -2858,10 +2861,10 @@ void BKE_animsys_evaluate_all_animation(Main *main, Depsgraph *depsgraph, Scene BKE_animsys_evaluate_animdata(depsgraph, scene, id, adt, ctime, aflag); \ } \ } (void)0 - - /* optimization: - * when there are no actions, don't go over database and loop over heaps of datablocks, - * which should ultimately be empty, since it is not possible for now to have any animation + + /* optimization: + * when there are no actions, don't go over database and loop over heaps of datablocks, + * which should ultimately be empty, since it is not possible for now to have any animation * without some actions, and drivers wouldn't get affected by any state changes * * however, if there are some curves, we will need to make sure that their 'ctime' property gets @@ -2870,46 +2873,46 @@ void BKE_animsys_evaluate_all_animation(Main *main, Depsgraph *depsgraph, Scene if (BLI_listbase_is_empty(&main->action) && BLI_listbase_is_empty(&main->curve)) { if (G.debug & G_DEBUG) printf("\tNo Actions, so no animation needs to be evaluated...\n"); - + return; } - + /* nodes */ EVAL_ANIM_IDS(main->nodetree.first, ADT_RECALC_ANIM); - + /* textures */ EVAL_ANIM_NODETREE_IDS(main->tex.first, Tex, ADT_RECALC_ANIM); - + /* lamps */ EVAL_ANIM_NODETREE_IDS(main->lamp.first, Lamp, ADT_RECALC_ANIM); - + /* materials */ EVAL_ANIM_NODETREE_IDS(main->mat.first, Material, ADT_RECALC_ANIM); - + /* cameras */ EVAL_ANIM_IDS(main->camera.first, ADT_RECALC_ANIM); - + /* shapekeys */ EVAL_ANIM_IDS(main->key.first, ADT_RECALC_ANIM); - + /* metaballs */ EVAL_ANIM_IDS(main->mball.first, ADT_RECALC_ANIM); - + /* curves */ EVAL_ANIM_IDS(main->curve.first, ADT_RECALC_ANIM); - + /* armatures */ EVAL_ANIM_IDS(main->armature.first, ADT_RECALC_ANIM); - + /* lattices */ EVAL_ANIM_IDS(main->latt.first, ADT_RECALC_ANIM); - + /* meshes */ EVAL_ANIM_IDS(main->mesh.first, ADT_RECALC_ANIM); - + /* particles */ EVAL_ANIM_IDS(main->particle.first, ADT_RECALC_ANIM); - + /* speakers */ EVAL_ANIM_IDS(main->speaker.first, ADT_RECALC_ANIM); @@ -2918,31 +2921,31 @@ void BKE_animsys_evaluate_all_animation(Main *main, Depsgraph *depsgraph, Scene /* linestyles */ EVAL_ANIM_IDS(main->linestyle.first, ADT_RECALC_ANIM); - + /* grease pencil */ EVAL_ANIM_IDS(main->gpencil.first, ADT_RECALC_ANIM); /* cache files */ EVAL_ANIM_IDS(main->cachefiles.first, ADT_RECALC_ANIM); - + /* objects */ /* ADT_RECALC_ANIM doesn't need to be supplied here, since object AnimData gets * this tagged by Depsgraph on framechange. This optimization means that objects * linked from other (not-visible) scenes will not need their data calculated. */ - EVAL_ANIM_IDS(main->object.first, 0); + EVAL_ANIM_IDS(main->object.first, 0); /* masks */ EVAL_ANIM_IDS(main->mask.first, ADT_RECALC_ANIM); - + /* worlds */ EVAL_ANIM_NODETREE_IDS(main->world.first, World, ADT_RECALC_ANIM); - + /* scenes */ EVAL_ANIM_NODETREE_IDS(main->scene.first, Scene, ADT_RECALC_ANIM); } -/* ***************************************** */ +/* ***************************************** */ /* ************** */ /* Evaluation API */ @@ -3017,7 +3020,7 @@ void BKE_animsys_eval_driver(Depsgraph *depsgraph, PathResolvedRNA anim_rna; if (animsys_store_rna_setting(&id_ptr, NULL, fcu->rna_path, fcu->array_index, &anim_rna)) { const float ctime = DEG_get_ctime(depsgraph); - const float curval = calculate_fcurve(&anim_rna, fcu, ctime); + const float curval = evaluate_fcurve_driver(&anim_rna, fcu, driver_orig, ctime); ok = animsys_write_rna_setting(&anim_rna, curval); if (ok && DEG_is_active(depsgraph)) { animsys_write_orig_anim_rna(&id_ptr, NULL, fcu, curval); diff --git a/source/blender/blenkernel/intern/appdir.c b/source/blender/blenkernel/intern/appdir.c index 3b2534eae73..ccff6216cb3 100644 --- a/source/blender/blenkernel/intern/appdir.c +++ b/source/blender/blenkernel/intern/appdir.c @@ -83,18 +83,18 @@ const char *BKE_appdir_folder_default(void) if (uput_getenv("HOME", documentfolder, MAXPATHLEN)) { if (BLI_is_dir(documentfolder)) return documentfolder; } - + /* add user profile support for WIN 2K / NT. * This is %APPDATA%, which translates to either * %USERPROFILE%\Application Data or since Vista * to %USERPROFILE%\AppData\Roaming */ hResult = SHGetFolderPath(NULL, CSIDL_PERSONAL, NULL, SHGFP_TYPE_CURRENT, documentfolder); - + if (hResult == S_OK) { if (BLI_is_dir(documentfolder)) return documentfolder; } - + return NULL; #endif /* WIN32 */ } @@ -120,7 +120,7 @@ static bool test_path( const char *path_base, const char *path_sep, const char *folder_name) { char tmppath[FILE_MAX]; - + if (path_sep) { BLI_join_dirfile(tmppath, sizeof(tmppath), path_base, path_sep); } @@ -161,7 +161,7 @@ static bool test_env_path(char *path, const char *envvar) { const char *env = envvar ? getenv(envvar) : NULL; if (!env) return false; - + if (BLI_is_dir(env)) { BLI_strncpy(path, env, FILE_MAX); #ifdef PATH_DEBUG @@ -193,7 +193,7 @@ static bool get_path_local( const char *folder_name, const char *subfolder_name, const int ver) { char relfolder[FILE_MAX]; - + #ifdef PATH_DEBUG printf("%s...\n", __func__); #endif @@ -276,11 +276,11 @@ static bool get_path_user( if (!user_path[0]) return false; - + #ifdef PATH_DEBUG printf("%s: %s\n", __func__, user_path); #endif - + if (subfolder_name) { return test_path(targetpath, targetpath_len, user_path, folder_name, subfolder_name); } @@ -334,14 +334,14 @@ static bool get_path_system( system_base_path = (const char *)GHOST_getSystemDir(ver, blender_version_decimal(ver)); if (system_base_path) BLI_strncpy(system_path, system_base_path, FILE_MAX); - + if (!system_path[0]) return false; - + #ifdef PATH_DEBUG printf("%s: %s\n", __func__, system_path); #endif - + if (subfolder_name) { /* try $BLENDERPATH/folder_name/subfolder_name */ return test_path(targetpath, targetpath_len, system_path, folder_name, subfolder_name); @@ -371,16 +371,16 @@ const char *BKE_appdir_folder_id_ex( if (get_path_local(path, path_len, "datafiles", subfolder, ver)) break; if (get_path_system(path, path_len, "datafiles", subfolder, "BLENDER_SYSTEM_DATAFILES", ver)) break; return NULL; - + case BLENDER_USER_DATAFILES: if (get_path_user(path, path_len, "datafiles", subfolder, "BLENDER_USER_DATAFILES", ver)) break; return NULL; - + case BLENDER_SYSTEM_DATAFILES: if (get_path_local(path, path_len, "datafiles", subfolder, ver)) break; if (get_path_system(path, path_len, "datafiles", subfolder, "BLENDER_SYSTEM_DATAFILES", ver)) break; return NULL; - + case BLENDER_USER_AUTOSAVE: if (get_path_user(path, path_len, "autosave", subfolder, "BLENDER_USER_DATAFILES", ver)) break; return NULL; @@ -388,16 +388,16 @@ const char *BKE_appdir_folder_id_ex( case BLENDER_USER_CONFIG: if (get_path_user(path, path_len, "config", subfolder, "BLENDER_USER_CONFIG", ver)) break; return NULL; - + case BLENDER_USER_SCRIPTS: if (get_path_user(path, path_len, "scripts", subfolder, "BLENDER_USER_SCRIPTS", ver)) break; return NULL; - + case BLENDER_SYSTEM_SCRIPTS: if (get_path_local(path, path_len, "scripts", subfolder, ver)) break; if (get_path_system(path, path_len, "scripts", subfolder, "BLENDER_SYSTEM_SCRIPTS", ver)) break; return NULL; - + case BLENDER_SYSTEM_PYTHON: if (get_path_local(path, path_len, "python", subfolder, ver)) break; if (get_path_system(path, path_len, "python", subfolder, "BLENDER_SYSTEM_PYTHON", ver)) break; @@ -407,7 +407,7 @@ const char *BKE_appdir_folder_id_ex( BLI_assert(0); break; } - + return path; } @@ -460,14 +460,14 @@ const char *BKE_appdir_folder_id_create(const int folder_id, const char *subfold /* only for user folders */ if (!ELEM(folder_id, BLENDER_USER_DATAFILES, BLENDER_USER_CONFIG, BLENDER_USER_SCRIPTS, BLENDER_USER_AUTOSAVE)) return NULL; - + path = BKE_appdir_folder_id(folder_id, subfolder); - + if (!path) { path = BKE_appdir_folder_id_user_notest(folder_id, subfolder); if (path) BLI_dir_create_recursive(path); } - + return path; } @@ -739,8 +739,8 @@ static void where_is_temp(char *fullname, char *basename, const size_t maxlen, c if (userdir && BLI_is_dir(userdir)) { BLI_strncpy(fullname, userdir, maxlen); } - - + + #ifdef WIN32 if (fullname[0] == '\0') { const char *tmp = getenv("TEMP"); /* Windows */ @@ -756,7 +756,7 @@ static void where_is_temp(char *fullname, char *basename, const size_t maxlen, c BLI_strncpy(fullname, tmp, maxlen); } } - + if (fullname[0] == '\0') { const char *tmp = getenv("TMPDIR"); if (tmp && BLI_is_dir(tmp)) { @@ -764,7 +764,7 @@ static void where_is_temp(char *fullname, char *basename, const size_t maxlen, c } } #endif - + if (fullname[0] == '\0') { BLI_strncpy(fullname, "/tmp/", maxlen); } diff --git a/source/blender/blenkernel/intern/armature.c b/source/blender/blenkernel/intern/armature.c index 8dbfc35c774..ba45b5acb5d 100644 --- a/source/blender/blenkernel/intern/armature.c +++ b/source/blender/blenkernel/intern/armature.c @@ -632,17 +632,17 @@ void b_bone_spline_setup(bPoseChannel *pchan, int rest, Mat4 result_array[MAX_BB /* add extra rolls */ roll1 += bone->roll1 + (!rest ? pchan->roll1 : 0.0f); roll2 += bone->roll2 + (!rest ? pchan->roll2 : 0.0f); - + if (bone->flag & BONE_ADD_PARENT_END_ROLL) { if (prev) { if (prev->bone) roll1 += prev->bone->roll2; - + if (!rest) roll1 += prev->roll2; } } - + /* extra curve x / y */ /* NOTE: Scale correction factors here are to compensate for some random floating-point glitches * when scaling up the bone or it's parent by a factor of approximately 8.15/6, which results @@ -650,14 +650,14 @@ void b_bone_spline_setup(bPoseChannel *pchan, int rest, Mat4 result_array[MAX_BB */ const float xscale_correction = (do_scale) ? scale[0] : 1.0f; const float yscale_correction = (do_scale) ? scale[2] : 1.0f; - + h1[0] += (bone->curveInX + (!rest ? pchan->curveInX : 0.0f)) * xscale_correction; h1[2] += (bone->curveInY + (!rest ? pchan->curveInY : 0.0f)) * yscale_correction; - + h2[0] += (bone->curveOutX + (!rest ? pchan->curveOutX : 0.0f)) * xscale_correction; h2[2] += (bone->curveOutY + (!rest ? pchan->curveOutY : 0.0f)) * yscale_correction; } - + /* make curve */ if (bone->segments > MAX_BBONE_SUBDIV) bone->segments = MAX_BBONE_SUBDIV; @@ -673,39 +673,39 @@ void b_bone_spline_setup(bPoseChannel *pchan, int rest, Mat4 result_array[MAX_BB for (a = 0, fp = data[0]; a < bone->segments; a++, fp += 4) { sub_v3_v3v3(h1, fp + 4, fp); vec_roll_to_mat3(h1, fp[3], mat3); /* fp[3] is roll */ - + copy_m4_m3(result_array[a].mat, mat3); copy_v3_v3(result_array[a].mat[3], fp); - + if (do_scale) { /* correct for scaling when this matrix is used in scaled space */ mul_m4_series(result_array[a].mat, iscalemat, result_array[a].mat, scalemat); } - + /* BBone scale... */ { const int num_segments = bone->segments; - + const float scaleIn = bone->scaleIn * (!rest ? pchan->scaleIn : 1.0f); const float scaleFactorIn = 1.0f + (scaleIn - 1.0f) * ((float)(num_segments - a) / (float)num_segments); - + const float scaleOut = bone->scaleOut * (!rest ? pchan->scaleOut : 1.0f); const float scaleFactorOut = 1.0f + (scaleOut - 1.0f) * ((float)(a + 1) / (float)num_segments); - + const float scalefac = scaleFactorIn * scaleFactorOut; float bscalemat[4][4], bscale[3]; - + bscale[0] = scalefac; bscale[1] = 1.0f; bscale[2] = scalefac; - + size_to_mat4(bscalemat, bscale); - + /* Note: don't multiply by inverse scale mat here, as it causes problems with scaling shearing and breaking segment chains */ /*mul_m4_series(result_array[a].mat, ibscalemat, result_array[a].mat, bscalemat);*/ mul_m4_series(result_array[a].mat, result_array[a].mat, bscalemat); } - + } } @@ -764,10 +764,10 @@ static void b_bone_deform(bPoseChanDeform *pdef_info, Bone *bone, float co[3], D float (*mat)[4] = b_bone[0].mat; float segment, y; int a; - + /* need to transform co back to bonespace, only need y */ y = mat[0][1] * co[0] + mat[1][1] * co[1] + mat[2][1] * co[2] + mat[3][1]; - + /* now calculate which of the b_bones are deforming this */ segment = bone->length / ((float)bone->segments); a = (int)(y / segment); @@ -1811,7 +1811,7 @@ static void pose_proxy_synchronize(Object *ob, Object *from, int layer_protected for (pchan = pose->chanbase.first; pchan; pchan = pchan->next) { pchanp = BKE_pose_channel_find_name(frompose, pchan->name); - + if (UNLIKELY(pchanp == NULL)) { /* happens for proxies that become invalid because of a missing link * for regular cases it shouldn't happen at all */ @@ -1819,7 +1819,7 @@ static void pose_proxy_synchronize(Object *ob, Object *from, int layer_protected else if (pchan->bone->layer & layer_protected) { ListBase proxylocal_constraints = {NULL, NULL}; bPoseChannel pchanw; - + /* copy posechannel to temp, but restore important pointers */ pchanw = *pchanp; pchanw.bone = pchan->bone; @@ -1835,13 +1835,13 @@ static void pose_proxy_synchronize(Object *ob, Object *from, int layer_protected /* this is freed so copy a copy, else undo crashes */ if (pchanw.prop) { pchanw.prop = IDP_CopyProperty(pchanw.prop); - + /* use the values from the existing props */ if (pchan->prop) { IDP_SyncGroupValues(pchanw.prop, pchan->prop); } } - + /* constraints - proxy constraints are flushed... local ones are added after * 1. extract constraints not from proxy (CONSTRAINT_PROXY_LOCAL) from pchan's constraints * 2. copy proxy-pchan's constraints on-to new @@ -1853,29 +1853,29 @@ static void pose_proxy_synchronize(Object *ob, Object *from, int layer_protected BKE_constraints_proxylocal_extract(&proxylocal_constraints, &pchan->constraints); BKE_constraints_copy(&pchanw.constraints, &pchanp->constraints, false); BLI_movelisttolist(&pchanw.constraints, &proxylocal_constraints); - + /* constraints - set target ob pointer to own object */ for (con = pchanw.constraints.first; con; con = con->next) { const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con); ListBase targets = {NULL, NULL}; bConstraintTarget *ct; - + if (cti && cti->get_constraint_targets) { cti->get_constraint_targets(con, &targets); - + for (ct = targets.first; ct; ct = ct->next) { if (ct->tar == from) ct->tar = ob; } - + if (cti->flush_constraint_targets) cti->flush_constraint_targets(con, &targets, 0); } } - + /* free stuff from current channel */ BKE_pose_channel_free(pchan); - + /* copy data in temp back over to the cleaned-out (but still allocated) original channel */ *pchan = pchanw; if (pchan->custom) { diff --git a/source/blender/blenkernel/intern/armature_update.c b/source/blender/blenkernel/intern/armature_update.c index ce99da87c74..628f92c7803 100644 --- a/source/blender/blenkernel/intern/armature_update.c +++ b/source/blender/blenkernel/intern/armature_update.c @@ -117,7 +117,7 @@ static void splineik_init_tree_from_pchan(Scene *scene, Object *UNUSED(ob), bPos /* only happens on reload file, but violates depsgraph still... fix! */ if (ELEM(NULL, ikData->tar->curve_cache, ikData->tar->curve_cache->path, ikData->tar->curve_cache->path->data)) { BKE_displist_make_curveTypes(depsgraph, scene, ikData->tar, 0); - + /* path building may fail in EditMode after removing verts [#33268]*/ if (ELEM(NULL, ikData->tar->curve_cache->path, ikData->tar->curve_cache->path->data)) { /* BLI_assert(cu->path != NULL); */ @@ -427,21 +427,21 @@ static void splineik_evaluate_bone( { /* improved volume preservation based on the Stretch To constraint */ float final_scale; - + /* as the basis for volume preservation, we use the inverse scale factor... */ if (fabsf(scaleFac) != 0.0f) { /* NOTE: The method here is taken wholesale from the Stretch To constraint */ float bulge = powf(1.0f / fabsf(scaleFac), ikData->bulge); - + if (bulge > 1.0f) { if (ikData->flag & CONSTRAINT_SPLINEIK_USE_BULGE_MAX) { float bulge_max = max_ff(ikData->bulge_max, 1.0f); float hard = min_ff(bulge, bulge_max); - + float range = bulge_max - 1.0f; float scale = (range > 0.0f) ? 1.0f / range : 0.0f; float soft = 1.0f + range * atanf((bulge - 1.0f) * scale) / (float)M_PI_2; - + bulge = interpf(soft, hard, ikData->bulge_smooth); } } @@ -449,15 +449,15 @@ static void splineik_evaluate_bone( if (ikData->flag & CONSTRAINT_SPLINEIK_USE_BULGE_MIN) { float bulge_min = CLAMPIS(ikData->bulge_min, 0.0f, 1.0f); float hard = max_ff(bulge, bulge_min); - + float range = 1.0f - bulge_min; float scale = (range > 0.0f) ? 1.0f / range : 0.0f; float soft = 1.0f - range * atanf((1.0f - bulge) * scale) / (float)M_PI_2; - + bulge = interpf(soft, hard, ikData->bulge_smooth); } } - + /* compute scale factor for xz axes from this value */ final_scale = sqrtf(bulge); } @@ -465,7 +465,7 @@ static void splineik_evaluate_bone( /* no scaling, so scale factor is simple */ final_scale = 1.0f; } - + /* apply the scaling (assuming normalised scale) */ mul_v3_fl(poseMat[0], final_scale); mul_v3_fl(poseMat[2], final_scale); diff --git a/source/blender/blenkernel/intern/blender.c b/source/blender/blenkernel/intern/blender.c index 3f78b096115..c366d822648 100644 --- a/source/blender/blenkernel/intern/blender.c +++ b/source/blender/blenkernel/intern/blender.c @@ -62,6 +62,7 @@ #include "BKE_scene.h" #include "BKE_screen.h" #include "BKE_sequencer.h" +#include "BKE_studiolight.h" #include "DEG_depsgraph.h" @@ -81,23 +82,25 @@ char versionstr[48] = ""; /* only to be called on exit blender */ void BKE_blender_free(void) { - /* samples are in a global list..., also sets G.main->sound->sample NULL */ - BKE_main_free(G.main); - G.main = NULL; + /* samples are in a global list..., also sets G_MAIN->sound->sample NULL */ + + BKE_studiolight_free(); /* needs to run before main free as wm is still referenced for icons preview jobs */ + BKE_main_free(G_MAIN); + G_MAIN = NULL; if (G.log.file != NULL) { fclose(G.log.file); } BKE_spacetypes_free(); /* after free main, it uses space callbacks */ - + IMB_exit(); BKE_cachefiles_exit(); BKE_images_exit(); DEG_free_node_types(); BKE_brush_system_exit(); - RE_texture_rng_exit(); + RE_texture_rng_exit(); BLI_callback_global_finalize(); @@ -122,10 +125,10 @@ void BKE_blender_version_string(char *version_str, size_t maxncpy, short version void BKE_blender_globals_init(void) { memset(&G, 0, sizeof(Global)); - + U.savetime = 1; - G.main = BKE_main_new(); + G_MAIN = BKE_main_new(); strcpy(G.ima, "//"); @@ -142,9 +145,9 @@ void BKE_blender_globals_init(void) void BKE_blender_globals_clear(void) { - BKE_main_free(G.main); /* free all lib data */ + BKE_main_free(G_MAIN); /* free all lib data */ - G.main = NULL; + G_MAIN = NULL; } /***/ @@ -325,7 +328,7 @@ int BKE_blender_test_break(void) if (blender_test_break_cb) blender_test_break_cb(); } - + return (G.is_break == true); } diff --git a/source/blender/blenkernel/intern/blendfile.c b/source/blender/blenkernel/intern/blendfile.c index 597c69408b5..27b5089b092 100644 --- a/source/blender/blenkernel/intern/blendfile.c +++ b/source/blender/blenkernel/intern/blendfile.c @@ -116,7 +116,7 @@ static void setup_app_data( bContext *C, BlendFileData *bfd, const char *filepath, ReportList *reports) { - Main *bmain = G.main; /* Valid usage */ + Main *bmain = G_MAIN; Scene *curscene = NULL; const bool is_startup = (bfd->filename[0] == '\0'); const bool recover = (G.fileflags & G_FILE_RECOVER) != 0; @@ -207,7 +207,7 @@ static void setup_app_data( win->scene = curscene; } - /* BKE_blender_globals_clear will free G.main, here we can still restore pointers */ + /* BKE_blender_globals_clear will free G_MAIN, here we can still restore pointers */ blo_lib_link_restore(bfd->main, CTX_wm_manager(C), curscene, cur_view_layer); if (win) { curscene = win->scene; @@ -230,14 +230,14 @@ static void setup_app_data( } } - /* free G.main Main database */ + /* free G_MAIN Main database */ // CTX_wm_manager_set(C, NULL); BKE_blender_globals_clear(); /* clear old property update cache, in case some old references are left dangling */ RNA_property_update_cache_free(); - bmain = G.main = bfd->main; + bmain = G_MAIN = bfd->main; CTX_data_main_set(C, bmain); diff --git a/source/blender/blenkernel/intern/bmfont.c b/source/blender/blenkernel/intern/bmfont.c index 8018629ef2a..c99894bfbaf 100644 --- a/source/blender/blenkernel/intern/bmfont.c +++ b/source/blender/blenkernel/intern/bmfont.c @@ -71,7 +71,7 @@ void calcAlpha(ImBuf *ibuf) { int i; char *rect; - + if (ibuf) { rect = (char *) ibuf->rect; for (i = ibuf->x * ibuf->y; i > 0; i--) { @@ -86,21 +86,21 @@ void readBitmapFontVersion0(ImBuf *ibuf, unsigned char *rect, int step) int glyphcount, bytes, i, index, linelength, ysize; unsigned char *buffer; bmFont * bmfont; - + linelength = ibuf->x * step; - + glyphcount = (rect[6 * step] << 8) | rect[7 * step]; bytes = ((glyphcount - 1) * sizeof(bmGlyph)) + sizeof(bmFont); - + ysize = (bytes + (ibuf->x - 1)) / ibuf->x; - + if (ysize < ibuf->y) { /* we're first going to copy all data into a linear buffer. * step can be 4 or 1 bytes, and the data is not sequential because * the bitmap was flipped vertically. */ - + buffer = MEM_mallocN(bytes, "readBitmapFontVersion0:buffer"); - + index = 0; for (i = 0; i < bytes; i++) { buffer[i] = rect[index]; @@ -111,12 +111,12 @@ void readBitmapFontVersion0(ImBuf *ibuf, unsigned char *rect, int step) index -= linelength; } } - + /* we're now going to endian convert the data */ - + bmfont = MEM_mallocN(bytes, "readBitmapFontVersion0:bmfont"); index = 0; - + /* first read the header */ bmfont->magic[0] = buffer[index++]; bmfont->magic[1] = buffer[index++]; @@ -126,7 +126,7 @@ void readBitmapFontVersion0(ImBuf *ibuf, unsigned char *rect, int step) bmfont->glyphcount = (buffer[index] << 8) | buffer[index + 1]; index += 2; bmfont->xsize = (buffer[index] << 8) | buffer[index + 1]; index += 2; bmfont->ysize = (buffer[index] << 8) | buffer[index + 1]; index += 2; - + for (i = 0; i < bmfont->glyphcount; i++) { bmfont->glyphs[i].unicode = (buffer[index] << 8) | buffer[index + 1]; index += 2; bmfont->glyphs[i].locx = (buffer[index] << 8) | buffer[index + 1]; index += 2; @@ -141,9 +141,9 @@ void readBitmapFontVersion0(ImBuf *ibuf, unsigned char *rect, int step) printfGlyph(&bmfont->glyphs[i]); } } - + MEM_freeN(buffer); - + if (G.debug & G_DEBUG) { printf("Oldy = %d Newy = %d\n", ibuf->y, ibuf->y - ysize); printf("glyphcount = %d\n", glyphcount); @@ -173,7 +173,7 @@ void detectBitmapFont(ImBuf *ibuf) unsigned char *rect; unsigned short version; int i; - + if (ibuf != NULL && ibuf->rect != NULL) { /* bitmap must have an x size that is a power of two */ if (is_power_of_two(ibuf->x)) { @@ -215,7 +215,7 @@ void detectBitmapFont(ImBuf *ibuf) int locateGlyph(bmFont *bmfont, unsigned short unicode) { int min, max, current = 0; - + if (bmfont) { min = 0; max = bmfont->glyphcount; @@ -242,7 +242,7 @@ int locateGlyph(bmFont *bmfont, unsigned short unicode) } } } - + return(current); } @@ -256,19 +256,19 @@ void matrixGlyph( { int index; bmFont *bmfont; - + *centerx = *centery = 0.0; *sizex = *sizey = 1.0; *transx = *transy = 0.0; *movex = *movey = 0.0; *advance = 1.0; - + if (ibuf) { bmfont = ibuf->userdata; if (bmfont && (ibuf->userflags & IB_BITMAPFONT)) { index = locateGlyph(bmfont, unicode); if (index) { - + *sizex = (bmfont->glyphs[index].sizex) / (float) (bmfont->glyphs[0].sizex); *sizey = (bmfont->glyphs[index].sizey) / (float) (bmfont->glyphs[0].sizey); @@ -279,10 +279,10 @@ void matrixGlyph( *centery = (ibuf->y - bmfont->glyphs[0].locy) / (float) ibuf->y; /* 2.0 units is the default size of an object */ - + *movey = 1.0f - *sizey + 2.0f * (bmfont->glyphs[index].ofsy - bmfont->glyphs[0].ofsy) / (float) bmfont->glyphs[0].sizey; *movex = *sizex - 1.0f + 2.0f * (bmfont->glyphs[index].ofsx - bmfont->glyphs[0].ofsx) / (float) bmfont->glyphs[0].sizex; - + *advance = 2.0f * bmfont->glyphs[index].advance / (float) bmfont->glyphs[0].advance; // printfGlyph(&bmfont->glyphs[index]); diff --git a/source/blender/blenkernel/intern/boids.c b/source/blender/blenkernel/intern/boids.c index eb5cdd02fe5..8fdaf183b06 100644 --- a/source/blender/blenkernel/intern/boids.c +++ b/source/blender/blenkernel/intern/boids.c @@ -277,7 +277,7 @@ static int rule_avoid_collision(BoidRule *rule, BoidBrainData *bbd, BoidValues * sub_v3_v3v3(loc, co1, co2); sub_v3_v3v3(vec, vel1, vel2); - + inp = dot_v3v3(vec, vec); /* velocities not parallel */ @@ -287,7 +287,7 @@ static int rule_avoid_collision(BoidRule *rule, BoidBrainData *bbd, BoidValues * if (t > 0.0f && t < t_min) { madd_v3_v3fl(co1, vel1, t); madd_v3_v3fl(co2, vel2, t); - + sub_v3_v3v3(vec, co2, co1); len = normalize_v3(vec); @@ -327,7 +327,7 @@ static int rule_avoid_collision(BoidRule *rule, BoidBrainData *bbd, BoidValues * sub_v3_v3v3(loc, co1, co2); sub_v3_v3v3(vec, vel1, vel2); - + inp = dot_v3v3(vec, vec); /* velocities not parallel */ @@ -337,7 +337,7 @@ static int rule_avoid_collision(BoidRule *rule, BoidBrainData *bbd, BoidValues * if (t > 0.0f && t < t_min) { madd_v3_v3fl(co1, vel1, t); madd_v3_v3fl(co2, vel2, t); - + sub_v3_v3v3(vec, co2, co1); len = normalize_v3(vec); @@ -395,7 +395,7 @@ static int rule_separate(BoidRule *UNUSED(rule), BoidBrainData *bbd, BoidValues neighbors = BLI_kdtree_range_search( epsys->tree, pa->prev_state.co, &ptn, 2.0f * val->personal_space * pa->size); - + if (neighbors > 0 && ptn[0].dist < len) { sub_v3_v3v3(vec, pa->prev_state.co, ptn[0].co); mul_v3_fl(vec, (2.0f * val->personal_space * pa->size - ptn[0].dist) / ptn[1].dist); @@ -497,13 +497,13 @@ static int rule_follow_leader(BoidRule *rule, BoidBrainData *bbd, BoidValues *va sub_v3_v3v3(vec, flbr->loc, flbr->oloc); mul_v3_fl(vec, 1.0f/bbd->timestep); } - + /* fac is seconds behind leader */ madd_v3_v3fl(loc, vec, -flbr->distance); sub_v3_v3v3(bbd->wanted_co, loc, pa->prev_state.co); bbd->wanted_speed = len_v3(bbd->wanted_co); - + ret = 1; } else if (p % n) { @@ -560,13 +560,13 @@ static int rule_follow_leader(BoidRule *rule, BoidBrainData *bbd, BoidValues *va copy_v3_v3(vec, bbd->sim->psys->particles[p - p%n].prev_state.vel); copy_v3_v3(loc, bbd->sim->psys->particles[p - p%n].prev_state.co); } - + /* fac is seconds behind leader */ madd_v3_v3fl(loc, vec, -flbr->distance); sub_v3_v3v3(bbd->wanted_co, loc, pa->prev_state.co); bbd->wanted_speed = len_v3(bbd->wanted_co); - + ret = 1; } @@ -612,7 +612,7 @@ static int rule_average_speed(BoidRule *rule, BoidBrainData *bbd, BoidValues *va bbd->wanted_co[1] = 2.0f*(0.5f - BLI_rng_get_float(bbd->rng)); bbd->wanted_co[2] = 2.0f*(0.5f - BLI_rng_get_float(bbd->rng)); } - + /* leveling */ if (asbr->level > 0.0f && psys_uses_gravity(bbd->sim)) { project_v3_v3v3(vec, bbd->wanted_co, bbd->sim->scene->physics_settings.gravity); @@ -622,7 +622,7 @@ static int rule_average_speed(BoidRule *rule, BoidBrainData *bbd, BoidValues *va } bbd->wanted_speed = asbr->speed * val->max_speed; - + return 1; } static int rule_fight(BoidRule *rule, BoidBrainData *bbd, BoidValues *val, ParticleData *pa) @@ -662,7 +662,7 @@ static int rule_fight(BoidRule *rule, BoidBrainData *bbd, BoidValues *val, Parti neighbors = BLI_kdtree_range_search( epsys->tree, pa->prev_state.co, &ptn, fbr->distance); - + health = 0.0f; for (n=0; n<neighbors; n++) { @@ -776,7 +776,7 @@ static Object *boid_find_ground(BoidBrainData *bbd, ParticleData *pa, float grou if (bpa->data.mode == eBoidMode_Climbing) { SurfaceModifierData *surmd = NULL; float x[3], v[3]; - + surmd = (SurfaceModifierData *)modifiers_findByType(bpa->ground, eModifierType_Surface ); /* take surface velocity into account */ @@ -869,10 +869,10 @@ static int boid_rule_applies(ParticleData *pa, BoidSettings *UNUSED(boids), Boid if (rule==NULL) return 0; - + if (ELEM(bpa->data.mode, eBoidMode_OnLand, eBoidMode_Climbing) && rule->flag & BOIDRULE_ON_LAND) return 1; - + if (bpa->data.mode==eBoidMode_InAir && rule->flag & BOIDRULE_IN_AIR) return 1; @@ -1050,7 +1050,7 @@ void boid_brain(BoidBrainData *bbd, int p, ParticleData *pa) if (bpa->data.mode == eBoidMode_OnLand) { /* fuzziness makes boids capable of misjudgement */ float mul = 1.0f + state->rule_fuzziness; - + if (boids->options & BOID_ALLOW_FLIGHT && bbd->wanted_co[2] > 0.0f) { float cvel[3], dir[3]; @@ -1166,7 +1166,7 @@ void boid_body(BoidBrainData *bbd, ParticleData *pa) /* auto-leveling & landing if close to ground */ bpa->ground = boid_find_ground(bbd, pa, ground_co, ground_nor); - + /* level = how many particle sizes above ground */ level = (pa->prev_state.co[2] - ground_co[2])/(2.0f * pa->size) - 0.5f; @@ -1227,7 +1227,7 @@ void boid_body(BoidBrainData *bbd, ParticleData *pa) /* constrain speed with maximum acceleration */ old_speed = len_v3(pa->prev_state.vel); - + if (bbd->wanted_speed < old_speed) new_speed = MAX2(bbd->wanted_speed, old_speed - val.max_acc); else @@ -1274,7 +1274,7 @@ void boid_body(BoidBrainData *bbd, ParticleData *pa) mul_v3_fl(force, length); } - + add_v3_v3(acc, force); /* store smoothed acceleration for nice banking etc. */ @@ -1289,7 +1289,7 @@ void boid_body(BoidBrainData *bbd, ParticleData *pa) copy_v3_v3(dvec, acc); mul_v3_fl(dvec, dtime*dtime*0.5f); - + copy_v3_v3(bvec, pa->prev_state.vel); mul_v3_fl(bvec, dtime); add_v3_v3(dvec, bvec); @@ -1468,7 +1468,7 @@ void boid_body(BoidBrainData *bbd, ParticleData *pa) } negate_v3(mat[2]); cross_v3_v3v3(mat[1], mat[2], mat[0]); - + /* apply rotation */ mat3_to_quat_is_ok(q, mat); copy_qt_qt(pa->state.rot, q); diff --git a/source/blender/blenkernel/intern/brush.c b/source/blender/blenkernel/intern/brush.c index 7f50e521e63..42cd7968321 100644 --- a/source/blender/blenkernel/intern/brush.c +++ b/source/blender/blenkernel/intern/brush.c @@ -271,7 +271,7 @@ void BKE_brush_debug_print_state(Brush *br) /* create a fake brush and set it to the defaults */ Brush def = {{NULL}}; brush_defaults(&def); - + #define BR_TEST(field, t) \ if (br->field != def.field) \ printf("br->" #field " = %" #t ";\n", br->field) @@ -281,7 +281,7 @@ void BKE_brush_debug_print_state(Brush *br) printf("br->flag |= " #_f ";\n"); \ else if (!(br->flag & _f) && (def.flag & _f)) \ printf("br->flag &= ~" #_f ";\n") - + #define BR_TEST_FLAG_OVERLAY(_f) \ if ((br->overlay_flags & _f) && !(def.overlay_flags & _f)) \ printf("br->overlay_flags |= " #_f ";\n"); \ @@ -355,7 +355,7 @@ void BKE_brush_debug_print_state(Brush *br) BR_TEST(sub_col[2], f); printf("\n"); - + #undef BR_TEST #undef BR_TEST_FLAG } @@ -757,7 +757,7 @@ int BKE_brush_size_get(const Scene *scene, const Brush *brush) { UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings; int size = (ups->flag & UNIFIED_PAINT_SIZE) ? ups->size : brush->size; - + return size; } diff --git a/source/blender/blenkernel/intern/bvhutils.c b/source/blender/blenkernel/intern/bvhutils.c index e8328139d64..1a7c4e2a4a0 100644 --- a/source/blender/blenkernel/intern/bvhutils.c +++ b/source/blender/blenkernel/intern/bvhutils.c @@ -79,7 +79,7 @@ float bvhtree_sphereray_tri_intersection( const BVHTreeRay *ray, float radius, const float m_dist, const float v0[3], const float v1[3], const float v2[3]) { - + float idist; float p1[3]; float hit_point[3]; @@ -110,7 +110,7 @@ static void mesh_faces_nearest_point(void *userdata, int index, const float co[3 t2 = vert[face->v3].co; t3 = face->v4 ? vert[face->v4].co : NULL; - + do { float nearest_tmp[3], dist_sq; @@ -194,7 +194,7 @@ static void mesh_faces_spherecast(void *userdata, int index, const BVHTreeRay *r t2 = vert[face->v3].co; t3 = face->v4 ? vert[face->v4].co : NULL; - + do { float dist; if (ray->radius == 0.0f) @@ -287,7 +287,7 @@ static void mesh_edges_nearest_point(void *userdata, int index, const float co[3 closest_to_line_segment_v3(nearest_tmp, co, t0, t1); dist_sq = len_squared_v3v3(nearest_tmp, co); - + if (dist_sq < nearest->dist_sq) { nearest->index = index; nearest->dist_sq = dist_sq; diff --git a/source/blender/blenkernel/intern/cachefile.c b/source/blender/blenkernel/intern/cachefile.c index 74c0dca6279..c7d7a3a98eb 100644 --- a/source/blender/blenkernel/intern/cachefile.c +++ b/source/blender/blenkernel/intern/cachefile.c @@ -217,7 +217,7 @@ bool BKE_cachefile_filepath_get( char ext[32]; BLI_path_frame_strip(r_filepath, true, ext); BLI_path_frame(r_filepath, frame, frame_len); - BLI_ensure_extension(r_filepath, FILE_MAX, ext); + BLI_path_extension_ensure(r_filepath, FILE_MAX, ext); /* TODO(kevin): store sequence range? */ return BLI_exists(r_filepath); diff --git a/source/blender/blenkernel/intern/camera.c b/source/blender/blenkernel/intern/camera.c index b1b4f18a6d5..d1ab559515b 100644 --- a/source/blender/blenkernel/intern/camera.c +++ b/source/blender/blenkernel/intern/camera.c @@ -161,7 +161,7 @@ void BKE_camera_object_mode(RenderData *rd, Object *cam_ob) /* get the camera's dof value, takes the dof object into account */ float BKE_camera_object_dof_distance(Object *ob) { - Camera *cam = (Camera *)ob->data; + Camera *cam = (Camera *)ob->data; if (ob->type != OB_CAMERA) return 0.0f; if (cam->dof_ob) { diff --git a/source/blender/blenkernel/intern/cdderivedmesh.c b/source/blender/blenkernel/intern/cdderivedmesh.c index 7bcc05b0e37..72a1f941c26 100644 --- a/source/blender/blenkernel/intern/cdderivedmesh.c +++ b/source/blender/blenkernel/intern/cdderivedmesh.c @@ -284,7 +284,7 @@ static PBVH *cdDM_getPBVH(Object *ob, DerivedMesh *dm) pbvh_show_diffuse_color_set(cddm->pbvh, ob->sculpt->show_diffuse_color); pbvh_show_mask_set(cddm->pbvh, ob->sculpt->show_mask); } - + /* always build pbvh from original mesh, and only use it for drawing if * this derivedmesh is just original mesh. it's the multires subsurf dm @@ -305,7 +305,7 @@ static PBVH *cdDM_getPBVH(Object *ob, DerivedMesh *dm) me->mvert, me->totloop, me->totpoly, looptri); - + BKE_pbvh_build_mesh( cddm->pbvh, me->mpoly, me->mloop, @@ -434,7 +434,7 @@ static void cdDM_foreachMappedFaceCenter( else { orig = i; } - + ml = &cddm->mloop[mp->loopstart]; BKE_mesh_calc_poly_center(mp, ml, mvert, cent); @@ -723,7 +723,7 @@ static void loops_to_customdata_corners( for (i = 0; i < numUV; i++) { texface = CustomData_get_n(facedata, CD_MTFACE, cdindex, i); - + for (j = 0; j < 3; j++) { l = l3[j]; mloopuv = CustomData_bmesh_get_n(&bm->ldata, l->head.data, CD_MLOOPUV, i); @@ -733,7 +733,7 @@ static void loops_to_customdata_corners( for (i = 0; i < numCol; i++) { mcol = CustomData_get_n(facedata, CD_MCOL, cdindex, i); - + for (j = 0; j < 3; j++) { l = l3[j]; mloopcol = CustomData_bmesh_get_n(&bm->ldata, l->head.data, CD_MLOOPCOL, i); @@ -780,18 +780,18 @@ static DerivedMesh *cddm_from_bmesh_ex( int *index, add_orig; CustomDataMask mask; unsigned int i, j; - + const int cd_vert_bweight_offset = CustomData_get_offset(&bm->vdata, CD_BWEIGHT); const int cd_edge_bweight_offset = CustomData_get_offset(&bm->edata, CD_BWEIGHT); const int cd_edge_crease_offset = CustomData_get_offset(&bm->edata, CD_CREASE); - + dm->deformedOnly = 1; - + /* don't add origindex layer if one already exists */ add_orig = !CustomData_has_layer(&bm->pdata, CD_ORIGINDEX); mask = use_mdisps ? CD_MASK_DERIVEDMESH | CD_MASK_MDISPS : CD_MASK_DERIVEDMESH; - + /* don't process shapekeys, we only feed them through the modifier stack as needed, * e.g. for applying modifiers or the like*/ mask &= ~CD_MASK_SHAPEKEY; @@ -882,7 +882,7 @@ static DerivedMesh *cddm_from_bmesh_ex( test_index_face(mf, &dm->faceData, i, 3); } } - + index = CustomData_get_layer(&dm->polyData, CD_ORIGINDEX); j = 0; BM_ITER_MESH_INDEX (efa, &iter, bm, BM_FACES_OF_MESH, i) { @@ -1585,7 +1585,7 @@ DerivedMesh *CDDM_merge_verts(DerivedMesh *dm, const int *vtargetmap, const int newv[i] = 0; } } - + /* now link target vertices to destination indices */ for (i = 0; i < totvert; i++) { if (vtargetmap[i] != -1) { @@ -1622,7 +1622,7 @@ DerivedMesh *CDDM_merge_verts(DerivedMesh *dm, const int *vtargetmap, const int newe[i] = -1; } } - + if (merge_mode == CDDM_MERGE_VERTS_DUMP_IF_EQUAL) { /* In this mode, we need to determine, whenever a poly' vertices are all mapped */ /* if the targets already make up a poly, in which case the new poly is dropped */ @@ -1663,7 +1663,7 @@ DerivedMesh *CDDM_merge_verts(DerivedMesh *dm, const int *vtargetmap, const int mv = cddm->mvert; for (i = 0; i < totpoly; i++, mp++) { MPoly *mp_new; - + ml = cddm->mloop + mp->loopstart; /* check faces with all vertices merged */ @@ -1867,7 +1867,7 @@ DerivedMesh *CDDM_merge_verts(DerivedMesh *dm, const int *vtargetmap, const int mp_new->totloop = c; BLI_assert(mp_new->totloop >= 3); mp_new->loopstart = STACK_SIZE(mloop) - c; - + STACK_PUSH(oldp, i); } /* end of the loop that tests polys */ @@ -1878,11 +1878,11 @@ DerivedMesh *CDDM_merge_verts(DerivedMesh *dm, const int *vtargetmap, const int BLI_gset_free(poly_gset, NULL); MEM_freeN(poly_keys); } - + /*create new cddm*/ cddm2 = (CDDerivedMesh *)CDDM_from_template( (DerivedMesh *)cddm, STACK_SIZE(mvert), STACK_SIZE(medge), 0, STACK_SIZE(mloop), STACK_SIZE(mpoly)); - + /*update edge indices and copy customdata*/ med = medge; for (i = 0; i < cddm2->dm.numEdgeData; i++, med++) { @@ -1896,7 +1896,7 @@ DerivedMesh *CDDM_merge_verts(DerivedMesh *dm, const int *vtargetmap, const int CustomData_copy_data(&dm->edgeData, &cddm2->dm.edgeData, olde[i], i, 1); } - + /*update loop indices and copy customdata*/ ml = mloop; for (i = 0; i < cddm2->dm.numLoopData; i++, ml++) { @@ -1906,19 +1906,19 @@ DerivedMesh *CDDM_merge_verts(DerivedMesh *dm, const int *vtargetmap, const int CustomData_copy_data(&dm->loopData, &cddm2->dm.loopData, oldl[i], i, 1); } - + /*copy vertex customdata*/ mv = mvert; for (i = 0; i < cddm2->dm.numVertData; i++, mv++) { CustomData_copy_data(&dm->vertData, &cddm2->dm.vertData, oldv[i], i, 1); } - + /*copy poly customdata*/ mp = mpoly; for (i = 0; i < cddm2->dm.numPolyData; i++, mp++) { CustomData_copy_data(&dm->polyData, &cddm2->dm.polyData, oldp[i], i, 1); } - + /*copy over data. CustomData_add_layer can do this, need to look it up.*/ memcpy(cddm2->mvert, mvert, sizeof(MVert) * STACK_SIZE(mvert)); memcpy(cddm2->medge, medge, sizeof(MEdge) * STACK_SIZE(medge)); @@ -1946,7 +1946,7 @@ DerivedMesh *CDDM_merge_verts(DerivedMesh *dm, const int *vtargetmap, const int /*free old derivedmesh*/ dm->needsFree = 1; dm->release(dm); - + return (DerivedMesh *)cddm2; } #endif @@ -1966,7 +1966,7 @@ void CDDM_calc_edges_tessface(DerivedMesh *dm) for (i = 0; i < numFaces; i++, mf++) { BLI_edgeset_add(eh, mf->v1, mf->v2); BLI_edgeset_add(eh, mf->v2, mf->v3); - + if (mf->v4) { BLI_edgeset_add(eh, mf->v3, mf->v4); BLI_edgeset_add(eh, mf->v4, mf->v1); @@ -2212,7 +2212,7 @@ void CDDM_tessfaces_to_faces(DerivedMesh *dm) void CDDM_set_mvert(DerivedMesh *dm, MVert *mvert) { CDDerivedMesh *cddm = (CDDerivedMesh *)dm; - + if (!CustomData_has_layer(&dm->vertData, CD_MVERT)) CustomData_add_layer(&dm->vertData, CD_MVERT, CD_ASSIGN, mvert, dm->numVertData); diff --git a/source/blender/blenkernel/intern/cloth.c b/source/blender/blenkernel/intern/cloth.c index cc1c7260cbc..c5d9472ca4b 100644 --- a/source/blender/blenkernel/intern/cloth.c +++ b/source/blender/blenkernel/intern/cloth.c @@ -80,7 +80,7 @@ static void cloth_apply_vgroup ( ClothModifierData *clmd, Mesh *mesh ); * 2. fill object with standard values or with the GUI settings if given */ void cloth_init(ClothModifierData *clmd ) -{ +{ /* Initialize our new data structure to reasonable values. */ clmd->sim_parms->gravity[0] = 0.0; clmd->sim_parms->gravity[1] = 0.0; @@ -91,7 +91,7 @@ void cloth_init(ClothModifierData *clmd ) clmd->sim_parms->bending = 0.5; clmd->sim_parms->max_bend = 0.5; clmd->sim_parms->bending_damping = 0.5; - clmd->sim_parms->Cdis = 5.0; + clmd->sim_parms->Cdis = 5.0; clmd->sim_parms->Cvi = 1.0; clmd->sim_parms->mass = 0.3f; clmd->sim_parms->stepsPerFrame = 5; @@ -107,7 +107,7 @@ void cloth_init(ClothModifierData *clmd ) clmd->sim_parms->time_scale = 1.0f; /* multiplies cloth speed */ clmd->sim_parms->reset = 0; clmd->sim_parms->vel_damping = 1.0f; /* 1.0 = no damping, 0.0 = fully dampened */ - + clmd->coll_parms->self_friction = 5.0; clmd->coll_parms->friction = 5.0; clmd->coll_parms->loop_count = 2; @@ -155,27 +155,27 @@ static BVHTree *bvhselftree_build_from_cloth (ClothModifierData *clmd, float eps if (!cloth) return NULL; - + verts = cloth->verts; - + /* in the moment, return zero if no faces there */ if (!cloth->mvert_num) return NULL; - + /* create quadtree with k=26 */ bvhtree = BLI_bvhtree_new(cloth->mvert_num, epsilon, 4, 6); - + /* fill tree */ for (i = 0; i < cloth->mvert_num; i++, verts++) { const float *co; co = verts->xold; - + BLI_bvhtree_insert(bvhtree, i, co, 1); } - + /* balance tree */ BLI_bvhtree_balance(bvhtree); - + return bvhtree; } @@ -194,10 +194,10 @@ static BVHTree *bvhtree_build_from_cloth (ClothModifierData *clmd, float epsilon if (!cloth) return NULL; - + verts = cloth->verts; vt = cloth->tri; - + /* in the moment, return zero if no faces there */ if (!cloth->tri_num) return NULL; @@ -218,23 +218,23 @@ static BVHTree *bvhtree_build_from_cloth (ClothModifierData *clmd, float epsilon /* balance tree */ BLI_bvhtree_balance(bvhtree); - + return bvhtree; } void bvhtree_update_from_cloth(ClothModifierData *clmd, bool moving) -{ +{ unsigned int i = 0; Cloth *cloth = clmd->clothObject; BVHTree *bvhtree = cloth->bvhtree; ClothVertex *verts = cloth->verts; const MVertTri *vt; - + if (!bvhtree) return; - + vt = cloth->tri; - + /* update vertex position in bvh tree */ if (verts && vt) { for (i = 0; i < cloth->tri_num; i++, vt++) { @@ -257,25 +257,25 @@ void bvhtree_update_from_cloth(ClothModifierData *clmd, bool moving) else { ret = BLI_bvhtree_update_node(bvhtree, i, co[0], NULL, 3); } - + /* check if tree is already full */ if (ret == false) { break; } } - + BLI_bvhtree_update_tree(bvhtree); } } void bvhselftree_update_from_cloth(ClothModifierData *clmd, bool moving) -{ +{ unsigned int i = 0; Cloth *cloth = clmd->clothObject; BVHTree *bvhtree = cloth->bvhselftree; ClothVertex *verts = cloth->verts; const MVertTri *vt; - + if (!bvhtree) return; @@ -304,7 +304,7 @@ void bvhselftree_update_from_cloth(ClothModifierData *clmd, bool moving) break; } } - + BLI_bvhtree_update_tree(bvhtree); } } @@ -312,13 +312,13 @@ void bvhselftree_update_from_cloth(ClothModifierData *clmd, bool moving) void cloth_clear_cache(Object *ob, ClothModifierData *clmd, float framenr) { PTCacheID pid; - + BKE_ptcache_id_from_cloth(&pid, ob, clmd); // don't do anything as long as we're in editmode! if (pid.cache->edit && ob->mode & OB_MODE_PARTICLE_EDIT) return; - + BKE_ptcache_id_clear(&pid, PTCACHE_CLEAR_AFTER, framenr); } @@ -335,13 +335,13 @@ static int do_init_cloth(Object *ob, ClothModifierData *clmd, Mesh *result, int modifier_setError(&(clmd->modifier), "Can't initialize cloth"); return 0; } - + if (clmd->clothObject == NULL) { BKE_ptcache_invalidate(cache); modifier_setError(&(clmd->modifier), "Null cloth object"); return 0; } - + BKE_cloth_solver_set_positions(clmd); clmd->clothObject->last_frame= MINFRAME-1; @@ -387,7 +387,7 @@ static int do_step_cloth(struct Depsgraph *depsgraph, Object *ob, ClothModifierD cloth_update_spring_lengths ( clmd, result ); cloth_update_springs( clmd ); - + // TIMEIT_START(cloth_step) /* call the solver. */ @@ -398,7 +398,7 @@ static int do_step_cloth(struct Depsgraph *depsgraph, Object *ob, ClothModifierD pdEndEffectors(&effectors); // printf ( "%f\n", ( float ) tval() ); - + return ret; } @@ -429,7 +429,7 @@ void clothModifier_do(ClothModifierData *clmd, struct Depsgraph *depsgraph, Scen cache->last_exact= 0; cache->flag &= ~PTCACHE_REDO_NEEDED; } - + // unused in the moment, calculated separately in implicit.c clmd->sim_parms->dt = clmd->sim_parms->timescale / clmd->sim_parms->stepsPerFrame; @@ -507,13 +507,13 @@ void clothModifier_do(ClothModifierData *clmd, struct Depsgraph *depsgraph, Scen void cloth_free_modifier(ClothModifierData *clmd ) { Cloth *cloth = NULL; - + if ( !clmd ) return; cloth = clmd->clothObject; - + if ( cloth ) { BPH_cloth_solver_free(clmd); @@ -529,12 +529,12 @@ void cloth_free_modifier(ClothModifierData *clmd ) LinkNode *search = cloth->springs; while (search) { ClothSpring *spring = search->link; - + MEM_freeN ( spring ); search = search->next; } BLI_linklist_free(cloth->springs, NULL); - + cloth->springs = NULL; } @@ -544,7 +544,7 @@ void cloth_free_modifier(ClothModifierData *clmd ) // free BVH collision tree if ( cloth->bvhtree ) BLI_bvhtree_free ( cloth->bvhtree ); - + if ( cloth->bvhselftree ) BLI_bvhtree_free ( cloth->bvhselftree ); @@ -554,8 +554,8 @@ void cloth_free_modifier(ClothModifierData *clmd ) if (cloth->edgeset) BLI_edgeset_free(cloth->edgeset); - - + + /* if (clmd->clothObject->facemarks) MEM_freeN(clmd->clothObject->facemarks); @@ -571,12 +571,12 @@ void cloth_free_modifier_extern(ClothModifierData *clmd ) Cloth *cloth = NULL; if (G.debug_value > 0) printf("cloth_free_modifier_extern\n"); - + if ( !clmd ) return; cloth = clmd->clothObject; - + if ( cloth ) { if (G.debug_value > 0) printf("cloth_free_modifier_extern in\n"); @@ -610,7 +610,7 @@ void cloth_free_modifier_extern(ClothModifierData *clmd ) // free BVH collision tree if ( cloth->bvhtree ) BLI_bvhtree_free ( cloth->bvhtree ); - + if ( cloth->bvhselftree ) BLI_bvhtree_free ( cloth->bvhselftree ); @@ -660,11 +660,11 @@ static void cloth_to_object (Object *ob, ClothModifierData *clmd, float (*verte int cloth_uses_vgroup(ClothModifierData *clmd) { - return (((clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_SCALING ) || + return (((clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_SCALING ) || (clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL ) || (clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_SEW) || - (clmd->coll_parms->flags & CLOTH_COLLSETTINGS_FLAG_SELF)) && - ((clmd->sim_parms->vgroup_mass>0) || + (clmd->coll_parms->flags & CLOTH_COLLSETTINGS_FLAG_SELF)) && + ((clmd->sim_parms->vgroup_mass>0) || (clmd->sim_parms->vgroup_struct>0)|| (clmd->sim_parms->vgroup_bend>0) || (clmd->sim_parms->vgroup_shrink>0) || @@ -693,7 +693,7 @@ static void cloth_apply_vgroup ( ClothModifierData *clmd, Mesh *mesh ) mvert_num = mesh->totvert; verts = clothObj->verts; - + if (cloth_uses_vgroup(clmd)) { for (i = 0; i < mvert_num; i++, verts++) { @@ -717,21 +717,21 @@ static void cloth_apply_vgroup ( ClothModifierData *clmd, Mesh *mesh ) verts->goal = dvert->dw [j].weight; /* goalfac= 1.0f; */ /* UNUSED */ - + // Kicking goal factor to simplify things...who uses that anyway? // ABS ( clmd->sim_parms->maxgoal - clmd->sim_parms->mingoal ); - + verts->goal = pow4f(verts->goal); if ( verts->goal >= SOFTGOALSNAP ) verts->flags |= CLOTH_VERT_FLAG_PINNED; } - + if (clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_SCALING ) { if ( dvert->dw[j].def_nr == (clmd->sim_parms->vgroup_struct-1)) { verts->struct_stiff = dvert->dw [j].weight; verts->shear_stiff = dvert->dw [j].weight; } - + if ( dvert->dw[j].def_nr == (clmd->sim_parms->vgroup_bend-1)) { verts->bend_stiff = dvert->dw [j].weight; } @@ -786,7 +786,7 @@ static int cloth_from_object(Object *ob, ClothModifierData *clmd, Mesh *mesh, fl Cloth *cloth = NULL; float maxdist = 0; - // If we have a clothObject, free it. + // If we have a clothObject, free it. if ( clmd->clothObject != NULL ) { cloth_free_modifier ( clmd ); if (G.debug_value > 0) @@ -837,9 +837,9 @@ static int cloth_from_object(Object *ob, ClothModifierData *clmd, Mesh *mesh, fl else copy_v3_v3(verts->xrest, verts->x); } - + /* no GUI interface yet */ - verts->mass = clmd->sim_parms->mass; + verts->mass = clmd->sim_parms->mass; verts->impulse_count = 0; if ( clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL ) @@ -859,7 +859,7 @@ static int cloth_from_object(Object *ob, ClothModifierData *clmd, Mesh *mesh, fl verts->impulse_count = 0; copy_v3_v3 ( verts->impulse, tnull ); } - + // apply / set vertex groups // has to be happen before springs are build! cloth_apply_vgroup (clmd, mesh); @@ -870,19 +870,19 @@ static int cloth_from_object(Object *ob, ClothModifierData *clmd, Mesh *mesh, fl printf("cloth_free_modifier cloth_build_springs\n"); return 0; } - + // init our solver BPH_cloth_solver_init(ob, clmd); - + if (!first) BKE_cloth_solver_set_positions(clmd); clmd->clothObject->bvhtree = bvhtree_build_from_cloth ( clmd, MAX2(clmd->coll_parms->epsilon, clmd->coll_parms->distance_repel) ); - + for (i = 0; i < mesh->totvert; i++) { maxdist = MAX2(maxdist, clmd->coll_parms->selfepsilon* ( cloth->verts[i].avg_spring_len*2.0f)); } - + clmd->clothObject->bvhselftree = bvhselftree_build_from_cloth ( clmd, maxdist ); return 1; @@ -958,17 +958,17 @@ static void cloth_free_errorsprings(Cloth *cloth, LinkNodePair *edgelist) LinkNode *search = cloth->springs; while (search) { ClothSpring *spring = search->link; - + MEM_freeN ( spring ); search = search->next; } BLI_linklist_free(cloth->springs, NULL); - + cloth->springs = NULL; } cloth_free_edgelist(edgelist, cloth->mvert_num); - + if (cloth->edgeset) { BLI_edgeset_free(cloth->edgeset); cloth->edgeset = NULL; @@ -981,10 +981,10 @@ static void cloth_hair_update_bending_targets(ClothModifierData *clmd) LinkNode *search = NULL; float hair_frame[3][3], dir_old[3], dir_new[3]; int prev_mn; /* to find hair chains */ - + if (!clmd->hairdata) return; - + /* XXX Note: we need to propagate frames from the root up, * but structural hair springs are stored in reverse order. * The bending springs however are then inserted in the same @@ -992,17 +992,17 @@ static void cloth_hair_update_bending_targets(ClothModifierData *clmd) * This messy situation can be resolved when solver data is * generated directly from a dedicated hair system. */ - + prev_mn = -1; for (search = cloth->springs; search; search = search->next) { ClothSpring *spring = search->link; ClothHairData *hair_ij, *hair_kl; bool is_root = spring->kl != prev_mn; - + if (spring->type != CLOTH_SPRING_TYPE_BENDING_ANG) { continue; } - + hair_ij = &clmd->hairdata[spring->ij]; hair_kl = &clmd->hairdata[spring->kl]; if (is_root) { @@ -1013,39 +1013,39 @@ static void cloth_hair_update_bending_targets(ClothModifierData *clmd) */ copy_v3_v3(dir_new, hair_frame[2]); } - + copy_v3_v3(dir_old, dir_new); sub_v3_v3v3(dir_new, cloth->verts[spring->mn].x, cloth->verts[spring->kl].x); normalize_v3(dir_new); - + #if 0 if (clmd->debug_data && (spring->ij == 0 || spring->ij == 1)) { float a[3], b[3]; - + copy_v3_v3(a, cloth->verts[spring->kl].x); // BKE_sim_debug_data_add_dot(clmd->debug_data, cloth_vert ? cloth_vert->x : key->co, 1, 1, 0, "frames", 8246, p, k); - + mul_v3_v3fl(b, hair_frame[0], clmd->sim_parms->avg_spring_len); BKE_sim_debug_data_add_vector(clmd->debug_data, a, b, 1, 0, 0, "frames", 8247, spring->kl, spring->mn); - + mul_v3_v3fl(b, hair_frame[1], clmd->sim_parms->avg_spring_len); BKE_sim_debug_data_add_vector(clmd->debug_data, a, b, 0, 1, 0, "frames", 8248, spring->kl, spring->mn); - + mul_v3_v3fl(b, hair_frame[2], clmd->sim_parms->avg_spring_len); BKE_sim_debug_data_add_vector(clmd->debug_data, a, b, 0, 0, 1, "frames", 8249, spring->kl, spring->mn); } #endif - + /* get local targets for kl/mn vertices by putting rest targets into the current frame, * then multiply with the rest length to get the actual goals */ - + mul_v3_m3v3(spring->target, hair_frame, hair_kl->rest_target); mul_v3_fl(spring->target, spring->restlen); - + /* move frame to next hair segment */ cloth_parallel_transport_hair_frame(hair_frame, dir_old, dir_new); - + prev_mn = spring->mn; } } @@ -1056,10 +1056,10 @@ static void cloth_hair_update_bending_rest_targets(ClothModifierData *clmd) LinkNode *search = NULL; float hair_frame[3][3], dir_old[3], dir_new[3]; int prev_mn; /* to find hair roots */ - + if (!clmd->hairdata) return; - + /* XXX Note: we need to propagate frames from the root up, * but structural hair springs are stored in reverse order. * The bending springs however are then inserted in the same @@ -1067,17 +1067,17 @@ static void cloth_hair_update_bending_rest_targets(ClothModifierData *clmd) * This messy situation can be resolved when solver data is * generated directly from a dedicated hair system. */ - + prev_mn = -1; for (search = cloth->springs; search; search = search->next) { ClothSpring *spring = search->link; ClothHairData *hair_ij, *hair_kl; bool is_root = spring->kl != prev_mn; - + if (spring->type != CLOTH_SPRING_TYPE_BENDING_ANG) { continue; } - + hair_ij = &clmd->hairdata[spring->ij]; hair_kl = &clmd->hairdata[spring->kl]; if (is_root) { @@ -1088,18 +1088,18 @@ static void cloth_hair_update_bending_rest_targets(ClothModifierData *clmd) */ copy_v3_v3(dir_new, hair_frame[2]); } - + copy_v3_v3(dir_old, dir_new); sub_v3_v3v3(dir_new, cloth->verts[spring->mn].xrest, cloth->verts[spring->kl].xrest); normalize_v3(dir_new); - + /* dir expressed in the hair frame defines the rest target direction */ copy_v3_v3(hair_kl->rest_target, dir_new); mul_transposed_m3_v3(hair_frame, hair_kl->rest_target); - + /* move frame to next hair segment */ cloth_parallel_transport_hair_frame(hair_frame, dir_old, dir_new); - + prev_mn = spring->mn; } } @@ -1148,10 +1148,10 @@ static void cloth_update_springs( ClothModifierData *clmd ) spring->flags |= CLOTH_SPRING_FLAG_DEACTIVATE; } } - + search = search->next; } - + cloth_hair_update_bending_targets(clmd); } @@ -1243,10 +1243,10 @@ BLI_INLINE void madd_m3_m3fl(float r[3][3], float m[3][3], float f) void cloth_parallel_transport_hair_frame(float mat[3][3], const float dir_old[3], const float dir_new[3]) { float rot[3][3]; - + /* rotation between segments */ rotation_between_vecs_to_mat3(rot, dir_old, dir_new); - + /* rotate the frame */ mul_m3_m3m3(mat, rot, mat); } @@ -1268,7 +1268,7 @@ static int cloth_build_springs ( ClothModifierData *clmd, Mesh *mesh ) LinkNodePair *edgelist; EdgeSet *edgeset = NULL; LinkNode *search = NULL, *search2 = NULL; - + // error handling if ( numedges==0 ) return 0; @@ -1282,7 +1282,7 @@ static int cloth_build_springs ( ClothModifierData *clmd, Mesh *mesh ) cloth->edgeset = NULL; edgelist = MEM_callocN(sizeof(*edgelist) * mvert_num, "cloth_edgelist_alloc" ); - + if (!edgelist) return 0; @@ -1314,7 +1314,7 @@ static int cloth_build_springs ( ClothModifierData *clmd, Mesh *mesh ) spring->flags = 0; struct_springs++; - + BLI_linklist_prepend ( &cloth->springs, spring ); } else { @@ -1325,7 +1325,7 @@ static int cloth_build_springs ( ClothModifierData *clmd, Mesh *mesh ) if (struct_springs_real > 0) clmd->sim_parms->avg_spring_len /= struct_springs_real; - + for (i = 0; i < mvert_num; i++) { if (cloth->verts[i].spring_count > 0) cloth->verts[i].avg_spring_len = cloth->verts[i].avg_spring_len * 0.49f / ((float)cloth->verts[i].spring_count); @@ -1415,15 +1415,15 @@ static int cloth_build_springs ( ClothModifierData *clmd, Mesh *mesh ) while (search && search2) { tspring = search->link; tspring2 = search2->link; - + if (tspring->ij == tspring2->kl) { spring = (ClothSpring *)MEM_callocN ( sizeof ( ClothSpring ), "cloth spring" ); - + if (!spring) { cloth_free_errorsprings(cloth, edgelist); return 0; } - + spring->ij = tspring2->ij; spring->kl = tspring->ij; spring->mn = tspring->kl; @@ -1431,10 +1431,10 @@ static int cloth_build_springs ( ClothModifierData *clmd, Mesh *mesh ) spring->type = CLOTH_SPRING_TYPE_BENDING_ANG; spring->stiffness = (cloth->verts[spring->kl].bend_stiff + cloth->verts[spring->ij].bend_stiff) / 2.0f; bend_springs++; - + BLI_linklist_prepend ( &cloth->springs, spring ); } - + search = search->next; search2 = search2->next; } @@ -1452,33 +1452,33 @@ static int cloth_build_springs ( ClothModifierData *clmd, Mesh *mesh ) while (search && search2) { tspring = search->link; tspring2 = search2->link; - + if (tspring->ij == tspring2->kl) { spring = (ClothSpring *)MEM_callocN ( sizeof ( ClothSpring ), "cloth spring" ); - + if (!spring) { cloth_free_errorsprings(cloth, edgelist); return 0; } - + spring->ij = tspring2->ij; spring->kl = tspring->kl; spring->restlen = len_v3v3(cloth->verts[spring->kl].xrest, cloth->verts[spring->ij].xrest); spring->type = CLOTH_SPRING_TYPE_BENDING; spring->stiffness = (cloth->verts[spring->kl].bend_stiff + cloth->verts[spring->ij].bend_stiff) / 2.0f; bend_springs++; - + BLI_linklist_prepend ( &cloth->springs, spring ); } - + search = search->next; search2 = search2->next; } } - + cloth_hair_update_bending_rest_targets(clmd); } - + /* note: the edges may already exist so run reinsert */ /* insert other near springs in edgeset AFTER bending springs are calculated (for selfcolls) */ @@ -1492,10 +1492,10 @@ static int cloth_build_springs ( ClothModifierData *clmd, Mesh *mesh ) BLI_edgeset_add(edgeset, mloop[mpoly[i].loopstart + 1].v, mloop[mpoly[i].loopstart + 3].v); } } - - + + cloth->numsprings = struct_springs + shear_springs + bend_springs; - + cloth_free_edgelist(edgelist, mvert_num); #if 0 diff --git a/source/blender/blenkernel/intern/collection.c b/source/blender/blenkernel/intern/collection.c index ab0ec8b0491..eef4a6210c8 100644 --- a/source/blender/blenkernel/intern/collection.c +++ b/source/blender/blenkernel/intern/collection.c @@ -297,20 +297,6 @@ void BKE_collection_new_name_get(Collection *collection_parent, char *rname) MEM_freeN(name); } -/************************* Dependencies ****************************/ - -bool BKE_collection_is_animated(Collection *collection, Object *UNUSED(parent)) -{ - FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(collection, object) - { - if (object->proxy) { - return true; - } - } - FOREACH_COLLECTION_OBJECT_RECURSIVE_END; - return false; -} - /* **************** Object List Cache *******************/ static void collection_object_cache_fill(ListBase *lb, Collection *collection, int parent_restrict) @@ -323,20 +309,21 @@ static void collection_object_cache_fill(ListBase *lb, Collection *collection, i if (base == NULL) { base = MEM_callocN(sizeof(Base), "Object Base"); base->object = cob->ob; + BLI_addtail(lb, base); + } - if ((child_restrict & COLLECTION_RESTRICT_VIEW) == 0) { - base->flag |= BASE_VISIBLED | BASE_VISIBLE_VIEWPORT; - - if ((child_restrict & COLLECTION_RESTRICT_SELECT) == 0) { - base->flag |= BASE_SELECTABLED; - } - } + int object_restrict = base->object->restrictflag; - if ((child_restrict & COLLECTION_RESTRICT_RENDER) == 0) { - base->flag |= BASE_VISIBLE_RENDER; - } + if (((child_restrict & COLLECTION_RESTRICT_VIEW) == 0) && + ((object_restrict & OB_RESTRICT_VIEW) == 0)) + { + base->flag |= BASE_VISIBLE_VIEWPORT; + } - BLI_addtail(lb, base); + if (((child_restrict & COLLECTION_RESTRICT_RENDER) == 0) && + ((object_restrict & OB_RESTRICT_RENDER) == 0)) + { + base->flag |= BASE_VISIBLE_RENDER; } } @@ -377,7 +364,7 @@ void BKE_collection_object_cache_free(Collection *collection) collection_object_cache_free(collection); } -Base *BKE_collection_or_layer_objects(Depsgraph *depsgraph, +Base *BKE_collection_or_layer_objects(const Depsgraph *depsgraph, const Scene *scene, const ViewLayer *view_layer, Collection *collection) @@ -623,7 +610,7 @@ static bool scene_collections_object_remove(Main *bmain, Scene *scene, Object *o { bool removed = false; - BKE_scene_remove_rigidbody_object(scene, ob); + BKE_scene_remove_rigidbody_object(bmain, scene, ob); FOREACH_SCENE_COLLECTION_BEGIN(scene, collection) { diff --git a/source/blender/blenkernel/intern/collision.c b/source/blender/blenkernel/intern/collision.c index b23b1b2dbed..38cb1a1de16 100644 --- a/source/blender/blenkernel/intern/collision.c +++ b/source/blender/blenkernel/intern/collision.c @@ -446,7 +446,7 @@ static CollPair* cloth_collision(ModifierData *md1, ModifierData *md2, float v1[3], v2[3], relativeVelocity[3]; // calc relative velocity - + // compute barycentric coordinates for both collision points collision_compute_barycentric ( collpair->pa, verts1[collpair->ap1].txold, @@ -489,14 +489,14 @@ static void add_collision_object(Object ***objs, unsigned int *numobj, unsigned /* only get objects with collision modifier */ if (((modifier_type == eModifierType_Collision) && ob->pd && ob->pd->deflect) || (modifier_type != eModifierType_Collision)) cmd= (CollisionModifierData *)modifiers_findByType(ob, modifier_type); - + if (cmd) { /* extend array */ if (*numobj >= *maxobj) { *maxobj *= 2; *objs= MEM_reallocN(*objs, sizeof(Object *)*(*maxobj)); } - + (*objs)[*numobj] = ob; (*numobj)++; } @@ -515,13 +515,13 @@ static void add_collision_object(Object ***objs, unsigned int *numobj, unsigned } // return all collision objects in scene -// collision object will exclude self +// collision object will exclude self Object **get_collisionobjects_ext(Scene *scene, Object *self, Collection *collection, unsigned int *numcollobj, unsigned int modifier_type, bool dupli) { Object **objs; unsigned int numobj= 0, maxobj= 100; int level = dupli ? 0 : 1; - + objs= MEM_callocN(sizeof(Object *)*maxobj, "CollisionObjectsArray"); /* gather all collision objects */ @@ -566,7 +566,7 @@ static void add_collider_cache_object(ListBase **objs, Object *ob, Object *self, if (ob->pd && ob->pd->deflect) cmd =(CollisionModifierData *)modifiers_findByType(ob, eModifierType_Collision); - + if (cmd && cmd->bvhtree) { if (*objs == NULL) *objs = MEM_callocN(sizeof(ListBase), "ColliderCache array"); @@ -595,7 +595,7 @@ static void add_collider_cache_object(ListBase **objs, Object *ob, Object *self, ListBase *get_collider_cache(Scene *scene, Object *self, Collection *collection) { ListBase *objs= NULL; - + /* add object in same layer in scene */ if (collection) { FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(collection, object) @@ -633,7 +633,7 @@ static void cloth_bvh_objcollisions_nearcheck ( ClothModifierData * clmd, Collis CollPair **collisions, CollPair **collisions_index, int numresult, BVHTreeOverlap *overlap, double dt) { int i; - + *collisions = (CollPair *) MEM_mallocN(sizeof(CollPair) * numresult * 4, "collision array" ); // * 4 since cloth_collision_static can return more than 1 collision *collisions_index = *collisions; @@ -650,10 +650,10 @@ static int cloth_bvh_objcollisions_resolve ( ClothModifierData * clmd, Collision ClothVertex *verts = NULL; int ret = 0; int result = 0; - + mvert_num = clmd->clothObject->mvert_num; verts = cloth->verts; - + // process all collisions (calculate impulses, TODO: also repulses if distance too short) result = 1; for ( j = 0; j < 2; j++ ) { /* 5 is just a value that ensures convergence */ @@ -699,7 +699,7 @@ int cloth_bvh_objcollision(Object *ob, ClothModifierData *clmd, float step, floa if ((clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_COLLOBJ) || cloth_bvh==NULL) return 0; - + verts = cloth->verts; /* numfaces = cloth->numfaces; */ /* UNUSED */ mvert_num = cloth->mvert_num; @@ -711,9 +711,9 @@ int cloth_bvh_objcollision(Object *ob, ClothModifierData *clmd, float step, floa // update cloth bvh bvhtree_update_from_cloth ( clmd, 1 ); // 0 means STATIC, 1 means MOVING (see later in this function) bvhselftree_update_from_cloth ( clmd, 0 ); // 0 means STATIC, 1 means MOVING (see later in this function) - + collobjs = get_collisionobjects(clmd->scene, ob, clmd->coll_parms->group, &numcollobj, eModifierType_Collision); - + if (!collobjs) return 0; @@ -731,31 +731,31 @@ int cloth_bvh_objcollision(Object *ob, ClothModifierData *clmd, float step, floa do { CollPair **collisions, **collisions_index; - + ret2 = 0; collisions = MEM_callocN(sizeof(CollPair *) *numcollobj, "CollPair"); collisions_index = MEM_callocN(sizeof(CollPair *) *numcollobj, "CollPair"); - + // check all collision objects for (i = 0; i < numcollobj; i++) { Object *collob= collobjs[i]; CollisionModifierData *collmd = (CollisionModifierData *)modifiers_findByType(collob, eModifierType_Collision); BVHTreeOverlap *overlap = NULL; unsigned int result = 0; - + if (!collmd->bvhtree) continue; - + /* search for overlapping collision pairs */ overlap = BLI_bvhtree_overlap(cloth_bvh, collmd->bvhtree, &result, NULL, NULL); - + // go to next object if no overlap is there if ( result && overlap ) { /* check if collisions really happen (costly near check) */ - cloth_bvh_objcollisions_nearcheck ( clmd, collmd, &collisions[i], + cloth_bvh_objcollisions_nearcheck ( clmd, collmd, &collisions[i], &collisions_index[i], result, overlap, dt/(float)clmd->coll_parms->loop_count); - + // resolve nearby collisions ret += cloth_bvh_objcollisions_resolve ( clmd, collmd, collisions[i], collisions_index[i]); ret2 += ret; @@ -765,11 +765,11 @@ int cloth_bvh_objcollision(Object *ob, ClothModifierData *clmd, float step, floa MEM_freeN ( overlap ); } rounds++; - + for (i = 0; i < numcollobj; i++) { if ( collisions[i] ) MEM_freeN ( collisions[i] ); } - + MEM_freeN(collisions); MEM_freeN(collisions_index); @@ -789,8 +789,8 @@ int cloth_bvh_objcollision(Object *ob, ClothModifierData *clmd, float step, floa VECADD ( verts[i].tx, verts[i].txold, verts[i].tv ); } //////////////////////////////////////////////////////////// - - + + //////////////////////////////////////////////////////////// // Test on *simple* selfcollisions //////////////////////////////////////////////////////////// @@ -799,15 +799,15 @@ int cloth_bvh_objcollision(Object *ob, ClothModifierData *clmd, float step, floa /* TODO: add coll quality rounds again */ BVHTreeOverlap *overlap = NULL; unsigned int result = 0; - + // collisions = 1; verts = cloth->verts; // needed for openMP - + /* numfaces = cloth->numfaces; */ /* UNUSED */ mvert_num = cloth->mvert_num; - + verts = cloth->verts; - + if ( cloth->bvhselftree ) { // search for overlapping collision pairs overlap = BLI_bvhtree_overlap(cloth->bvhselftree, cloth->bvhselftree, &result, NULL, NULL); @@ -817,12 +817,12 @@ int cloth_bvh_objcollision(Object *ob, ClothModifierData *clmd, float step, floa float temp[3]; float length = 0; float mindistance; - + i = overlap[k].indexA; j = overlap[k].indexB; - + mindistance = clmd->coll_parms->selfepsilon* ( cloth->verts[i].avg_spring_len + cloth->verts[j].avg_spring_len ); - + if ( clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL ) { if ( ( cloth->verts [i].flags & CLOTH_VERT_FLAG_PINNED ) && ( cloth->verts [j].flags & CLOTH_VERT_FLAG_PINNED ) ) @@ -836,20 +836,20 @@ int cloth_bvh_objcollision(Object *ob, ClothModifierData *clmd, float step, floa { continue; } - + sub_v3_v3v3(temp, verts[i].tx, verts[j].tx); - + if ( ( ABS ( temp[0] ) > mindistance ) || ( ABS ( temp[1] ) > mindistance ) || ( ABS ( temp[2] ) > mindistance ) ) continue; - + if (BLI_edgeset_haskey(cloth->edgeset, i, j)) { continue; } - + length = normalize_v3(temp ); - + if ( length < mindistance ) { float correction = mindistance - length; - + if ( cloth->verts [i].flags & CLOTH_VERT_FLAG_PINNED ) { mul_v3_fl(temp, -correction); VECADD ( verts[j].tx, verts[j].tx, temp ); @@ -861,7 +861,7 @@ int cloth_bvh_objcollision(Object *ob, ClothModifierData *clmd, float step, floa else { mul_v3_fl(temp, correction * -0.5f); VECADD ( verts[j].tx, verts[j].tx, temp ); - + sub_v3_v3v3(verts[i].tx, verts[i].tx, temp); } ret = 1; @@ -871,10 +871,10 @@ int cloth_bvh_objcollision(Object *ob, ClothModifierData *clmd, float step, floa // check for approximated time collisions } } - + if ( overlap ) MEM_freeN ( overlap ); - + } } //////////////////////////////////////////////////////////// @@ -893,7 +893,7 @@ int cloth_bvh_objcollision(Object *ob, ClothModifierData *clmd, float step, floa } } while ( ret2 && ( clmd->coll_parms->loop_count>rounds ) ); - + if (collobjs) MEM_freeN(collobjs); @@ -910,14 +910,14 @@ BLI_INLINE void max_v3_v3v3(float r[3], const float a[3], const float b[3]) void collision_get_collider_velocity(float vel_old[3], float vel_new[3], CollisionModifierData *collmd, CollPair *collpair) { float u1, u2, u3; - + /* compute barycentric coordinates */ collision_compute_barycentric(collpair->pb, collmd->current_x[collpair->bp1].co, collmd->current_x[collpair->bp2].co, collmd->current_x[collpair->bp3].co, &u1, &u2, &u3); - + collision_interpolateOnTriangle(vel_new, collmd->current_v[collpair->bp1].co, collmd->current_v[collpair->bp2].co, collmd->current_v[collpair->bp3].co, u1, u2, u3); /* XXX assume constant velocity of the collider for now */ copy_v3_v3(vel_old, vel_new); @@ -930,7 +930,7 @@ static bool cloth_points_collision_response_static(ClothModifierData *clmd, Coll float restitution = (1.0f - clmd->coll_parms->damping) * (1.0f - pd->pdef_sbdamp); float inv_dt = 1.0f / dt; Cloth *cloth1 = clmd->clothObject; - + // float w1, w2; float u1, u2, u3; float v1[3], v2_old[3], v2_new[3], v_rel_old[3], v_rel_new[3]; @@ -984,20 +984,20 @@ static bool cloth_points_collision_response_static(ClothModifierData *clmd, Coll float v_nor_old, v_nor_new; float v_tan_old[3], v_tan_new[3]; float bounce, repulse; - + /* Collision response based on * "Simulating Complex Hair with Robust Collision Handling" (Choe, Choi, Ko, ACM SIGGRAPH 2005) * http://graphics.snu.ac.kr/publications/2005-choe-HairSim/Choe_2005_SCA.pdf */ - + v_nor_old = mag_v_rel; v_nor_new = dot_v3v3(v_rel_new, collpair->normal); - + madd_v3_v3v3fl(v_tan_old, v_rel_old, collpair->normal, -v_nor_old); madd_v3_v3v3fl(v_tan_new, v_rel_new, collpair->normal, -v_nor_new); - + repulse = -margin_distance * inv_dt + dot_v3v3(v1, collpair->normal); - + if (margin_distance < -epsilon2) { bounce = -v_nor_new + v_nor_old * restitution; mul_v3_v3fl(impulse, collpair->normal, max_ff(repulse, bounce)); @@ -1007,10 +1007,10 @@ static bool cloth_points_collision_response_static(ClothModifierData *clmd, Coll mul_v3_v3fl(impulse, collpair->normal, repulse); } cloth1->verts[collpair->ap1].impulse_count++; - + result = true; } - + if (result) { int i = 0; @@ -1028,21 +1028,21 @@ BLI_INLINE bool cloth_point_face_collision_params(const float p1[3], const float { float edge1[3], edge2[3], p2face[3], p1p2[3], v0p2[3]; float nor_v0p2, nor_p1p2; - + sub_v3_v3v3(edge1, v1, v0); sub_v3_v3v3(edge2, v2, v0); cross_v3_v3v3(r_nor, edge1, edge2); normalize_v3(r_nor); - + nor_v0p2 = dot_v3v3(v0p2, r_nor); madd_v3_v3v3fl(p2face, p2, r_nor, -nor_v0p2); interp_weights_tri_v3(r_w, v0, v1, v2, p2face); - + sub_v3_v3v3(p1p2, p2, p1); sub_v3_v3v3(v0p2, p2, v0); nor_p1p2 = dot_v3v3(p1p2, r_nor); *r_lambda = (nor_p1p2 != 0.0f ? nor_v0p2 / nor_p1p2 : 0.0f); - + return r_w[1] >= 0.0f && r_w[2] >= 0.0f && r_w[1] + r_w[2] <= 1.0f; #if 0 /* XXX this method uses the intersection point, but is broken and doesn't work well in general */ @@ -1099,7 +1099,7 @@ static CollPair *cloth_point_collpair( if (!cloth_point_face_collision_params(p1, p2, co1, co2, co3, facenor, &lambda, w)) return collpair; - + sub_v3_v3v3(v1p1, p1, co1); // distance1 = dot_v3v3(v1p1, facenor); sub_v3_v3v3(v1p2, p2, co1); @@ -1107,7 +1107,7 @@ static CollPair *cloth_point_collpair( // if (distance2 > epsilon || (distance1 < 0.0f && distance2 < 0.0f)) if (distance2 > epsilon) return collpair; - + collpair->face1 = index_cloth; /* XXX actually not a face, but equivalent index for point */ collpair->face2 = index_coll; collpair->ap1 = index_cloth; @@ -1115,20 +1115,20 @@ static CollPair *cloth_point_collpair( collpair->bp1 = bp1; collpair->bp2 = bp2; collpair->bp3 = bp3; - + /* note: using the second point here, which is * the current updated position that needs to be corrected */ copy_v3_v3(collpair->pa, p2); collpair->distance = distance2; mul_v3_v3fl(collpair->vector, facenor, -distance2); - + interp_v3_v3v3v3(collpair->pb, co1, co2, co3, w); - + copy_v3_v3(collpair->normal, facenor); collpair->time = lambda; collpair->flag = 0; - + collpair++; return collpair; } @@ -1163,7 +1163,7 @@ static void cloth_points_objcollisions_nearcheck( int numresult, BVHTreeOverlap *overlap, float epsilon, double dt) { int i; - + /* can return 2 collisions in total */ *collisions = (CollPair *) MEM_mallocN(sizeof(CollPair) * numresult * 2, "collision array" ); *collisions_index = *collisions; @@ -1182,11 +1182,11 @@ static int cloth_points_objcollisions_resolve( int i = 0, mvert_num = clmd->clothObject->mvert_num; ClothVertex *verts = cloth->verts; int ret = 0; - + // process all collisions if ( collmd->bvhtree ) { bool result = cloth_points_collision_response_static(clmd, collmd, pd, collisions, collisions_index, dt); - + // apply impulses in parallel if (result) { for (i = 0; i < mvert_num; i++) { @@ -1196,13 +1196,13 @@ static int cloth_points_objcollisions_resolve( VECADD ( verts[i].tv, verts[i].tv, verts[i].impulse); zero_v3(verts[i].impulse); verts[i].impulse_count = 0; - + ret++; } } } } - + return ret; } @@ -1218,32 +1218,32 @@ int cloth_points_objcollision(Object *ob, ClothModifierData *clmd, float step, f int ret = 0, ret2 = 0; Object **collobjs = NULL; unsigned int numcollobj = 0; - + verts = cloth->verts; mvert_num = cloth->mvert_num; - + //////////////////////////////////////////////////////////// // static collisions //////////////////////////////////////////////////////////// - + // create temporary cloth points bvh cloth_bvh = BLI_bvhtree_new(mvert_num, max_ff(clmd->coll_parms->epsilon, clmd->coll_parms->distance_repel), 4, 6); /* fill tree */ for (i = 0; i < mvert_num; i++) { float co[2][3]; - + copy_v3_v3(co[0], verts[i].x); copy_v3_v3(co[1], verts[i].tx); - + BLI_bvhtree_insert(cloth_bvh, i, co[0], 2); } /* balance tree */ BLI_bvhtree_balance(cloth_bvh); - + collobjs = get_collisionobjects(clmd->scene, ob, clmd->coll_parms->group, &numcollobj, eModifierType_Collision); if (!collobjs) return 0; - + /* move object to position (step) in time */ for (i = 0; i < numcollobj; i++) { Object *collob= collobjs[i]; @@ -1257,12 +1257,12 @@ int cloth_points_objcollision(Object *ob, ClothModifierData *clmd, float step, f do { CollPair **collisions, **collisions_index; - + ret2 = 0; - + collisions = MEM_callocN(sizeof(CollPair *) *numcollobj, "CollPair"); collisions_index = MEM_callocN(sizeof(CollPair *) *numcollobj, "CollPair"); - + // check all collision objects for (i = 0; i < numcollobj; i++) { Object *collob= collobjs[i]; @@ -1270,35 +1270,35 @@ int cloth_points_objcollision(Object *ob, ClothModifierData *clmd, float step, f BVHTreeOverlap *overlap = NULL; unsigned int result = 0; float epsilon; - + if (!collmd->bvhtree) continue; - + /* search for overlapping collision pairs */ overlap = BLI_bvhtree_overlap(cloth_bvh, collmd->bvhtree, &result, NULL, NULL); epsilon = BLI_bvhtree_get_epsilon(collmd->bvhtree); - + // go to next object if no overlap is there if (result && overlap) { /* check if collisions really happen (costly near check) */ cloth_points_objcollisions_nearcheck(clmd, collmd, &collisions[i], &collisions_index[i], result, overlap, epsilon, round_dt); - + // resolve nearby collisions ret += cloth_points_objcollisions_resolve(clmd, collmd, collob->pd, collisions[i], collisions_index[i], round_dt); ret2 += ret; } - + if (overlap) MEM_freeN ( overlap ); } rounds++; - + for (i = 0; i < numcollobj; i++) { if (collisions[i]) MEM_freeN(collisions[i]); } - + MEM_freeN(collisions); MEM_freeN(collisions_index); @@ -1320,7 +1320,7 @@ int cloth_points_objcollision(Object *ob, ClothModifierData *clmd, float step, f //////////////////////////////////////////////////////////// } while ( ret2 && ( clmd->coll_parms->loop_count>rounds ) ); - + if (collobjs) MEM_freeN(collobjs); @@ -1336,53 +1336,53 @@ void cloth_find_point_contacts(Object *ob, ClothModifierData *clmd, float step, BVHTree *cloth_bvh; unsigned int i = 0, mvert_num = 0; ClothVertex *verts = NULL; - + ColliderContacts *collider_contacts; - + Object **collobjs = NULL; unsigned int numcollobj = 0; - + verts = cloth->verts; mvert_num = cloth->mvert_num; - + //////////////////////////////////////////////////////////// // static collisions //////////////////////////////////////////////////////////// - + // create temporary cloth points bvh cloth_bvh = BLI_bvhtree_new(mvert_num, max_ff(clmd->coll_parms->epsilon, clmd->coll_parms->distance_repel), 4, 6); /* fill tree */ for (i = 0; i < mvert_num; i++) { float co[6]; - + copy_v3_v3(&co[0*3], verts[i].x); copy_v3_v3(&co[1*3], verts[i].tx); - + BLI_bvhtree_insert(cloth_bvh, i, co, 2); } /* balance tree */ BLI_bvhtree_balance(cloth_bvh); - + collobjs = get_collisionobjects(clmd->scene, ob, clmd->coll_parms->group, &numcollobj, eModifierType_Collision); if (!collobjs) { *r_collider_contacts = NULL; *r_totcolliders = 0; return; } - + /* move object to position (step) in time */ for (i = 0; i < numcollobj; i++) { Object *collob= collobjs[i]; CollisionModifierData *collmd = (CollisionModifierData *)modifiers_findByType(collob, eModifierType_Collision); if (!collmd->bvhtree) continue; - + /* move object to position (step) in time */ collision_move_object ( collmd, step + dt, step ); } - + collider_contacts = MEM_callocN(sizeof(ColliderContacts) * numcollobj, "CollPair"); - + // check all collision objects for (i = 0; i < numcollobj; i++) { ColliderContacts *ct = collider_contacts + i; @@ -1391,46 +1391,46 @@ void cloth_find_point_contacts(Object *ob, ClothModifierData *clmd, float step, BVHTreeOverlap *overlap; unsigned int result = 0; float epsilon; - + ct->ob = collob; ct->collmd = collmd; ct->collisions = NULL; ct->totcollisions = 0; - + if (!collmd->bvhtree) continue; - + /* search for overlapping collision pairs */ overlap = BLI_bvhtree_overlap(cloth_bvh, collmd->bvhtree, &result, NULL, NULL); epsilon = BLI_bvhtree_get_epsilon(collmd->bvhtree); - + // go to next object if no overlap is there if (result && overlap) { CollPair *collisions_index; - + /* check if collisions really happen (costly near check) */ cloth_points_objcollisions_nearcheck(clmd, collmd, &ct->collisions, &collisions_index, result, overlap, epsilon, dt); ct->totcollisions = (int)(collisions_index - ct->collisions); - + // resolve nearby collisions // ret += cloth_points_objcollisions_resolve(clmd, collmd, collob->pd, collisions[i], collisions_index[i], dt); } - + if (overlap) MEM_freeN(overlap); } - + if (collobjs) MEM_freeN(collobjs); BLI_bvhtree_free(cloth_bvh); - + //////////////////////////////////////////////////////////// // update positions // this is needed for bvh_calc_DOP_hull_moving() [kdop.c] //////////////////////////////////////////////////////////// - + // verts come from clmd for (i = 0; i < mvert_num; i++) { if (clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL) { @@ -1438,11 +1438,11 @@ void cloth_find_point_contacts(Object *ob, ClothModifierData *clmd, float step, continue; } } - + VECADD(verts[i].tx, verts[i].txold, verts[i].tv); } //////////////////////////////////////////////////////////// - + *r_collider_contacts = collider_contacts; *r_totcolliders = numcollobj; } diff --git a/source/blender/blenkernel/intern/colortools.c b/source/blender/blenkernel/intern/colortools.c index 6c97380b9ca..ff4795afe87 100644 --- a/source/blender/blenkernel/intern/colortools.c +++ b/source/blender/blenkernel/intern/colortools.c @@ -62,21 +62,21 @@ void curvemapping_set_defaults(CurveMapping *cumap, int tot, float minx, float m { int a; float clipminx, clipminy, clipmaxx, clipmaxy; - + cumap->flag = CUMA_DO_CLIP; if (tot == 4) cumap->cur = 3; /* rhms, hack for 'col' curve? */ - + clipminx = min_ff(minx, maxx); clipminy = min_ff(miny, maxy); clipmaxx = max_ff(minx, maxx); clipmaxy = max_ff(miny, maxy); - + BLI_rctf_init(&cumap->curr, clipminx, clipmaxx, clipminy, clipmaxy); cumap->clipr = cumap->curr; - + cumap->white[0] = cumap->white[1] = cumap->white[2] = 1.0f; cumap->bwmul[0] = cumap->bwmul[1] = cumap->bwmul[2] = 1.0f; - + for (a = 0; a < tot; a++) { cumap->cm[a].flag = CUMA_EXTEND_EXTRAPOLATE; cumap->cm[a].totpoint = 2; @@ -187,7 +187,7 @@ bool curvemap_remove_point(CurveMap *cuma, CurveMapPoint *point) { CurveMapPoint *cmp; int a, b, removed = 0; - + /* must have 2 points minimum */ if (cuma->totpoint <= 2) return false; @@ -204,7 +204,7 @@ bool curvemap_remove_point(CurveMap *cuma, CurveMapPoint *point) removed++; } } - + MEM_freeN(cuma->curve); cuma->curve = cmp; cuma->totpoint -= removed; @@ -216,7 +216,7 @@ void curvemap_remove(CurveMap *cuma, const short flag) { CurveMapPoint *cmp = MEM_mallocN((cuma->totpoint) * sizeof(CurveMapPoint), "curve points"); int a, b, removed = 0; - + /* well, lets keep the two outer points! */ cmp[0] = cuma->curve[0]; for (a = 1, b = 1; a < cuma->totpoint - 1; a++) { @@ -229,7 +229,7 @@ void curvemap_remove(CurveMap *cuma, const short flag) } } cmp[b] = cuma->curve[a]; - + MEM_freeN(cuma->curve); cuma->curve = cmp; cuma->totpoint -= removed; @@ -359,11 +359,11 @@ void curvemap_reset(CurveMap *cuma, const rctf *clipr, int preset, int slope) if (slope == CURVEMAP_SLOPE_POSITIVE) { int i, last = cuma->totpoint - 1; CurveMapPoint *newpoints = MEM_dupallocN(cuma->curve); - + for (i = 0; i < cuma->totpoint; i++) { newpoints[i].y = cuma->curve[last - i].y; } - + MEM_freeN(cuma->curve); cuma->curve = newpoints; } @@ -397,7 +397,7 @@ void curvemap_reset(CurveMap *cuma, const rctf *clipr, int preset, int slope) void curvemap_handle_set(CurveMap *cuma, int type) { int a; - + for (a = 0; a < cuma->totpoint; a++) { if (cuma->curve[a].flag & CUMA_SELECT) { cuma->curve[a].flag &= ~(CUMA_HANDLE_VECTOR | CUMA_HANDLE_AUTO_ANIM); @@ -435,9 +435,9 @@ static void calchandle_curvemap( if (bezt->h1 == 0 && bezt->h2 == 0) { return; } - + p2 = bezt->vec[1]; - + if (prev == NULL) { p3 = next->vec[1]; pt[0] = 2.0f * p2[0] - p3[0]; @@ -447,7 +447,7 @@ static void calchandle_curvemap( else { p1 = prev->vec[1]; } - + if (next == NULL) { p1 = prev->vec[1]; pt[0] = 2.0f * p2[0] - p1[0]; @@ -474,7 +474,7 @@ static void calchandle_curvemap( len = len_v2(tvec) * 2.5614f; if (len != 0.0f) { - + if (ELEM(bezt->h1, HD_AUTO, HD_AUTO_ANIM)) { len_a /= len; madd_v2_v2v2fl(p2_h1, p2, tvec, -len_a); @@ -541,7 +541,7 @@ static void calchandle_curvemap( #undef p2_h2 } -/* in X, out Y. +/* in X, out Y. * X is presumed to be outside first or last */ static float curvemap_calc_extend(const CurveMap *cuma, float x, const float first[2], const float last[2]) { @@ -579,16 +579,16 @@ static void curvemap_make_table(CurveMap *cuma, const rctf *clipr) BezTriple *bezt; float *fp, *allpoints, *lastpoint, curf, range; int a, totpoint; - + if (cuma->curve == NULL) return; - + /* default rect also is table range */ cuma->mintable = clipr->xmin; cuma->maxtable = clipr->xmax; - + /* hrmf... we now rely on blender ipo beziers, these are more advanced */ bezt = MEM_callocN(cuma->totpoint * sizeof(BezTriple), "beztarr"); - + for (a = 0; a < cuma->totpoint; a++) { cuma->mintable = min_ff(cuma->mintable, cmp[a].x); cuma->maxtable = max_ff(cuma->maxtable, cmp[a].x); @@ -604,27 +604,27 @@ static void curvemap_make_table(CurveMap *cuma, const rctf *clipr) bezt[a].h1 = bezt[a].h2 = HD_AUTO; } } - + const BezTriple *bezt_prev = NULL; for (a = 0; a < cuma->totpoint; a++) { const BezTriple *bezt_next = (a != cuma->totpoint - 1) ? &bezt[a + 1] : NULL; calchandle_curvemap(&bezt[a], bezt_prev, bezt_next); bezt_prev = &bezt[a]; } - - /* first and last handle need correction, instead of pointing to center of next/prev, + + /* first and last handle need correction, instead of pointing to center of next/prev, * we let it point to the closest handle */ if (cuma->totpoint > 2) { float hlen, nlen, vec[3]; - + if (bezt[0].h2 == HD_AUTO) { - + hlen = len_v3v3(bezt[0].vec[1], bezt[0].vec[2]); /* original handle length */ /* clip handle point */ copy_v3_v3(vec, bezt[1].vec[0]); if (vec[0] < bezt[0].vec[1][0]) vec[0] = bezt[0].vec[1][0]; - + sub_v3_v3(vec, bezt[0].vec[1]); nlen = len_v3(vec); if (nlen > FLT_EPSILON) { @@ -635,13 +635,13 @@ static void curvemap_make_table(CurveMap *cuma, const rctf *clipr) } a = cuma->totpoint - 1; if (bezt[a].h2 == HD_AUTO) { - + hlen = len_v3v3(bezt[a].vec[1], bezt[a].vec[0]); /* original handle length */ /* clip handle point */ copy_v3_v3(vec, bezt[a - 1].vec[2]); if (vec[0] > bezt[a].vec[1][0]) vec[0] = bezt[a].vec[1][0]; - + sub_v3_v3(vec, bezt[a].vec[1]); nlen = len_v3(vec); if (nlen > FLT_EPSILON) { @@ -656,13 +656,13 @@ static void curvemap_make_table(CurveMap *cuma, const rctf *clipr) MEM_freeN(cuma->table); totpoint = (cuma->totpoint - 1) * CM_RESOL; fp = allpoints = MEM_callocN(totpoint * 2 * sizeof(float), "table"); - + for (a = 0; a < cuma->totpoint - 1; a++, fp += 2 * CM_RESOL) { correct_bezpart(bezt[a].vec[1], bezt[a].vec[2], bezt[a + 1].vec[0], bezt[a + 1].vec[1]); BKE_curve_forward_diff_bezier(bezt[a].vec[1][0], bezt[a].vec[2][0], bezt[a + 1].vec[0][0], bezt[a + 1].vec[1][0], fp, CM_RESOL - 1, 2 * sizeof(float)); BKE_curve_forward_diff_bezier(bezt[a].vec[1][1], bezt[a].vec[2][1], bezt[a + 1].vec[0][1], bezt[a + 1].vec[1][1], fp + 1, CM_RESOL - 1, 2 * sizeof(float)); } - + /* store first and last handle for extrapolation, unit length */ cuma->ext_in[0] = bezt[0].vec[0][0] - bezt[0].vec[1][0]; cuma->ext_in[1] = bezt[0].vec[0][1] - bezt[0].vec[1][1]; @@ -676,13 +676,13 @@ static void curvemap_make_table(CurveMap *cuma, const rctf *clipr) range = sqrtf(cuma->ext_out[0] * cuma->ext_out[0] + cuma->ext_out[1] * cuma->ext_out[1]); cuma->ext_out[0] /= range; cuma->ext_out[1] /= range; - + /* cleanup */ MEM_freeN(bezt); range = CM_TABLEDIV * (cuma->maxtable - cuma->mintable); cuma->range = 1.0f / range; - + /* now make a table with CM_TABLE equal x distances */ fp = allpoints; lastpoint = allpoints + 2 * (totpoint - 1); @@ -691,7 +691,7 @@ static void curvemap_make_table(CurveMap *cuma, const rctf *clipr) for (a = 0; a <= CM_TABLE; a++) { curf = cuma->mintable + range * (float)a; cmp[a].x = curf; - + /* get the first x coordinate larger than curf */ while (curf >= fp[0] && fp != lastpoint) { fp += 2; @@ -708,7 +708,7 @@ static void curvemap_make_table(CurveMap *cuma, const rctf *clipr) cmp[a].y = fac1 * fp[-1] + (1.0f - fac1) * fp[1]; } } - + MEM_freeN(allpoints); cuma->table = cmp; } @@ -718,7 +718,7 @@ static void curvemap_make_table(CurveMap *cuma, const rctf *clipr) void curvemapping_premultiply(CurveMapping *cumap, int restore) { int a; - + if (restore) { if (cumap->flag & CUMA_PREMULLED) { for (a = 0; a < 3; a++) { @@ -731,7 +731,7 @@ void curvemapping_premultiply(CurveMapping *cumap, int restore) zero_v2(cumap->cm[a].premul_ext_in); zero_v2(cumap->cm[a].premul_ext_out); } - + cumap->flag &= ~CUMA_PREMULLED; } } @@ -745,10 +745,10 @@ void curvemapping_premultiply(CurveMapping *cumap, int restore) cumap->cm[a].table = MEM_mallocN((CM_TABLE + 1) * sizeof(CurveMapPoint), "premul table"); memcpy(cumap->cm[a].table, cumap->cm[a].premultable, (CM_TABLE + 1) * sizeof(CurveMapPoint)); } - + if (cumap->cm[3].table == NULL) curvemap_make_table(cumap->cm + 3, &cumap->clipr); - + /* premul */ for (a = 0; a < 3; a++) { int b; @@ -761,7 +761,7 @@ void curvemapping_premultiply(CurveMapping *cumap, int restore) mul_v2_v2(cumap->cm[a].ext_in, cumap->cm[3].ext_in); mul_v2_v2(cumap->cm[a].ext_out, cumap->cm[3].ext_out); } - + cumap->flag |= CUMA_PREMULLED; } } @@ -770,7 +770,7 @@ void curvemapping_premultiply(CurveMapping *cumap, int restore) static int sort_curvepoints(const void *a1, const void *a2) { const struct CurveMapPoint *x1 = a1, *x2 = a2; - + if (x1->x > x2->x) return 1; else if (x1->x < x2->x) return -1; return 0; @@ -821,10 +821,10 @@ void curvemapping_changed(CurveMapping *cumap, const bool rem_doubles) cumap->curr.ymax = cumap->clipr.ymax; } } - - + + qsort(cmp, cuma->totpoint, sizeof(CurveMapPoint), sort_curvepoints); - + /* remove doubles, threshold set on 1% of default range */ if (rem_doubles && cuma->totpoint > 2) { for (a = 0; a < cuma->totpoint - 1; a++) { @@ -873,14 +873,14 @@ float curvemap_evaluateF(const CurveMap *cuma, float value) /* index in table */ fi = (value - cuma->mintable) * cuma->range; i = (int)fi; - + /* fi is table float index and should check against table range i.e. [0.0 CM_TABLE] */ if (fi < 0.0f || fi > CM_TABLE) return curvemap_calc_extend(cuma, value, &cuma->table[0].x, &cuma->table[CM_TABLE].x); else { if (i < 0) return cuma->table[0].y; if (i >= CM_TABLE) return cuma->table[CM_TABLE].y; - + fi = fi - (float)i; return (1.0f - fi) * cuma->table[i].y + (fi) * cuma->table[i + 1].y; } @@ -963,18 +963,18 @@ void curvemapping_evaluate_premulRGB(const CurveMapping *cumap, unsigned char ve int curvemapping_RGBA_does_something(const CurveMapping *cumap) { int a; - + if (cumap->black[0] != 0.0f) return 1; if (cumap->black[1] != 0.0f) return 1; if (cumap->black[2] != 0.0f) return 1; if (cumap->white[0] != 1.0f) return 1; if (cumap->white[1] != 1.0f) return 1; if (cumap->white[2] != 1.0f) return 1; - + for (a = 0; a < CM_TOT; a++) { if (cumap->cm[a].curve) { if (cumap->cm[a].totpoint != 2) return 1; - + if (cumap->cm[a].curve[0].x != 0.0f) return 1; if (cumap->cm[a].curve[0].y != 0.0f) return 1; if (cumap->cm[a].curve[1].x != 1.0f) return 1; @@ -987,9 +987,9 @@ int curvemapping_RGBA_does_something(const CurveMapping *cumap) void curvemapping_initialize(CurveMapping *cumap) { int a; - + if (cumap == NULL) return; - + for (a = 0; a < CM_TOT; a++) { if (cumap->cm[a].table == NULL) curvemap_make_table(cumap->cm + a, &cumap->clipr); @@ -999,7 +999,7 @@ void curvemapping_initialize(CurveMapping *cumap) void curvemapping_table_RGBA(const CurveMapping *cumap, float **array, int *size) { int a; - + *size = CM_TABLE + 1; *array = MEM_callocN(sizeof(float) * (*size) * 4, "CurveMapping"); @@ -1165,7 +1165,7 @@ typedef struct ScopesUpdateDataChunk { float min[3], max[3]; } ScopesUpdateDataChunk; -static void scopes_update_cb(void *__restrict userdata, +static void scopes_update_cb(void *__restrict userdata, const int y, const ParallelRangeTLS *__restrict tls) { @@ -1347,7 +1347,7 @@ void scopes_update(Scopes *scopes, ImBuf *ibuf, const ColorManagedViewSettings * /* convert to number of lines with logarithmic scale */ scopes->sample_lines = (scopes->accuracy * 0.01f) * (scopes->accuracy * 0.01f) * ibuf->y; CLAMP_MIN(scopes->sample_lines, 1); - + if (scopes->sample_full) scopes->sample_lines = ibuf->y; @@ -1356,9 +1356,9 @@ void scopes_update(Scopes *scopes, ImBuf *ibuf, const ColorManagedViewSettings * scopes->minmax[a][0] = 25500.0f; scopes->minmax[a][1] = -25500.0f; } - + scopes->waveform_tot = ibuf->x * scopes->sample_lines; - + if (scopes->waveform_1) MEM_freeN(scopes->waveform_1); if (scopes->waveform_2) @@ -1367,12 +1367,12 @@ void scopes_update(Scopes *scopes, ImBuf *ibuf, const ColorManagedViewSettings * MEM_freeN(scopes->waveform_3); if (scopes->vecscope) MEM_freeN(scopes->vecscope); - + scopes->waveform_1 = MEM_callocN(scopes->waveform_tot * 2 * sizeof(float), "waveform point channel 1"); scopes->waveform_2 = MEM_callocN(scopes->waveform_tot * 2 * sizeof(float), "waveform point channel 2"); scopes->waveform_3 = MEM_callocN(scopes->waveform_tot * 2 * sizeof(float), "waveform point channel 3"); scopes->vecscope = MEM_callocN(scopes->waveform_tot * 2 * sizeof(float), "vectorscope point channel"); - + if (ibuf->rect_float) { cm_processor = IMB_colormanagement_display_processor_new(view_settings, display_settings); } @@ -1411,7 +1411,7 @@ void scopes_update(Scopes *scopes, ImBuf *ibuf, const ColorManagedViewSettings * bin_a[a] = sqrt(bin_a[a]); } #endif - + /* convert hist data to float (proportional to max count) */ nl = na = nr = nb = ng = 0; for (a = 0; a < 256; a++) { @@ -1426,7 +1426,7 @@ void scopes_update(Scopes *scopes, ImBuf *ibuf, const ColorManagedViewSettings * divr = nr ? 1.0 / (double)nr : 1.0; divg = ng ? 1.0 / (double)ng : 1.0; divb = nb ? 1.0 / (double)nb : 1.0; - + for (a = 0; a < 256; a++) { scopes->hist.data_luma[a] = bin_lum[a] * divl; scopes->hist.data_r[a] = bin_r[a] * divr; @@ -1439,7 +1439,7 @@ void scopes_update(Scopes *scopes, ImBuf *ibuf, const ColorManagedViewSettings * IMB_colormanagement_processor_free(cm_processor); if (cache_handle) IMB_display_buffer_release(cache_handle); - + scopes->ok = 1; } diff --git a/source/blender/blenkernel/intern/constraint.c b/source/blender/blenkernel/intern/constraint.c index fe60d53a9a2..ac47a9e0756 100644 --- a/source/blender/blenkernel/intern/constraint.c +++ b/source/blender/blenkernel/intern/constraint.c @@ -30,7 +30,7 @@ */ -#include <stdio.h> +#include <stdio.h> #include <stddef.h> #include <string.h> #include <math.h> @@ -122,14 +122,14 @@ void BKE_constraint_unique_name(bConstraint *con, ListBase *list) bConstraintOb *BKE_constraints_make_evalob(Depsgraph *depsgraph, Scene *scene, Object *ob, void *subdata, short datatype) { bConstraintOb *cob; - + /* create regardless of whether we have any data! */ cob = MEM_callocN(sizeof(bConstraintOb), "bConstraintOb"); - + /* for system time, part of deglobalization, code nicer later with local time (ton) */ cob->scene = scene; cob->depsgraph = depsgraph; - + /* based on type of available data */ switch (datatype) { case CONSTRAINT_OBTYPE_OBJECT: @@ -138,7 +138,7 @@ bConstraintOb *BKE_constraints_make_evalob(Depsgraph *depsgraph, Scene *scene, O if (ob) { cob->ob = ob; cob->type = datatype; - + if (cob->ob->rotmode > 0) { /* Should be some kind of Euler order, so use it */ /* NOTE: Versions <= 2.76 assumed that "default" order @@ -156,7 +156,7 @@ bConstraintOb *BKE_constraints_make_evalob(Depsgraph *depsgraph, Scene *scene, O } else unit_m4(cob->matrix); - + copy_m4_m4(cob->startmat, cob->matrix); break; } @@ -167,7 +167,7 @@ bConstraintOb *BKE_constraints_make_evalob(Depsgraph *depsgraph, Scene *scene, O cob->ob = ob; cob->pchan = (bPoseChannel *)subdata; cob->type = datatype; - + if (cob->pchan->rotmode > 0) { /* should be some type of Euler order */ cob->rotOrder = cob->pchan->rotmode; @@ -176,13 +176,13 @@ bConstraintOb *BKE_constraints_make_evalob(Depsgraph *depsgraph, Scene *scene, O /* Quats, so eulers should just use default order */ cob->rotOrder = EULER_ORDER_DEFAULT; } - + /* matrix in world-space */ mul_m4_m4m4(cob->matrix, ob->obmat, cob->pchan->pose_mat); } else unit_m4(cob->matrix); - + copy_m4_m4(cob->startmat, cob->matrix); break; } @@ -199,11 +199,11 @@ bConstraintOb *BKE_constraints_make_evalob(Depsgraph *depsgraph, Scene *scene, O void BKE_constraints_clear_evalob(bConstraintOb *cob) { float delta[4][4], imat[4][4]; - + /* prevent crashes */ - if (cob == NULL) + if (cob == NULL) return; - + /* calculate delta of constraints evaluation */ invert_m4_m4(imat, cob->startmat); /* XXX This would seem to be in wrong order. However, it does not work in 'right' order - would be nice to @@ -211,7 +211,7 @@ void BKE_constraints_clear_evalob(bConstraintOb *cob) * In any case, we **do not get a delta** here (e.g. startmat & matrix having same location, still gives * a 'delta' with non-null translation component :/ ).*/ mul_m4_m4m4(delta, cob->matrix, imat); - + /* copy matrices back to source */ switch (cob->type) { case CONSTRAINT_OBTYPE_OBJECT: @@ -220,7 +220,7 @@ void BKE_constraints_clear_evalob(bConstraintOb *cob) if (cob->ob) { /* copy new ob-matrix back to owner */ copy_m4_m4(cob->ob->obmat, cob->matrix); - + /* copy inverse of delta back to owner */ invert_m4_m4(cob->ob->constinv, delta); } @@ -232,21 +232,21 @@ void BKE_constraints_clear_evalob(bConstraintOb *cob) if (cob->ob && cob->pchan) { /* copy new pose-matrix back to owner */ mul_m4_m4m4(cob->pchan->pose_mat, cob->ob->imat, cob->matrix); - + /* copy inverse of delta back to owner */ invert_m4_m4(cob->pchan->constinv, delta); } break; } } - + /* free tempolary struct */ MEM_freeN(cob); } /* -------------- Space-Conversion API -------------- */ -/* This function is responsible for the correct transformations/conversions +/* This function is responsible for the correct transformations/conversions * of a matrix from one space to another for constraint evaluation. * For now, this is only implemented for Objects and PoseChannels. */ @@ -255,12 +255,12 @@ void BKE_constraint_mat_convertspace( { float diff_mat[4][4]; float imat[4][4]; - + /* prevent crashes in these unlikely events */ if (ob == NULL || mat == NULL) return; /* optimize trick - check if need to do anything */ if (from == to) return; - + /* are we dealing with pose-channels or objects */ if (pchan) { /* pose channels */ @@ -270,7 +270,7 @@ void BKE_constraint_mat_convertspace( /* world to pose */ invert_m4_m4(imat, ob->obmat); mul_m4_m4m4(mat, imat, mat); - + /* use pose-space as stepping stone for other spaces... */ if (ELEM(to, CONSTRAINT_SPACE_LOCAL, CONSTRAINT_SPACE_PARLOCAL)) { /* call self with slightly different values */ @@ -306,7 +306,7 @@ void BKE_constraint_mat_convertspace( /* we need the posespace_matrix = local_matrix + (parent_posespace_matrix + restpos) */ BKE_armature_mat_bone_to_pose(pchan, mat, mat); } - + /* use pose-space as stepping stone for other spaces */ if (ELEM(to, CONSTRAINT_SPACE_WORLD, CONSTRAINT_SPACE_PARLOCAL)) { /* call self with slightly different values */ @@ -321,7 +321,7 @@ void BKE_constraint_mat_convertspace( copy_m4_m4(diff_mat, pchan->bone->arm_mat); mul_m4_m4m4(mat, mat, diff_mat); } - + /* use pose-space as stepping stone for other spaces */ if (ELEM(to, CONSTRAINT_SPACE_WORLD, CONSTRAINT_SPACE_LOCAL)) { /* call self with slightly different values */ @@ -342,7 +342,7 @@ void BKE_constraint_mat_convertspace( mul_m4_m4m4(mat, imat, mat); } else { - /* Local space in this case will have to be defined as local to the owner's + /* Local space in this case will have to be defined as local to the owner's * transform-property-rotated axes. So subtract this rotation component. */ /* XXX This is actually an ugly hack, local space of a parent-less object *is* the same as @@ -357,7 +357,7 @@ void BKE_constraint_mat_convertspace( normalize_m4(diff_mat); } zero_v3(diff_mat[3]); - + invert_m4_m4_safe(imat, diff_mat); mul_m4_m4m4(mat, imat, mat); } @@ -370,7 +370,7 @@ void BKE_constraint_mat_convertspace( mul_m4_m4m4(mat, diff_mat, mat); } else { - /* Local space in this case will have to be defined as local to the owner's + /* Local space in this case will have to be defined as local to the owner's * transform-property-rotated axes. So add back this rotation component. */ /* XXX See comment above for world->local case... */ @@ -379,7 +379,7 @@ void BKE_constraint_mat_convertspace( normalize_m4(diff_mat); } zero_v3(diff_mat[3]); - + mul_m4_m4m4(mat, diff_mat, mat); } } @@ -398,10 +398,10 @@ static void contarget_get_mesh_mat(Object *ob, const char *substring, float mat[ float imat[3][3], tmat[3][3]; const int defgroup = defgroup_name_index(ob, substring); short freeDM = 0; - + /* initialize target matrix using target matrix */ copy_m4_m4(mat, ob->obmat); - + /* get index of vertex group */ if (defgroup == -1) return; @@ -413,18 +413,18 @@ static void contarget_get_mesh_mat(Object *ob, const char *substring, float mat[ } else { /* when not in EditMode, use the 'final' derived mesh, depsgraph - * ensures we build with CD_MDEFORMVERT layer + * ensures we build with CD_MDEFORMVERT layer */ dm = (DerivedMesh *)ob->derivedFinal; } - + /* only continue if there's a valid DerivedMesh */ if (dm) { MDeformVert *dvert = dm->getVertDataArray(dm, CD_MDEFORMVERT); int numVerts = dm->getNumVerts(dm); int i; float co[3], nor[3]; - + /* check that dvert is a valid pointers (just in case) */ if (dvert) { MDeformVert *dv = dvert; @@ -448,22 +448,22 @@ static void contarget_get_mesh_mat(Object *ob, const char *substring, float mat[ mul_v3_fl(vec, 1.0f / weightsum); mul_v3_fl(normal, 1.0f / weightsum); } - - - /* derive the rotation from the average normal: - * - code taken from transform_manipulator.c, + + + /* derive the rotation from the average normal: + * - code taken from transform_manipulator.c, * calc_manipulator_stats, V3D_MANIP_NORMAL case */ /* we need the transpose of the inverse for a normal... */ copy_m3_m4(imat, ob->obmat); - + invert_m3_m3(tmat, imat); transpose_m3(tmat); mul_m3_v3(tmat, normal); - + normalize_v3(normal); copy_v3_v3(plane, tmat[1]); - + cross_v3_v3v3(mat[0], normal, plane); if (len_squared_v3(mat[0]) < SQUARE(1e-3f)) { copy_v3_v3(plane, tmat[0]); @@ -475,12 +475,12 @@ static void contarget_get_mesh_mat(Object *ob, const char *substring, float mat[ normalize_m4(mat); - + /* apply the average coordinate as the new location */ mul_v3_m4v3(mat[3], ob->obmat, vec); } } - + /* free temporary DerivedMesh created (in EditMode case) */ if (dm && freeDM) dm->release(dm); @@ -490,25 +490,25 @@ static void contarget_get_mesh_mat(Object *ob, const char *substring, float mat[ static void contarget_get_lattice_mat(Object *ob, const char *substring, float mat[4][4]) { Lattice *lt = (Lattice *)ob->data; - + DispList *dl = ob->curve_cache ? BKE_displist_find(&ob->curve_cache->disp, DL_VERTS) : NULL; const float *co = dl ? dl->verts : NULL; BPoint *bp = lt->def; - + MDeformVert *dv = lt->dvert; int tot_verts = lt->pntsu * lt->pntsv * lt->pntsw; float vec[3] = {0.0f, 0.0f, 0.0f}, tvec[3]; int grouped = 0; int i, n; const int defgroup = defgroup_name_index(ob, substring); - + /* initialize target matrix using target matrix */ copy_m4_m4(mat, ob->obmat); /* get index of vertex group */ if (defgroup == -1) return; if (dv == NULL) return; - + /* 1. Loop through control-points checking if in nominated vertex-group. * 2. If it is, add it to vec to find the average point. */ @@ -523,17 +523,17 @@ static void contarget_get_lattice_mat(Object *ob, const char *substring, float m grouped++; } } - + /* advance pointer to coordinate data */ if (co) co += 3; else bp++; } - + /* find average location, then multiply by ob->obmat to find world-space location */ if (grouped) mul_v3_fl(vec, 1.0f / grouped); mul_v3_m4v3(tvec, ob->obmat, vec); - + /* copy new location to matrix */ copy_v3_v3(mat[3], tvec); } @@ -549,7 +549,7 @@ static void constraint_target_to_mat4(Object *ob, const char *substring, float m } /* Case VERTEXGROUP */ /* Current method just takes the average location of all the points in the - * VertexGroup, and uses that as the location value of the targets. Where + * VertexGroup, and uses that as the location value of the targets. Where * possible, the orientation will also be calculated, by calculating an * 'average' vertex normal, and deriving the rotation from that. * @@ -567,7 +567,7 @@ static void constraint_target_to_mat4(Object *ob, const char *substring, float m /* Case BONE */ else { bPoseChannel *pchan; - + pchan = BKE_pose_channel_find_name(ob->pose, substring); if (pchan) { /* Multiply the PoseSpace accumulation/final matrix for this @@ -583,22 +583,22 @@ static void constraint_target_to_mat4(Object *ob, const char *substring, float m Mat4 bbone[MAX_BBONE_SUBDIV]; float tempmat[4][4]; float loc[3], fac; - + /* get bbone segments */ b_bone_spline_setup(pchan, 0, bbone); - + /* figure out which segment(s) the headtail value falls in */ fac = (float)pchan->bone->segments * headtail; - + if (fac >= pchan->bone->segments - 1) { /* special case: end segment doesn't get created properly... */ float pt[3], sfac; int index; - + /* bbone points are in bonespace, so need to move to posespace first */ index = pchan->bone->segments - 1; mul_v3_m4v3(pt, pchan->pose_mat, bbone[index].mat[3]); - + /* interpolate between last segment point and the endpoint */ sfac = fac - (float)(pchan->bone->segments - 1); /* fac is just the "leftover" between penultimate and last points */ interp_v3_v3v3(loc, pt, pchan->pose_tail, sfac); @@ -607,45 +607,45 @@ static void constraint_target_to_mat4(Object *ob, const char *substring, float m /* get indices for finding interpolating between points along the bbone */ float pt_a[3], pt_b[3], pt[3]; int index_a, index_b; - + index_a = floorf(fac); CLAMP(index_a, 0, MAX_BBONE_SUBDIV - 1); - + index_b = ceilf(fac); CLAMP(index_b, 0, MAX_BBONE_SUBDIV - 1); - + /* interpolate between these points */ copy_v3_v3(pt_a, bbone[index_a].mat[3]); copy_v3_v3(pt_b, bbone[index_b].mat[3]); - + interp_v3_v3v3(pt, pt_a, pt_b, fac - floorf(fac)); - + /* move the point from bone local space to pose space... */ mul_v3_m4v3(loc, pchan->pose_mat, pt); } - + /* use interpolated distance for subtarget */ copy_m4_m4(tempmat, pchan->pose_mat); copy_v3_v3(tempmat[3], loc); - + mul_m4_m4m4(mat, ob->obmat, tempmat); } else { float tempmat[4][4], loc[3]; - + /* interpolate along length of bone */ interp_v3_v3v3(loc, pchan->pose_head, pchan->pose_tail, headtail); - + /* use interpolated distance for subtarget */ copy_m4_m4(tempmat, pchan->pose_mat); copy_v3_v3(tempmat[3], loc); - + mul_m4_m4m4(mat, ob->obmat, tempmat); } } else copy_m4_m4(mat, ob->obmat); - + /* convert matrix space as required */ BKE_constraint_mat_convertspace(ob, pchan, mat, from, to, false); } @@ -656,7 +656,7 @@ static void constraint_target_to_mat4(Object *ob, const char *substring, float m * times. In addition to this, each constraint should have a type-info struct, where * its functions are attached for use. */ - + /* Template for type-info data: * - make a copy of this when creating new constraints, and just change the functions * pointed to as necessary @@ -685,7 +685,7 @@ static bConstraintTypeInfo CTI_CONSTRNAME = { }; #endif -/* This function should be used for the get_target_matrix member of all +/* This function should be used for the get_target_matrix member of all * constraints that are not picky about what happens to their target matrix. */ static void default_get_tarmat(struct Depsgraph *UNUSED(depsgraph), bConstraint *con, bConstraintOb *UNUSED(cob), bConstraintTarget *ct, float UNUSED(ctime)) @@ -696,7 +696,7 @@ static void default_get_tarmat(struct Depsgraph *UNUSED(depsgraph), bConstraint unit_m4(ct->matrix); } -/* This following macro should be used for all standard single-target *_get_tars functions +/* This following macro should be used for all standard single-target *_get_tars functions * to save typing and reduce maintenance woes. * (Hopefully all compilers will be happy with the lines with just a space on them. Those are * really just to help this code easier to read) @@ -729,8 +729,8 @@ static void default_get_tarmat(struct Depsgraph *UNUSED(depsgraph), bConstraint \ BLI_addtail(list, ct); \ } (void)0 - -/* This following macro should be used for all standard single-target *_get_tars functions + +/* This following macro should be used for all standard single-target *_get_tars functions * to save typing and reduce maintenance woes. It does not do the subtarget related operations * (Hopefully all compilers will be happy with the lines with just a space on them. Those are * really just to help this code easier to read) @@ -769,7 +769,7 @@ static void default_get_tarmat(struct Depsgraph *UNUSED(depsgraph), bConstraint ct = ctn; \ } \ } (void)0 - + /* This following macro should be used for all standard single-target *_flush_tars functions * to save typing and reduce maintenance woes. It does not do the subtarget related operations. * Note: the pointer to ct will be changed to point to the next in the list (as it gets removed) @@ -795,7 +795,7 @@ static void default_get_tarmat(struct Depsgraph *UNUSED(depsgraph), bConstraint static void childof_new_data(void *cdata) { bChildOfConstraint *data = (bChildOfConstraint *)cdata; - + data->flag = (CHILDOF_LOCX | CHILDOF_LOCY | CHILDOF_LOCZ | CHILDOF_ROTX | CHILDOF_ROTY | CHILDOF_ROTZ | CHILDOF_SIZEX | CHILDOF_SIZEY | CHILDOF_SIZEZ); @@ -805,7 +805,7 @@ static void childof_new_data(void *cdata) static void childof_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata) { bChildOfConstraint *data = con->data; - + /* target only */ func(con, (ID **)&data->tar, false, userdata); } @@ -815,13 +815,13 @@ static int childof_get_tars(bConstraint *con, ListBase *list) if (con && list) { bChildOfConstraint *data = con->data; bConstraintTarget *ct; - + /* standard target-getting macro for single-target constraints */ SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list); - + return 1; } - + return 0; } @@ -830,7 +830,7 @@ static void childof_flush_tars(bConstraint *con, ListBase *list, bool no_copy) if (con && list) { bChildOfConstraint *data = con->data; bConstraintTarget *ct = list->first; - + /* the following macro is used for all standard single-target constraints */ SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, no_copy); } @@ -844,16 +844,16 @@ static void childof_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *tar /* only evaluate if there is a target */ if (VALID_CONS_TARGET(ct)) { float parmat[4][4]; - + /* simple matrix parenting */ if (data->flag == CHILDOF_ALL) { - - /* multiply target (parent matrix) by offset (parent inverse) to get + + /* multiply target (parent matrix) by offset (parent inverse) to get * the effect of the parent that will be exerted on the owner */ mul_m4_m4m4(parmat, ct->matrix, data->invmat); - - /* now multiply the parent matrix by the owner matrix to get the + + /* now multiply the parent matrix by the owner matrix to get the * the effect of this constraint (i.e. owner is 'parented' to parent) */ mul_m4_m4m4(cob->matrix, parmat, cob->matrix); @@ -862,19 +862,19 @@ static void childof_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *tar float invmat[4][4], tempmat[4][4]; float loc[3], eul[3], size[3]; float loco[3], eulo[3], sizo[3]; - + /* get offset (parent-inverse) matrix */ copy_m4_m4(invmat, data->invmat); - + /* extract components of both matrices */ copy_v3_v3(loc, ct->matrix[3]); mat4_to_eulO(eul, ct->rotOrder, ct->matrix); mat4_to_size(size, ct->matrix); - + copy_v3_v3(loco, invmat[3]); mat4_to_eulO(eulo, cob->rotOrder, invmat); mat4_to_size(sizo, invmat); - + /* disable channels not enabled */ if (!(data->flag & CHILDOF_LOCX)) loc[0] = loco[0] = 0.0f; if (!(data->flag & CHILDOF_LOCY)) loc[1] = loco[1] = 0.0f; @@ -885,22 +885,22 @@ static void childof_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *tar if (!(data->flag & CHILDOF_SIZEX)) size[0] = sizo[0] = 1.0f; if (!(data->flag & CHILDOF_SIZEY)) size[1] = sizo[1] = 1.0f; if (!(data->flag & CHILDOF_SIZEZ)) size[2] = sizo[2] = 1.0f; - + /* make new target mat and offset mat */ loc_eulO_size_to_mat4(ct->matrix, loc, eul, size, ct->rotOrder); loc_eulO_size_to_mat4(invmat, loco, eulo, sizo, cob->rotOrder); - - /* multiply target (parent matrix) by offset (parent inverse) to get + + /* multiply target (parent matrix) by offset (parent inverse) to get * the effect of the parent that will be exerted on the owner */ mul_m4_m4m4(parmat, ct->matrix, invmat); - - /* now multiply the parent matrix by the owner matrix to get the + + /* now multiply the parent matrix by the owner matrix to get the * the effect of this constraint (i.e. owner is 'parented' to parent) */ copy_m4_m4(tempmat, cob->matrix); mul_m4_m4m4(cob->matrix, parmat, tempmat); - + /* without this, changes to scale and rotation can change location * of a parentless bone or a disconnected bone. Even though its set * to zero above. */ @@ -932,15 +932,15 @@ static bConstraintTypeInfo CTI_CHILDOF = { static void trackto_new_data(void *cdata) { bTrackToConstraint *data = (bTrackToConstraint *)cdata; - + data->reserved1 = TRACK_Y; data->reserved2 = UP_Z; -} +} static void trackto_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata) { bTrackToConstraint *data = con->data; - + /* target only */ func(con, (ID **)&data->tar, false, userdata); } @@ -950,13 +950,13 @@ static int trackto_get_tars(bConstraint *con, ListBase *list) if (con && list) { bTrackToConstraint *data = con->data; bConstraintTarget *ct; - + /* standard target-getting macro for single-target constraints */ SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list); - + return 1; } - + return 0; } @@ -965,7 +965,7 @@ static void trackto_flush_tars(bConstraint *con, ListBase *list, bool no_copy) if (con && list) { bTrackToConstraint *data = con->data; bConstraintTarget *ct = list->first; - + /* the following macro is used for all standard single-target constraints */ SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, no_copy); } @@ -975,14 +975,14 @@ static void trackto_flush_tars(bConstraint *con, ListBase *list, bool no_copy) static int basis_cross(int n, int m) { switch (n - m) { - case 1: + case 1: case -2: return 1; - - case -1: + + case -1: case 2: return -1; - + default: return 0; } @@ -1038,14 +1038,14 @@ static void vectomat(const float vec[3], const float target_up[3], short axis, s if (axis != upflag) { right_index = 3 - axis - upflag; neg = (float)basis_cross(axis, upflag); - + /* account for up direction, track direction */ m[right_index][0] = neg * right[0]; m[right_index][1] = neg * right[1]; m[right_index][2] = neg * right[2]; - + copy_v3_v3(m[upflag], proj); - + copy_v3_v3(m[axis], n); } /* identity matrix - don't do anything if the two axes are the same */ @@ -1059,14 +1059,14 @@ static void trackto_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *tar { bTrackToConstraint *data = con->data; bConstraintTarget *ct = targets->first; - + if (VALID_CONS_TARGET(ct)) { float size[3], vec[3]; float totmat[3][3]; - + /* Get size property, since ob->size is only the object's own relative size, not its global one */ mat4_to_size(size, cob->matrix); - + /* Clear the object's rotation */ cob->matrix[0][0] = size[0]; cob->matrix[0][1] = 0; @@ -1077,12 +1077,12 @@ static void trackto_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *tar cob->matrix[2][0] = 0; cob->matrix[2][1] = 0; cob->matrix[2][2] = size[2]; - + /* targetmat[2] instead of ownermat[2] is passed to vectomat * for backwards compatibility it seems... (Aligorith) */ sub_v3_v3v3(vec, cob->matrix[3], ct->matrix[3]); - vectomat(vec, ct->matrix[2], + vectomat(vec, ct->matrix[2], (short)data->reserved1, (short)data->reserved2, data->flags, totmat); @@ -1110,7 +1110,7 @@ static bConstraintTypeInfo CTI_TRACKTO = { static void kinematic_new_data(void *cdata) { bKinematicConstraint *data = (bKinematicConstraint *)cdata; - + data->weight = 1.0f; data->orientweight = 1.0f; data->iterations = 500; @@ -1121,10 +1121,10 @@ static void kinematic_new_data(void *cdata) static void kinematic_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata) { bKinematicConstraint *data = con->data; - + /* chain target */ func(con, (ID **)&data->tar, false, userdata); - + /* poletarget */ func(con, (ID **)&data->poletar, false, userdata); } @@ -1134,14 +1134,14 @@ static int kinematic_get_tars(bConstraint *con, ListBase *list) if (con && list) { bKinematicConstraint *data = con->data; bConstraintTarget *ct; - + /* standard target-getting macro for single-target constraints is used twice here */ SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list); SINGLETARGET_GET_TARS(con, data->poletar, data->polesubtarget, ct, list); - + return 2; } - + return 0; } @@ -1150,7 +1150,7 @@ static void kinematic_flush_tars(bConstraint *con, ListBase *list, bool no_copy) if (con && list) { bKinematicConstraint *data = con->data; bConstraintTarget *ct = list->first; - + /* the following macro is used for all standard single-target constraints */ SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, no_copy); SINGLETARGET_FLUSH_TARS(con, data->poletar, data->polesubtarget, ct, list, no_copy); @@ -1160,13 +1160,13 @@ static void kinematic_flush_tars(bConstraint *con, ListBase *list, bool no_copy) static void kinematic_get_tarmat(struct Depsgraph *UNUSED(depsgraph), bConstraint *con, bConstraintOb *cob, bConstraintTarget *ct, float UNUSED(ctime)) { bKinematicConstraint *data = con->data; - - if (VALID_CONS_TARGET(ct)) + + if (VALID_CONS_TARGET(ct)) constraint_target_to_mat4(ct->tar, ct->subtarget, ct->matrix, CONSTRAINT_SPACE_WORLD, ct->space, con->flag, con->headtail); else if (ct) { if (data->flag & CONSTRAINT_IK_AUTO) { Object *ob = cob->ob; - + if (ob == NULL) { unit_m4(ct->matrix); } @@ -1203,7 +1203,7 @@ static bConstraintTypeInfo CTI_KINEMATIC = { static void followpath_new_data(void *cdata) { bFollowPathConstraint *data = (bFollowPathConstraint *)cdata; - + data->trackflag = TRACK_Y; data->upflag = UP_Z; data->offset = 0; @@ -1213,7 +1213,7 @@ static void followpath_new_data(void *cdata) static void followpath_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata) { bFollowPathConstraint *data = con->data; - + /* target only */ func(con, (ID **)&data->tar, false, userdata); } @@ -1223,13 +1223,13 @@ static int followpath_get_tars(bConstraint *con, ListBase *list) if (con && list) { bFollowPathConstraint *data = con->data; bConstraintTarget *ct; - + /* standard target-getting macro for single-target constraints without subtargets */ SINGLETARGETNS_GET_TARS(con, data->tar, ct, list); - + return 1; } - + return 0; } @@ -1238,7 +1238,7 @@ static void followpath_flush_tars(bConstraint *con, ListBase *list, bool no_copy if (con && list) { bFollowPathConstraint *data = con->data; bConstraintTarget *ct = list->first; - + /* the following macro is used for all standard single-target constraints */ SINGLETARGETNS_FLUSH_TARS(con, data->tar, ct, list, no_copy); } @@ -1249,7 +1249,7 @@ static void followpath_get_tarmat(struct Depsgraph *UNUSED(depsgraph), bConstraintTarget *ct, float UNUSED(ctime)) { bFollowPathConstraint *data = con->data; - + if (VALID_CONS_TARGET(ct) && (ct->tar->type == OB_CURVE)) { Curve *cu = ct->tar->data; float vec[4], dir[3], radius; @@ -1258,7 +1258,7 @@ static void followpath_get_tarmat(struct Depsgraph *UNUSED(depsgraph), unit_m4(ct->matrix); /* note: when creating constraints that follow path, the curve gets the CU_PATH set now, - * currently for paths to work it needs to go through the bevlist/displist system (ton) + * currently for paths to work it needs to go through the bevlist/displist system (ton) */ if (ct->tar->curve_cache && ct->tar->curve_cache->path && ct->tar->curve_cache->path->data) { @@ -1267,9 +1267,9 @@ static void followpath_get_tarmat(struct Depsgraph *UNUSED(depsgraph), /* animated position along curve depending on time */ Nurb *nu = cu->nurb.first; curvetime = cu->ctime - data->offset; - + /* ctime is now a proper var setting of Curve which gets set by Animato like any other var that's animated, - * but this will only work if it actually is animated... + * but this will only work if it actually is animated... * * we divide the curvetime calculated in the previous step by the length of the path, to get a time * factor, which then gets clamped to lie within 0.0 - 1.0 range @@ -1292,7 +1292,7 @@ static void followpath_get_tarmat(struct Depsgraph *UNUSED(depsgraph), /* fixed position along curve */ curvetime = data->offset_fac; } - + if (where_on_path(ct->tar, curvetime, vec, dir, (data->followflag & FOLLOWPATH_FOLLOW) ? quat : NULL, &radius, NULL) ) { /* quat_pt is quat or NULL*/ float totmat[4][4]; unit_m4(totmat); @@ -1301,7 +1301,7 @@ static void followpath_get_tarmat(struct Depsgraph *UNUSED(depsgraph), #if 0 float x1, q[4]; vec_to_quat(quat, dir, (short)data->trackflag, (short)data->upflag); - + normalize_v3(dir); q[0] = cosf(0.5 * vec[3]); x1 = sinf(0.5 * vec[3]); @@ -1322,9 +1322,9 @@ static void followpath_get_tarmat(struct Depsgraph *UNUSED(depsgraph), mul_m4_m4m4(rmat, tmat, totmat); copy_m4_m4(totmat, rmat); } - + copy_v3_v3(totmat[3], vec); - + mul_m4_m4m4(ct->matrix, ct->tar->obmat, totmat); } } @@ -1336,27 +1336,27 @@ static void followpath_get_tarmat(struct Depsgraph *UNUSED(depsgraph), static void followpath_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *targets) { bConstraintTarget *ct = targets->first; - + /* only evaluate if there is a target */ if (VALID_CONS_TARGET(ct)) { float obmat[4][4]; float size[3]; bFollowPathConstraint *data = con->data; - + /* get Object transform (loc/rot/size) to determine transformation from path */ /* TODO: this used to be local at one point, but is probably more useful as-is */ copy_m4_m4(obmat, cob->matrix); - + /* get scaling of object before applying constraint */ mat4_to_size(size, cob->matrix); - + /* apply targetmat - containing location on path, and rotation */ mul_m4_m4m4(cob->matrix, ct->matrix, obmat); - + /* un-apply scaling caused by path */ if ((data->followflag & FOLLOWPATH_RADIUS) == 0) { /* XXX - assume that scale correction means that radius will have some scale error in it - Campbell */ float obsize[3]; - + mat4_to_size(obsize, cob->matrix); if (obsize[0]) mul_v3_fl(cob->matrix[0], size[0] / obsize[0]); @@ -1389,7 +1389,7 @@ static bConstraintTypeInfo CTI_FOLLOWPATH = { static void loclimit_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *UNUSED(targets)) { bLocLimitConstraint *data = con->data; - + if (data->flag & LIMIT_XMIN) { if (cob->matrix[3][0] < data->xmin) cob->matrix[3][0] = data->xmin; @@ -1407,7 +1407,7 @@ static void loclimit_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *UN cob->matrix[3][1] = data->ymax; } if (data->flag & LIMIT_ZMIN) { - if (cob->matrix[3][2] < data->zmin) + if (cob->matrix[3][2] < data->zmin) cob->matrix[3][2] = data->zmin; } if (data->flag & LIMIT_ZMAX) { @@ -1439,37 +1439,37 @@ static void rotlimit_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *UN float loc[3]; float eul[3]; float size[3]; - + copy_v3_v3(loc, cob->matrix[3]); mat4_to_size(size, cob->matrix); mat4_to_eulO(eul, cob->rotOrder, cob->matrix); /* constraint data uses radians internally */ - + /* limiting of euler values... */ if (data->flag & LIMIT_XROT) { - if (eul[0] < data->xmin) + if (eul[0] < data->xmin) eul[0] = data->xmin; - + if (eul[0] > data->xmax) eul[0] = data->xmax; } if (data->flag & LIMIT_YROT) { if (eul[1] < data->ymin) eul[1] = data->ymin; - + if (eul[1] > data->ymax) eul[1] = data->ymax; } if (data->flag & LIMIT_ZROT) { if (eul[2] < data->zmin) eul[2] = data->zmin; - + if (eul[2] > data->zmax) eul[2] = data->zmax; } - + loc_eulO_size_to_mat4(cob->matrix, loc, eul, size, cob->rotOrder); } @@ -1495,40 +1495,40 @@ static void sizelimit_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *U { bSizeLimitConstraint *data = con->data; float obsize[3], size[3]; - + mat4_to_size(size, cob->matrix); mat4_to_size(obsize, cob->matrix); - + if (data->flag & LIMIT_XMIN) { - if (size[0] < data->xmin) + if (size[0] < data->xmin) size[0] = data->xmin; } if (data->flag & LIMIT_XMAX) { - if (size[0] > data->xmax) + if (size[0] > data->xmax) size[0] = data->xmax; } if (data->flag & LIMIT_YMIN) { - if (size[1] < data->ymin) + if (size[1] < data->ymin) size[1] = data->ymin; } if (data->flag & LIMIT_YMAX) { - if (size[1] > data->ymax) + if (size[1] > data->ymax) size[1] = data->ymax; } if (data->flag & LIMIT_ZMIN) { - if (size[2] < data->zmin) + if (size[2] < data->zmin) size[2] = data->zmin; } if (data->flag & LIMIT_ZMAX) { - if (size[2] > data->zmax) + if (size[2] > data->zmax) size[2] = data->zmax; } - - if (obsize[0]) + + if (obsize[0]) mul_v3_fl(cob->matrix[0], size[0] / obsize[0]); - if (obsize[1]) + if (obsize[1]) mul_v3_fl(cob->matrix[1], size[1] / obsize[1]); - if (obsize[2]) + if (obsize[2]) mul_v3_fl(cob->matrix[2], size[2] / obsize[2]); } @@ -1552,14 +1552,14 @@ static bConstraintTypeInfo CTI_SIZELIMIT = { static void loclike_new_data(void *cdata) { bLocateLikeConstraint *data = (bLocateLikeConstraint *)cdata; - + data->flag = LOCLIKE_X | LOCLIKE_Y | LOCLIKE_Z; } static void loclike_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata) { bLocateLikeConstraint *data = con->data; - + /* target only */ func(con, (ID **)&data->tar, false, userdata); } @@ -1569,13 +1569,13 @@ static int loclike_get_tars(bConstraint *con, ListBase *list) if (con && list) { bLocateLikeConstraint *data = con->data; bConstraintTarget *ct; - + /* standard target-getting macro for single-target constraints */ SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list); - + return 1; } - + return 0; } @@ -1584,7 +1584,7 @@ static void loclike_flush_tars(bConstraint *con, ListBase *list, bool no_copy) if (con && list) { bLocateLikeConstraint *data = con->data; bConstraintTarget *ct = list->first; - + /* the following macro is used for all standard single-target constraints */ SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, no_copy); } @@ -1594,28 +1594,28 @@ static void loclike_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *tar { bLocateLikeConstraint *data = con->data; bConstraintTarget *ct = targets->first; - + if (VALID_CONS_TARGET(ct)) { float offset[3] = {0.0f, 0.0f, 0.0f}; - + if (data->flag & LOCLIKE_OFFSET) copy_v3_v3(offset, cob->matrix[3]); - + if (data->flag & LOCLIKE_X) { cob->matrix[3][0] = ct->matrix[3][0]; - + if (data->flag & LOCLIKE_X_INVERT) cob->matrix[3][0] *= -1; cob->matrix[3][0] += offset[0]; } if (data->flag & LOCLIKE_Y) { cob->matrix[3][1] = ct->matrix[3][1]; - + if (data->flag & LOCLIKE_Y_INVERT) cob->matrix[3][1] *= -1; cob->matrix[3][1] += offset[1]; } if (data->flag & LOCLIKE_Z) { cob->matrix[3][2] = ct->matrix[3][2]; - + if (data->flag & LOCLIKE_Z_INVERT) cob->matrix[3][2] *= -1; cob->matrix[3][2] += offset[2]; } @@ -1642,14 +1642,14 @@ static bConstraintTypeInfo CTI_LOCLIKE = { static void rotlike_new_data(void *cdata) { bRotateLikeConstraint *data = (bRotateLikeConstraint *)cdata; - + data->flag = ROTLIKE_X | ROTLIKE_Y | ROTLIKE_Z; } static void rotlike_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata) { bRotateLikeConstraint *data = con->data; - + /* target only */ func(con, (ID **)&data->tar, false, userdata); } @@ -1659,13 +1659,13 @@ static int rotlike_get_tars(bConstraint *con, ListBase *list) if (con && list) { bRotateLikeConstraint *data = con->data; bConstraintTarget *ct; - + /* standard target-getting macro for single-target constraints */ SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list); - + return 1; } - + return 0; } @@ -1674,7 +1674,7 @@ static void rotlike_flush_tars(bConstraint *con, ListBase *list, bool no_copy) if (con && list) { bRotateLikeConstraint *data = con->data; bConstraintTarget *ct = list->first; - + /* the following macro is used for all standard single-target constraints */ SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, no_copy); } @@ -1684,50 +1684,50 @@ static void rotlike_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *tar { bRotateLikeConstraint *data = con->data; bConstraintTarget *ct = targets->first; - + if (VALID_CONS_TARGET(ct)) { float loc[3]; float eul[3], obeul[3]; float size[3]; - + copy_v3_v3(loc, cob->matrix[3]); mat4_to_size(size, cob->matrix); - + /* to allow compatible rotations, must get both rotations in the order of the owner... */ mat4_to_eulO(obeul, cob->rotOrder, cob->matrix); /* we must get compatible eulers from the beginning because some of them can be modified below (see bug #21875) */ mat4_to_compatible_eulO(eul, obeul, cob->rotOrder, ct->matrix); - + if ((data->flag & ROTLIKE_X) == 0) eul[0] = obeul[0]; else { if (data->flag & ROTLIKE_OFFSET) rotate_eulO(eul, cob->rotOrder, 'X', obeul[0]); - + if (data->flag & ROTLIKE_X_INVERT) eul[0] *= -1; } - + if ((data->flag & ROTLIKE_Y) == 0) eul[1] = obeul[1]; else { if (data->flag & ROTLIKE_OFFSET) rotate_eulO(eul, cob->rotOrder, 'Y', obeul[1]); - + if (data->flag & ROTLIKE_Y_INVERT) eul[1] *= -1; } - + if ((data->flag & ROTLIKE_Z) == 0) eul[2] = obeul[2]; else { if (data->flag & ROTLIKE_OFFSET) rotate_eulO(eul, cob->rotOrder, 'Z', obeul[2]); - + if (data->flag & ROTLIKE_Z_INVERT) eul[2] *= -1; } - + /* good to make eulers compatible again, since we don't know how much they were changed above */ compatible_eul(eul, obeul); loc_eulO_size_to_mat4(cob->matrix, loc, eul, size, cob->rotOrder); @@ -1754,14 +1754,14 @@ static bConstraintTypeInfo CTI_ROTLIKE = { static void sizelike_new_data(void *cdata) { bSizeLikeConstraint *data = (bSizeLikeConstraint *)cdata; - + data->flag = SIZELIKE_X | SIZELIKE_Y | SIZELIKE_Z; } static void sizelike_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata) { bSizeLikeConstraint *data = con->data; - + /* target only */ func(con, (ID **)&data->tar, false, userdata); } @@ -1771,13 +1771,13 @@ static int sizelike_get_tars(bConstraint *con, ListBase *list) if (con && list) { bSizeLikeConstraint *data = con->data; bConstraintTarget *ct; - + /* standard target-getting macro for single-target constraints */ SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list); - + return 1; } - + return 0; } @@ -1786,7 +1786,7 @@ static void sizelike_flush_tars(bConstraint *con, ListBase *list, bool no_copy) if (con && list) { bSizeLikeConstraint *data = con->data; bConstraintTarget *ct = list->first; - + /* the following macro is used for all standard single-target constraints */ SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, no_copy); } @@ -1796,13 +1796,13 @@ static void sizelike_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *ta { bSizeLikeConstraint *data = con->data; bConstraintTarget *ct = targets->first; - + if (VALID_CONS_TARGET(ct)) { float obsize[3], size[3]; - + mat4_to_size(size, ct->matrix); mat4_to_size(obsize, cob->matrix); - + if ((data->flag & SIZELIKE_X) && (obsize[0] != 0)) { if (data->flag & SIZELIKE_OFFSET) { size[0] += (obsize[0] - 1.0f); @@ -1850,7 +1850,7 @@ static bConstraintTypeInfo CTI_SIZELIKE = { static void translike_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata) { bTransLikeConstraint *data = con->data; - + /* target only */ func(con, (ID **)&data->tar, false, userdata); } @@ -1860,13 +1860,13 @@ static int translike_get_tars(bConstraint *con, ListBase *list) if (con && list) { bTransLikeConstraint *data = con->data; bConstraintTarget *ct; - + /* standard target-getting macro for single-target constraints */ SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list); - + return 1; } - + return 0; } @@ -1875,7 +1875,7 @@ static void translike_flush_tars(bConstraint *con, ListBase *list, bool no_copy) if (con && list) { bTransLikeConstraint *data = con->data; bConstraintTarget *ct = list->first; - + /* the following macro is used for all standard single-target constraints */ SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, no_copy); } @@ -1884,7 +1884,7 @@ static void translike_flush_tars(bConstraint *con, ListBase *list, bool no_copy) static void translike_evaluate(bConstraint *UNUSED(con), bConstraintOb *cob, ListBase *targets) { bConstraintTarget *ct = targets->first; - + if (VALID_CONS_TARGET(ct)) { /* just copy the entire transform matrix of the target */ copy_m4_m4(cob->matrix, ct->matrix); @@ -1925,12 +1925,12 @@ static void samevolume_evaluate(bConstraint *con, bConstraintOb *cob, ListBase * float obsize[3]; mat4_to_size(obsize, cob->matrix); - + /* calculate normalizing scale factor for non-essential values */ total_scale = obsize[0] * obsize[1] * obsize[2]; if (total_scale != 0) fac = sqrtf(volume / total_scale); - + /* apply scaling factor to the channels not being kept */ switch (data->flag) { case SAMEVOL_X: @@ -1968,20 +1968,20 @@ static bConstraintTypeInfo CTI_SAMEVOL = { static void pycon_free(bConstraint *con) { bPythonConstraint *data = con->data; - + /* id-properties */ IDP_FreeProperty(data->prop); MEM_freeN(data->prop); - + /* multiple targets */ BLI_freelistN(&data->targets); -} +} static void pycon_copy(bConstraint *con, bConstraint *srccon) { bPythonConstraint *pycon = (bPythonConstraint *)con->data; bPythonConstraint *opycon = (bPythonConstraint *)srccon->data; - + pycon->prop = IDP_CopyProperty(opycon->prop); BLI_duplicatelist(&pycon->targets, &opycon->targets); } @@ -1989,7 +1989,7 @@ static void pycon_copy(bConstraint *con, bConstraint *srccon) static void pycon_new_data(void *cdata) { bPythonConstraint *data = (bPythonConstraint *)cdata; - + /* everything should be set correctly by calloc, except for the prop->type constant.*/ data->prop = MEM_callocN(sizeof(IDProperty), "PyConstraintProps"); data->prop->type = IDP_GROUP; @@ -1999,13 +1999,13 @@ static int pycon_get_tars(bConstraint *con, ListBase *list) { if (con && list) { bPythonConstraint *data = con->data; - + list->first = data->targets.first; list->last = data->targets.last; - + return data->tarnum; } - + return 0; } @@ -2013,11 +2013,11 @@ static void pycon_id_looper(bConstraint *con, ConstraintIDFunc func, void *userd { bPythonConstraint *data = con->data; bConstraintTarget *ct; - + /* targets */ for (ct = data->targets.first; ct; ct = ct->next) func(con, (ID **)&ct->tar, false, userdata); - + /* script */ func(con, (ID **)&data->text, true, userdata); } @@ -2041,7 +2041,7 @@ static void pycon_get_tarmat(struct Depsgraph *UNUSED(depsgraph), * this matrix if it needs to do so */ constraint_target_to_mat4(ct->tar, ct->subtarget, ct->matrix, CONSTRAINT_SPACE_WORLD, ct->space, con->flag, con->headtail); - + /* only execute target calculation if allowed */ #ifdef WITH_PYTHON if (G.f & G_SCRIPT_AUTOEXEC) @@ -2059,19 +2059,19 @@ static void pycon_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *targe return; #else bPythonConstraint *data = con->data; - + /* only evaluate in python if we're allowed to do so */ if ((G.f & G_SCRIPT_AUTOEXEC) == 0) return; - + /* currently removed, until I this can be re-implemented for multiple targets */ #if 0 - /* Firstly, run the 'driver' function which has direct access to the objects involved + /* Firstly, run the 'driver' function which has direct access to the objects involved * Technically, this is potentially dangerous as users may abuse this and cause dependency-problems, * but it also allows certain 'clever' rigging hacks to work. */ BPY_pyconstraint_driver(data, cob, targets); #endif - + /* Now, run the actual 'constraint' function, which should only access the matrices */ BPY_pyconstraint_exec(data, cob, targets); #endif /* WITH_PYTHON */ @@ -2097,7 +2097,7 @@ static bConstraintTypeInfo CTI_PYTHON = { static void actcon_new_data(void *cdata) { bActionConstraint *data = (bActionConstraint *)cdata; - + /* set type to 20 (Loc X), as 0 is Rot X for backwards compatibility */ data->type = 20; } @@ -2105,10 +2105,10 @@ static void actcon_new_data(void *cdata) static void actcon_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata) { bActionConstraint *data = con->data; - + /* target */ func(con, (ID **)&data->tar, false, userdata); - + /* action */ func(con, (ID **)&data->act, true, userdata); } @@ -2118,13 +2118,13 @@ static int actcon_get_tars(bConstraint *con, ListBase *list) if (con && list) { bActionConstraint *data = con->data; bConstraintTarget *ct; - + /* standard target-getting macro for single-target constraints */ SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list); - + return 1; } - + return 0; } @@ -2133,7 +2133,7 @@ static void actcon_flush_tars(bConstraint *con, ListBase *list, bool no_copy) if (con && list) { bActionConstraint *data = con->data; bConstraintTarget *ct = list->first; - + /* the following macro is used for all standard single-target constraints */ SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, no_copy); } @@ -2142,18 +2142,18 @@ static void actcon_flush_tars(bConstraint *con, ListBase *list, bool no_copy) static void actcon_get_tarmat(struct Depsgraph *UNUSED(depsgraph), bConstraint *con, bConstraintOb *cob, bConstraintTarget *ct, float UNUSED(ctime)) { bActionConstraint *data = con->data; - + if (VALID_CONS_TARGET(ct)) { float tempmat[4][4], vec[3]; float s, t; short axis; - + /* initialize return matrix */ unit_m4(ct->matrix); - + /* get the transform matrix of the target */ constraint_target_to_mat4(ct->tar, ct->subtarget, tempmat, CONSTRAINT_SPACE_WORLD, ct->space, con->flag, con->headtail); - + /* determine where in transform range target is */ /* data->type is mapped as follows for backwards compatibility: * 00,01,02 - rotation (it used to be like this) @@ -2176,21 +2176,21 @@ static void actcon_get_tarmat(struct Depsgraph *UNUSED(depsgraph), bConstraint * copy_v3_v3(vec, tempmat[3]); axis = data->type - 20; } - + BLI_assert((unsigned int)axis < 3); /* Target defines the animation */ s = (vec[axis] - data->min) / (data->max - data->min); CLAMP(s, 0, 1); t = (s * (data->end - data->start)) + data->start; - + if (G.debug & G_DEBUG) printf("do Action Constraint %s - Ob %s Pchan %s\n", con->name, cob->ob->id.name + 2, (cob->pchan) ? cob->pchan->name : NULL); - + /* Get the appropriate information from the action */ if (cob->type == CONSTRAINT_OBTYPE_OBJECT || (data->flag & ACTCON_BONE_USE_OBJECT_ACTION)) { Object workob; - + /* evaluate using workob */ /* FIXME: we don't have any consistent standards on limiting effects on object... */ what_does_obaction(cob->ob, &workob, NULL, data->act, NULL, t); @@ -2201,21 +2201,21 @@ static void actcon_get_tarmat(struct Depsgraph *UNUSED(depsgraph), bConstraint * bPose pose = {{0}}; bPoseChannel *pchan, *tchan; - /* make a copy of the bone of interest in the temp pose before evaluating action, so that it can get set + /* make a copy of the bone of interest in the temp pose before evaluating action, so that it can get set * - we need to manually copy over a few settings, including rotation order, otherwise this fails */ pchan = cob->pchan; - + tchan = BKE_pose_channel_verify(&pose, pchan->name); tchan->rotmode = pchan->rotmode; - + /* evaluate action using workob (it will only set the PoseChannel in question) */ what_does_obaction(cob->ob, &workob, &pose, data->act, pchan->name, t); - + /* convert animation to matrices for use here */ BKE_pchan_calc_mat(tchan); copy_m4_m4(ct->matrix, tchan->chan_mat); - + /* Clean up */ BKE_pose_free_data(&pose); } @@ -2229,10 +2229,10 @@ static void actcon_get_tarmat(struct Depsgraph *UNUSED(depsgraph), bConstraint * static void actcon_evaluate(bConstraint *UNUSED(con), bConstraintOb *cob, ListBase *targets) { bConstraintTarget *ct = targets->first; - + if (VALID_CONS_TARGET(ct)) { float temp[4][4]; - + /* Nice and simple... we just need to multiply the matrices, as the get_target_matrix * function has already taken care of everything else. */ @@ -2261,15 +2261,15 @@ static bConstraintTypeInfo CTI_ACTION = { static void locktrack_new_data(void *cdata) { bLockTrackConstraint *data = (bLockTrackConstraint *)cdata; - + data->trackflag = TRACK_Y; data->lockflag = LOCK_Z; -} +} static void locktrack_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata) { bLockTrackConstraint *data = con->data; - + /* target only */ func(con, (ID **)&data->tar, false, userdata); } @@ -2279,13 +2279,13 @@ static int locktrack_get_tars(bConstraint *con, ListBase *list) if (con && list) { bLockTrackConstraint *data = con->data; bConstraintTarget *ct; - + /* the following macro is used for all standard single-target constraints */ SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list); - + return 1; } - + return 0; } @@ -2294,7 +2294,7 @@ static void locktrack_flush_tars(bConstraint *con, ListBase *list, bool no_copy) if (con && list) { bLockTrackConstraint *data = con->data; bConstraintTarget *ct = list->first; - + /* the following macro is used for all standard single-target constraints */ SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, no_copy); } @@ -2304,14 +2304,14 @@ static void locktrack_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t { bLockTrackConstraint *data = con->data; bConstraintTarget *ct = targets->first; - + if (VALID_CONS_TARGET(ct)) { float vec[3], vec2[3]; float totmat[3][3]; float tmpmat[3][3]; float invmat[3][3]; float mdet; - + /* Vector object -> target */ sub_v3_v3v3(vec, ct->matrix[3], cob->matrix[3]); switch (data->lockflag) { @@ -2324,10 +2324,10 @@ static void locktrack_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t project_v3_v3v3(vec2, vec, cob->matrix[0]); sub_v3_v3v3(totmat[1], vec, vec2); normalize_v3(totmat[1]); - + /* the x axis is fixed */ normalize_v3_v3(totmat[0], cob->matrix[0]); - + /* the z axis gets mapped onto a third orthogonal vector */ cross_v3_v3v3(totmat[2], totmat[0], totmat[1]); break; @@ -2338,10 +2338,10 @@ static void locktrack_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t project_v3_v3v3(vec2, vec, cob->matrix[0]); sub_v3_v3v3(totmat[2], vec, vec2); normalize_v3(totmat[2]); - + /* the x axis is fixed */ normalize_v3_v3(totmat[0], cob->matrix[0]); - + /* the z axis gets mapped onto a third orthogonal vector */ cross_v3_v3v3(totmat[1], totmat[2], totmat[0]); break; @@ -2353,10 +2353,10 @@ static void locktrack_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t sub_v3_v3v3(totmat[1], vec, vec2); normalize_v3(totmat[1]); negate_v3(totmat[1]); - + /* the x axis is fixed */ normalize_v3_v3(totmat[0], cob->matrix[0]); - + /* the z axis gets mapped onto a third orthogonal vector */ cross_v3_v3v3(totmat[2], totmat[0], totmat[1]); break; @@ -2368,10 +2368,10 @@ static void locktrack_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t sub_v3_v3v3(totmat[2], vec, vec2); normalize_v3(totmat[2]); negate_v3(totmat[2]); - + /* the x axis is fixed */ normalize_v3_v3(totmat[0], cob->matrix[0]); - + /* the z axis gets mapped onto a third orthogonal vector */ cross_v3_v3v3(totmat[1], totmat[2], totmat[0]); break; @@ -2393,7 +2393,7 @@ static void locktrack_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t project_v3_v3v3(vec2, vec, cob->matrix[1]); sub_v3_v3v3(totmat[0], vec, vec2); normalize_v3(totmat[0]); - + /* the y axis is fixed */ normalize_v3_v3(totmat[1], cob->matrix[1]); @@ -2407,10 +2407,10 @@ static void locktrack_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t project_v3_v3v3(vec2, vec, cob->matrix[1]); sub_v3_v3v3(totmat[2], vec, vec2); normalize_v3(totmat[2]); - + /* the y axis is fixed */ normalize_v3_v3(totmat[1], cob->matrix[1]); - + /* the z axis gets mapped onto a third orthogonal vector */ cross_v3_v3v3(totmat[0], totmat[1], totmat[2]); break; @@ -2422,10 +2422,10 @@ static void locktrack_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t sub_v3_v3v3(totmat[0], vec, vec2); normalize_v3(totmat[0]); negate_v3(totmat[0]); - + /* the y axis is fixed */ normalize_v3_v3(totmat[1], cob->matrix[1]); - + /* the z axis gets mapped onto a third orthogonal vector */ cross_v3_v3v3(totmat[2], totmat[0], totmat[1]); break; @@ -2437,10 +2437,10 @@ static void locktrack_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t sub_v3_v3v3(totmat[2], vec, vec2); normalize_v3(totmat[2]); negate_v3(totmat[2]); - + /* the y axis is fixed */ normalize_v3_v3(totmat[1], cob->matrix[1]); - + /* the z axis gets mapped onto a third orthogonal vector */ cross_v3_v3v3(totmat[0], totmat[1], totmat[2]); break; @@ -2462,10 +2462,10 @@ static void locktrack_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t project_v3_v3v3(vec2, vec, cob->matrix[2]); sub_v3_v3v3(totmat[0], vec, vec2); normalize_v3(totmat[0]); - + /* the z axis is fixed */ normalize_v3_v3(totmat[2], cob->matrix[2]); - + /* the x axis gets mapped onto a third orthogonal vector */ cross_v3_v3v3(totmat[1], totmat[2], totmat[0]); break; @@ -2476,10 +2476,10 @@ static void locktrack_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t project_v3_v3v3(vec2, vec, cob->matrix[2]); sub_v3_v3v3(totmat[1], vec, vec2); normalize_v3(totmat[1]); - + /* the z axis is fixed */ normalize_v3_v3(totmat[2], cob->matrix[2]); - + /* the x axis gets mapped onto a third orthogonal vector */ cross_v3_v3v3(totmat[0], totmat[1], totmat[2]); break; @@ -2491,10 +2491,10 @@ static void locktrack_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t sub_v3_v3v3(totmat[0], vec, vec2); normalize_v3(totmat[0]); negate_v3(totmat[0]); - + /* the z axis is fixed */ normalize_v3_v3(totmat[2], cob->matrix[2]); - + /* the x axis gets mapped onto a third orthogonal vector */ cross_v3_v3v3(totmat[1], totmat[2], totmat[0]); break; @@ -2506,10 +2506,10 @@ static void locktrack_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t sub_v3_v3v3(totmat[1], vec, vec2); normalize_v3(totmat[1]); negate_v3(totmat[1]); - + /* the z axis is fixed */ normalize_v3_v3(totmat[2], cob->matrix[2]); - + /* the x axis gets mapped onto a third orthogonal vector */ cross_v3_v3v3(totmat[0], totmat[1], totmat[2]); break; @@ -2536,14 +2536,14 @@ static void locktrack_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t totmat[0][0] = tmpmat[0][0]; totmat[0][1] = tmpmat[0][1]; totmat[0][2] = tmpmat[0][2]; totmat[1][0] = tmpmat[1][0]; totmat[1][1] = tmpmat[1][1]; totmat[1][2] = tmpmat[1][2]; totmat[2][0] = tmpmat[2][0]; totmat[2][1] = tmpmat[2][1]; totmat[2][2] = tmpmat[2][2]; - + mdet = determinant_m3(totmat[0][0], totmat[0][1], totmat[0][2], totmat[1][0], totmat[1][1], totmat[1][2], totmat[2][0], totmat[2][1], totmat[2][2]); if (mdet == 0) { unit_m3(totmat); } - + /* apply out transformaton to the object */ mul_m4_m3m4(cob->matrix, totmat, cob->matrix); } @@ -2569,14 +2569,14 @@ static bConstraintTypeInfo CTI_LOCKTRACK = { static void distlimit_new_data(void *cdata) { bDistLimitConstraint *data = (bDistLimitConstraint *)cdata; - + data->dist = 0.0f; } static void distlimit_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata) { bDistLimitConstraint *data = con->data; - + /* target only */ func(con, (ID **)&data->tar, false, userdata); } @@ -2586,13 +2586,13 @@ static int distlimit_get_tars(bConstraint *con, ListBase *list) if (con && list) { bDistLimitConstraint *data = con->data; bConstraintTarget *ct; - + /* standard target-getting macro for single-target constraints */ SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list); - + return 1; } - + return 0; } @@ -2601,7 +2601,7 @@ static void distlimit_flush_tars(bConstraint *con, ListBase *list, bool no_copy) if (con && list) { bDistLimitConstraint *data = con->data; bConstraintTarget *ct = list->first; - + /* the following macro is used for all standard single-target constraints */ SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, no_copy); } @@ -2611,19 +2611,19 @@ static void distlimit_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t { bDistLimitConstraint *data = con->data; bConstraintTarget *ct = targets->first; - + /* only evaluate if there is a target */ if (VALID_CONS_TARGET(ct)) { float dvec[3], dist, sfac = 1.0f; short clamp_surf = 0; - + /* calculate our current distance from the target */ dist = len_v3v3(cob->matrix[3], ct->matrix[3]); - + /* set distance (flag is only set when user demands it) */ if (data->dist == 0) data->dist = dist; - + /* check if we're which way to clamp from, and calculate interpolation factor (if needed) */ if (data->mode == LIMITDIST_OUTSIDE) { /* if inside, then move to surface */ @@ -2650,7 +2650,7 @@ static void distlimit_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t if (dist >= (data->dist - data->soft)) { sfac = (float)(data->soft * (1.0f - expf(-(dist - data->dist) / data->soft)) + data->dist); if (dist != 0.0f) sfac /= dist; - + clamp_surf = 1; } } @@ -2661,12 +2661,12 @@ static void distlimit_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t if (dist != 0.0f) sfac = data->dist / dist; } } - + /* clamp to 'surface' (i.e. move owner so that dist == data->dist) */ if (clamp_surf) { /* simply interpolate along line formed by target -> owner */ interp_v3_v3v3(dvec, ct->matrix[3], cob->matrix[3], sfac); - + /* copy new vector onto owner */ copy_v3_v3(cob->matrix[3], dvec); } @@ -2693,10 +2693,10 @@ static bConstraintTypeInfo CTI_DISTLIMIT = { static void stretchto_new_data(void *cdata) { bStretchToConstraint *data = (bStretchToConstraint *)cdata; - + data->volmode = 0; data->plane = 0; - data->orglength = 0.0; + data->orglength = 0.0; data->bulge = 1.0; data->bulge_max = 1.0f; data->bulge_min = 1.0f; @@ -2705,7 +2705,7 @@ static void stretchto_new_data(void *cdata) static void stretchto_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata) { bStretchToConstraint *data = con->data; - + /* target only */ func(con, (ID **)&data->tar, false, userdata); } @@ -2715,13 +2715,13 @@ static int stretchto_get_tars(bConstraint *con, ListBase *list) if (con && list) { bStretchToConstraint *data = con->data; bConstraintTarget *ct; - + /* standard target-getting macro for single-target constraints */ SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list); - + return 1; } - + return 0; } @@ -2730,7 +2730,7 @@ static void stretchto_flush_tars(bConstraint *con, ListBase *list, bool no_copy) if (con && list) { bStretchToConstraint *data = con->data; bConstraintTarget *ct = list->first; - + /* the following macro is used for all standard single-target constraints */ SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, no_copy); } @@ -2740,51 +2740,51 @@ static void stretchto_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t { bStretchToConstraint *data = con->data; bConstraintTarget *ct = targets->first; - + /* only evaluate if there is a target */ if (VALID_CONS_TARGET(ct)) { float size[3], scale[3], vec[3], xx[3], zz[3], orth[3]; float totmat[3][3]; float dist, bulge; - + /* store scaling before destroying obmat */ mat4_to_size(size, cob->matrix); - + /* store X orientation before destroying obmat */ normalize_v3_v3(xx, cob->matrix[0]); - + /* store Z orientation before destroying obmat */ normalize_v3_v3(zz, cob->matrix[2]); - + /* XXX That makes the constraint buggy with asymmetrically scaled objects, see #29940. */ /* sub_v3_v3v3(vec, cob->matrix[3], ct->matrix[3]);*/ /* vec[0] /= size[0];*/ /* vec[1] /= size[1];*/ /* vec[2] /= size[2];*/ - + /* dist = normalize_v3(vec);*/ dist = len_v3v3(cob->matrix[3], ct->matrix[3]); /* Only Y constrained object axis scale should be used, to keep same length when scaling it. */ dist /= size[1]; - + /* data->orglength==0 occurs on first run, and after 'R' button is clicked */ if (data->orglength == 0) data->orglength = dist; scale[1] = dist / data->orglength; - + bulge = powf(data->orglength / dist, data->bulge); - + if (bulge > 1.0f) { if (data->flag & STRETCHTOCON_USE_BULGE_MAX) { float bulge_max = max_ff(data->bulge_max, 1.0f); float hard = min_ff(bulge, bulge_max); - + float range = bulge_max - 1.0f; float scale_fac = (range > 0.0f) ? 1.0f / range : 0.0f; float soft = 1.0f + range * atanf((bulge - 1.0f) * scale_fac) / (float)M_PI_2; - + bulge = interpf(soft, hard, data->bulge_smooth); } } @@ -2792,15 +2792,15 @@ static void stretchto_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t if (data->flag & STRETCHTOCON_USE_BULGE_MIN) { float bulge_min = CLAMPIS(data->bulge_min, 0.0f, 1.0f); float hard = max_ff(bulge, bulge_min); - + float range = 1.0f - bulge_min; float scale_fac = (range > 0.0f) ? 1.0f / range : 0.0f; float soft = 1.0f - range * atanf((1.0f - bulge) * scale_fac) / (float)M_PI_2; - + bulge = interpf(soft, hard, data->bulge_smooth); } } - + switch (data->volmode) { /* volume preserving scaling */ case VOLUME_XZ: @@ -2823,7 +2823,7 @@ static void stretchto_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t default: /* should not happen, but in case*/ return; } /* switch (data->volmode) */ - + /* Clear the object's rotation and scale */ cob->matrix[0][0] = size[0] * scale[0]; cob->matrix[0][1] = 0; @@ -2834,10 +2834,10 @@ static void stretchto_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t cob->matrix[2][0] = 0; cob->matrix[2][1] = 0; cob->matrix[2][2] = size[2] * scale[2]; - + sub_v3_v3v3(vec, cob->matrix[3], ct->matrix[3]); normalize_v3(vec); - + /* new Y aligns object target connection*/ negate_v3_v3(totmat[1], vec); switch (data->plane) { @@ -2846,10 +2846,10 @@ static void stretchto_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t /* othogonal to "new Y" "old X! plane */ cross_v3_v3v3(orth, vec, xx); normalize_v3(orth); - + /* new Z*/ copy_v3_v3(totmat[2], orth); - + /* we decided to keep X plane*/ cross_v3_v3v3(xx, orth, vec); normalize_v3_v3(totmat[0], xx); @@ -2859,16 +2859,16 @@ static void stretchto_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t /* othogonal to "new Y" "old Z! plane */ cross_v3_v3v3(orth, vec, zz); normalize_v3(orth); - + /* new X */ negate_v3_v3(totmat[0], orth); - + /* we decided to keep Z */ cross_v3_v3v3(zz, orth, vec); normalize_v3_v3(totmat[2], zz); break; } /* switch (data->plane) */ - + mul_m4_m3m4(cob->matrix, totmat, cob->matrix); } } @@ -2893,7 +2893,7 @@ static bConstraintTypeInfo CTI_STRETCHTO = { static void minmax_new_data(void *cdata) { bMinMaxConstraint *data = (bMinMaxConstraint *)cdata; - + data->minmaxflag = TRACK_Z; data->offset = 0.0f; zero_v3(data->cache); @@ -2903,7 +2903,7 @@ static void minmax_new_data(void *cdata) static void minmax_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata) { bMinMaxConstraint *data = con->data; - + /* target only */ func(con, (ID **)&data->tar, false, userdata); } @@ -2913,13 +2913,13 @@ static int minmax_get_tars(bConstraint *con, ListBase *list) if (con && list) { bMinMaxConstraint *data = con->data; bConstraintTarget *ct; - + /* standard target-getting macro for single-target constraints */ SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list); - + return 1; } - + return 0; } @@ -2928,7 +2928,7 @@ static void minmax_flush_tars(bConstraint *con, ListBase *list, bool no_copy) if (con && list) { bMinMaxConstraint *data = con->data; bConstraintTarget *ct = list->first; - + /* the following macro is used for all standard single-target constraints */ SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, no_copy); } @@ -2938,16 +2938,16 @@ static void minmax_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *targ { bMinMaxConstraint *data = con->data; bConstraintTarget *ct = targets->first; - + /* only evaluate if there is a target */ if (VALID_CONS_TARGET(ct)) { float obmat[4][4], imat[4][4], tarmat[4][4], tmat[4][4]; float val1, val2; int index; - + copy_m4_m4(obmat, cob->matrix); copy_m4_m4(tarmat, ct->matrix); - + if (data->flag & MINMAX_USEROT) { /* take rotation of target into account by doing the transaction in target's localspace */ invert_m4_m4(imat, tarmat); @@ -2955,7 +2955,7 @@ static void minmax_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *targ copy_m4_m4(obmat, tmat); unit_m4(tarmat); } - + switch (data->minmaxflag) { case TRACK_Z: val1 = tarmat[3][2]; @@ -2990,7 +2990,7 @@ static void minmax_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *targ default: return; } - + if (val1 > val2) { obmat[3][index] = tarmat[3][index] + data->offset; if (data->flag & MINMAX_STICKY) { @@ -3037,7 +3037,7 @@ static bConstraintTypeInfo CTI_MINMAX = { static void clampto_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata) { bClampToConstraint *data = con->data; - + /* target only */ func(con, (ID **)&data->tar, false, userdata); } @@ -3047,13 +3047,13 @@ static int clampto_get_tars(bConstraint *con, ListBase *list) if (con && list) { bClampToConstraint *data = con->data; bConstraintTarget *ct; - + /* standard target-getting macro for single-target constraints without subtargets */ SINGLETARGETNS_GET_TARS(con, data->tar, ct, list); - + return 1; } - + return 0; } @@ -3062,7 +3062,7 @@ static void clampto_flush_tars(bConstraint *con, ListBase *list, bool no_copy) if (con && list) { bClampToConstraint *data = con->data; bConstraintTarget *ct = list->first; - + /* the following macro is used for all standard single-target constraints */ SINGLETARGETNS_FLUSH_TARS(con, data->tar, ct, list, no_copy); } @@ -3083,33 +3083,33 @@ static void clampto_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *tar { bClampToConstraint *data = con->data; bConstraintTarget *ct = targets->first; - + /* only evaluate if there is a target and it is a curve */ if (VALID_CONS_TARGET(ct) && (ct->tar->type == OB_CURVE)) { float obmat[4][4], ownLoc[3]; float curveMin[3], curveMax[3]; float targetMatrix[4][4]; - + copy_m4_m4(obmat, cob->matrix); copy_v3_v3(ownLoc, obmat[3]); - + unit_m4(targetMatrix); INIT_MINMAX(curveMin, curveMax); /* XXX - don't think this is good calling this here - campbell */ BKE_object_minmax(ct->tar, curveMin, curveMax, true); - + /* get targetmatrix */ if (data->tar->curve_cache && data->tar->curve_cache->path && data->tar->curve_cache->path->data) { float vec[4], dir[3], totmat[4][4]; float curvetime; short clamp_axis; - + /* find best position on curve */ /* 1. determine which axis to sample on? */ if (data->flag == CLAMPTO_AUTO) { float size[3]; sub_v3_v3v3(size, curveMax, curveMin); - + /* find axis along which the bounding box has the greatest * extent. Otherwise, default to the x-axis, as that is quite * frequently used. @@ -3121,15 +3121,15 @@ static void clampto_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *tar else clamp_axis = CLAMPTO_X - 1; } - else + else clamp_axis = data->flag - 1; - + /* 2. determine position relative to curve on a 0-1 scale based on bounding box */ if (data->flag2 & CLAMPTO_CYCLIC) { /* cyclic, so offset within relative bounding box is used */ float len = (curveMax[clamp_axis] - curveMin[clamp_axis]); float offset; - + /* check to make sure len is not so close to zero that it'll cause errors */ if (IS_EQF(len, 0.0f) == false) { /* find bounding-box range where target is located */ @@ -3165,19 +3165,19 @@ static void clampto_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *tar curvetime = 1.0f; else if (IS_EQF((curveMax[clamp_axis] - curveMin[clamp_axis]), 0.0f) == false) curvetime = (ownLoc[clamp_axis] - curveMin[clamp_axis]) / (curveMax[clamp_axis] - curveMin[clamp_axis]); - else + else curvetime = 0.0f; } - + /* 3. position on curve */ if (where_on_path(ct->tar, curvetime, vec, dir, NULL, NULL, NULL) ) { unit_m4(totmat); copy_v3_v3(totmat[3], vec); - + mul_m4_m4m4(targetMatrix, ct->tar->obmat, totmat); } } - + /* obtain final object position */ copy_v3_v3(cob->matrix[3], targetMatrix[3]); } @@ -3203,7 +3203,7 @@ static bConstraintTypeInfo CTI_CLAMPTO = { static void transform_new_data(void *cdata) { bTransformConstraint *data = (bTransformConstraint *)cdata; - + data->map[0] = 0; data->map[1] = 1; data->map[2] = 2; @@ -3212,7 +3212,7 @@ static void transform_new_data(void *cdata) static void transform_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata) { bTransformConstraint *data = con->data; - + /* target only */ func(con, (ID **)&data->tar, false, userdata); } @@ -3222,13 +3222,13 @@ static int transform_get_tars(bConstraint *con, ListBase *list) if (con && list) { bTransformConstraint *data = con->data; bConstraintTarget *ct; - + /* standard target-getting macro for single-target constraints */ SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list); - + return 1; } - + return 0; } @@ -3237,7 +3237,7 @@ static void transform_flush_tars(bConstraint *con, ListBase *list, bool no_copy) if (con && list) { bTransformConstraint *data = con->data; bConstraintTarget *ct = list->first; - + /* the following macro is used for all standard single-target constraints */ SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, no_copy); } @@ -3247,21 +3247,21 @@ static void transform_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t { bTransformConstraint *data = con->data; bConstraintTarget *ct = targets->first; - + /* only evaluate if there is a target */ if (VALID_CONS_TARGET(ct)) { float *from_min, *from_max, *to_min, *to_max; float loc[3], eul[3], size[3]; float dvec[3], sval[3]; int i; - + /* obtain target effect */ switch (data->from) { case TRANS_SCALE: mat4_to_size(dvec, ct->matrix); - + if (is_negative_m4(ct->matrix)) { - /* Bugfix [#27886] + /* Bugfix [#27886] * We can't be sure which axis/axes are negative, though we know that something is negative. * Assume we don't care about negativity of separate axes. <--- This is a limitation that * riggers will have to live with for now. @@ -3283,12 +3283,12 @@ static void transform_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t from_max = data->from_max; break; } - + /* extract components of owner's matrix */ copy_v3_v3(loc, cob->matrix[3]); mat4_to_eulO(eul, cob->rotOrder, cob->matrix); mat4_to_size(size, cob->matrix); - + /* determine where in range current transforms lie */ if (data->expo) { for (i = 0; i < 3; i++) { @@ -3308,8 +3308,8 @@ static void transform_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t sval[i] = 0.0f; } } - - + + /* apply transforms */ switch (data->to) { case TRANS_SCALE: @@ -3340,7 +3340,7 @@ static void transform_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t } break; } - + /* apply to matrix */ loc_eulO_size_to_mat4(cob->matrix, loc, eul, size, cob->rotOrder); } @@ -3366,7 +3366,7 @@ static bConstraintTypeInfo CTI_TRANSFORM = { static void shrinkwrap_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata) { bShrinkwrapConstraint *data = con->data; - + /* target only */ func(con, (ID **)&data->target, false, userdata); } @@ -3384,12 +3384,12 @@ static int shrinkwrap_get_tars(bConstraint *con, ListBase *list) if (con && list) { bShrinkwrapConstraint *data = con->data; bConstraintTarget *ct; - + SINGLETARGETNS_GET_TARS(con, data->target, ct, list); - + return 1; } - + return 0; } @@ -3399,7 +3399,7 @@ static void shrinkwrap_flush_tars(bConstraint *con, ListBase *list, bool no_copy if (con && list) { bShrinkwrapConstraint *data = con->data; bConstraintTarget *ct = list->first; - + SINGLETARGETNS_FLUSH_TARS(con, data->target, ct, list, no_copy); } } @@ -3408,22 +3408,22 @@ static void shrinkwrap_flush_tars(bConstraint *con, ListBase *list, bool no_copy static void shrinkwrap_get_tarmat(struct Depsgraph *UNUSED(depsgraph), bConstraint *con, bConstraintOb *cob, bConstraintTarget *ct, float UNUSED(ctime)) { bShrinkwrapConstraint *scon = (bShrinkwrapConstraint *) con->data; - + if (VALID_CONS_TARGET(ct) && (ct->tar->type == OB_MESH) ) { bool fail = false; float co[3] = {0.0f, 0.0f, 0.0f}; - + SpaceTransform transform; /* TODO(sergey): use proper for_render flag here when known. */ DerivedMesh *target = object_get_derived_final(ct->tar, false); - + BVHTreeFromMesh treeData = {NULL}; - + unit_m4(ct->matrix); - + if (target != NULL) { BLI_space_transform_from_matrices(&transform, cob->matrix, ct->tar->obmat); - + switch (scon->shrinkType) { case MOD_SHRINKWRAP_NEAREST_SURFACE: case MOD_SHRINKWRAP_NEAREST_VERTEX: @@ -3438,16 +3438,16 @@ static void shrinkwrap_get_tarmat(struct Depsgraph *UNUSED(depsgraph), bConstrai bvhtree_from_mesh_get(&treeData, target, BVHTREE_FROM_VERTS, 2); else bvhtree_from_mesh_get(&treeData, target, BVHTREE_FROM_LOOPTRI, 2); - + if (treeData.tree == NULL) { fail = true; break; } - + BLI_space_transform_apply(&transform, co); - + BLI_bvhtree_find_nearest(treeData.tree, co, &nearest, treeData.nearest_callback, &treeData); - + dist = len_v3v3(co, nearest.co); if (dist != 0.0f) { interp_v3_v3v3(co, co, nearest.co, (dist - scon->dist) / dist); /* linear interpolation */ @@ -3474,7 +3474,7 @@ static void shrinkwrap_get_tarmat(struct Depsgraph *UNUSED(depsgraph), bConstrai no[scon->projAxis - OB_NEGX] = -1.0f; break; } - + /* transform normal into requested space */ /* Note that in this specific case, we need to keep scaling in non-parented 'local2world' object * case, because SpaceTransform also takes it into account when handling normals. See T42447. */ @@ -3505,14 +3505,14 @@ static void shrinkwrap_get_tarmat(struct Depsgraph *UNUSED(depsgraph), bConstrai break; } } - + free_bvhtree_from_mesh(&treeData); - + if (fail == true) { /* Don't move the point */ zero_v3(co); } - + /* co is in local object coordinates, change it to global and update target position */ mul_m4_v3(cob->matrix, co); copy_v3_v3(ct->matrix[3], co); @@ -3523,7 +3523,7 @@ static void shrinkwrap_get_tarmat(struct Depsgraph *UNUSED(depsgraph), bConstrai static void shrinkwrap_evaluate(bConstraint *UNUSED(con), bConstraintOb *cob, ListBase *targets) { bConstraintTarget *ct = targets->first; - + /* only evaluate if there is a target */ if (VALID_CONS_TARGET(ct)) { copy_v3_v3(cob->matrix[3], ct->matrix[3]); @@ -3550,14 +3550,14 @@ static bConstraintTypeInfo CTI_SHRINKWRAP = { static void damptrack_new_data(void *cdata) { bDampTrackConstraint *data = (bDampTrackConstraint *)cdata; - + data->trackflag = TRACK_Y; -} +} static void damptrack_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata) { bDampTrackConstraint *data = con->data; - + /* target only */ func(con, (ID **)&data->tar, false, userdata); } @@ -3567,13 +3567,13 @@ static int damptrack_get_tars(bConstraint *con, ListBase *list) if (con && list) { bDampTrackConstraint *data = con->data; bConstraintTarget *ct; - + /* the following macro is used for all standard single-target constraints */ SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list); - + return 1; } - + return 0; } @@ -3582,7 +3582,7 @@ static void damptrack_flush_tars(bConstraint *con, ListBase *list, bool no_copy) if (con && list) { bDampTrackConstraint *data = con->data; bConstraintTarget *ct = list->first; - + /* the following macro is used for all standard single-target constraints */ SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, no_copy); } @@ -3598,60 +3598,60 @@ static void damptrack_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t { bDampTrackConstraint *data = con->data; bConstraintTarget *ct = targets->first; - + if (VALID_CONS_TARGET(ct)) { float obvec[3], tarvec[3], obloc[3]; float raxis[3], rangle; float rmat[3][3], tmat[4][4]; - - /* find the (unit) direction that the axis we're interested in currently points - * - mul_mat3_m4_v3() only takes the 3x3 (rotation+scaling) components of the 4x4 matrix + + /* find the (unit) direction that the axis we're interested in currently points + * - mul_mat3_m4_v3() only takes the 3x3 (rotation+scaling) components of the 4x4 matrix * - the normalization step at the end should take care of any unwanted scaling * left over in the 3x3 matrix we used */ copy_v3_v3(obvec, track_dir_vecs[data->trackflag]); mul_mat3_m4_v3(cob->matrix, obvec); - + if (normalize_v3(obvec) == 0.0f) { /* exceptional case - just use the track vector as appropriate */ copy_v3_v3(obvec, track_dir_vecs[data->trackflag]); } - + /* find the (unit) direction vector going from the owner to the target */ copy_v3_v3(obloc, cob->matrix[3]); sub_v3_v3v3(tarvec, ct->matrix[3], obloc); - + if (normalize_v3(tarvec) == 0.0f) { /* the target is sitting on the owner, so just make them use the same direction vectors */ /* FIXME: or would it be better to use the pure direction vector? */ copy_v3_v3(tarvec, obvec); //copy_v3_v3(tarvec, track_dir_vecs[data->trackflag]); } - + /* determine the axis-angle rotation, which represents the smallest possible rotation * between the two rotation vectors (i.e. the 'damping' referred to in the name) * - we take this to be the rotation around the normal axis/vector to the plane defined - * by the current and destination vectors, which will 'map' the current axis to the + * by the current and destination vectors, which will 'map' the current axis to the * destination vector * - the min/max wrappers around (obvec . tarvec) result (stored temporarily in rangle) * are used to ensure that the smallest angle is chosen */ cross_v3_v3v3(raxis, obvec, tarvec); - + rangle = dot_v3v3(obvec, tarvec); rangle = acosf(max_ff(-1.0f, min_ff(1.0f, rangle))); - - /* construct rotation matrix from the axis-angle rotation found above + + /* construct rotation matrix from the axis-angle rotation found above * - this call takes care to make sure that the axis provided is a unit vector first */ axis_angle_to_mat3(rmat, raxis, rangle); - + /* rotate the owner in the way defined by this rotation matrix, then reapply the location since * we may have destroyed that in the process of multiplying the matrix */ unit_m4(tmat); mul_m4_m3m4(tmat, rmat, cob->matrix); // m1, m3, m2 - + copy_m4_m4(cob->matrix, tmat); copy_v3_v3(cob->matrix[3], obloc); } @@ -3677,17 +3677,17 @@ static bConstraintTypeInfo CTI_DAMPTRACK = { static void splineik_free(bConstraint *con) { bSplineIKConstraint *data = con->data; - + /* binding array */ if (data->points) MEM_freeN(data->points); -} +} static void splineik_copy(bConstraint *con, bConstraint *srccon) { bSplineIKConstraint *src = srccon->data; bSplineIKConstraint *dst = con->data; - + /* copy the binding array */ dst->points = MEM_dupallocN(src->points); } @@ -3705,7 +3705,7 @@ static void splineik_new_data(void *cdata) static void splineik_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata) { bSplineIKConstraint *data = con->data; - + /* target only */ func(con, (ID **)&data->tar, false, userdata); } @@ -3715,13 +3715,13 @@ static int splineik_get_tars(bConstraint *con, ListBase *list) if (con && list) { bSplineIKConstraint *data = con->data; bConstraintTarget *ct; - + /* standard target-getting macro for single-target constraints without subtargets */ SINGLETARGETNS_GET_TARS(con, data->tar, ct, list); - + return 1; } - + return 0; } @@ -3730,7 +3730,7 @@ static void splineik_flush_tars(bConstraint *con, ListBase *list, bool no_copy) if (con && list) { bSplineIKConstraint *data = con->data; bConstraintTarget *ct = list->first; - + /* the following macro is used for all standard single-target constraints */ SINGLETARGETNS_FLUSH_TARS(con, data->tar, ct, list, no_copy); } @@ -3767,7 +3767,7 @@ static bConstraintTypeInfo CTI_SPLINEIK = { static void pivotcon_id_looper(bConstraint *con, ConstraintIDFunc func, void *userdata) { bPivotConstraint *data = con->data; - + /* target only */ func(con, (ID **)&data->tar, false, userdata); } @@ -3777,13 +3777,13 @@ static int pivotcon_get_tars(bConstraint *con, ListBase *list) if (con && list) { bPivotConstraint *data = con->data; bConstraintTarget *ct; - + /* standard target-getting macro for single-target constraints */ SINGLETARGET_GET_TARS(con, data->tar, data->subtarget, ct, list); - + return 1; } - + return 0; } @@ -3792,7 +3792,7 @@ static void pivotcon_flush_tars(bConstraint *con, ListBase *list, bool no_copy) if (con && list) { bPivotConstraint *data = con->data; bConstraintTarget *ct = list->first; - + /* the following macro is used for all standard single-target constraints */ SINGLETARGET_FLUSH_TARS(con, data->tar, data->subtarget, ct, list, no_copy); } @@ -3802,20 +3802,20 @@ static void pivotcon_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *ta { bPivotConstraint *data = con->data; bConstraintTarget *ct = targets->first; - + float pivot[3], vec[3]; float rotMat[3][3]; /* pivot correction */ float axis[3], angle; - + /* firstly, check if pivoting should take place based on the current rotation */ if (data->rotAxis != PIVOTCON_AXIS_NONE) { float rot[3]; - + /* extract euler-rotation of target */ mat4_to_eulO(rot, cob->rotOrder, cob->matrix); - + /* check which range might be violated */ if (data->rotAxis < PIVOTCON_AXIS_X) { /* negative rotations (data->rotAxis = 0 -> 2) */ @@ -3828,7 +3828,7 @@ static void pivotcon_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *ta return; } } - + /* find the pivot-point to use */ if (VALID_CONS_TARGET(ct)) { /* apply offset to target location */ @@ -3845,7 +3845,7 @@ static void pivotcon_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *ta copy_v3_v3(pivot, data->offset); } } - + /* get rotation matrix representing the rotation of the owner */ /* TODO: perhaps we might want to include scaling based on the pivot too? */ copy_m3_m4(rotMat, cob->matrix); @@ -4413,7 +4413,7 @@ const bConstraintTypeInfo *BKE_constraint_typeinfo_from_type(int type) constraints_init_typeinfo(); CTI_INIT = 0; } - + /* only return for valid types */ if ((type >= CONSTRAINT_TYPE_NULL) && (type < NUM_CONSTRAINT_TYPES)) @@ -4424,10 +4424,10 @@ const bConstraintTypeInfo *BKE_constraint_typeinfo_from_type(int type) else { printf("No valid constraint type-info data available. Type = %i\n", type); } - + return NULL; -} - +} + /* This function should always be used to get the appropriate type-info, as it * has checks which prevent segfaults in some weird cases. */ @@ -4444,7 +4444,7 @@ const bConstraintTypeInfo *BKE_constraint_typeinfo_get(bConstraint *con) /* The functions here are called by various parts of Blender. Very few (should be none if possible) * constraint-specific code should occur here. */ - + /* ---------- Data Management ------- */ /* helper function for BKE_constraint_free_data() - unlinks references */ @@ -4462,17 +4462,17 @@ void BKE_constraint_free_data_ex(bConstraint *con, bool do_id_user) { if (con->data) { const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con); - + if (cti) { /* perform any special freeing constraint may have */ if (cti->free_data) cti->free_data(con); - + /* unlink the referenced resources it uses */ if (do_id_user && cti->id_looper) cti->id_looper(con, con_unlink_refs_cb, NULL); } - + /* free constraint data now */ MEM_freeN(con->data); } @@ -4487,11 +4487,11 @@ void BKE_constraint_free_data(bConstraint *con) void BKE_constraints_free_ex(ListBase *list, bool do_id_user) { bConstraint *con; - + /* Free constraint data and also any extra data */ for (con = list->first; con; con = con->next) BKE_constraint_free_data_ex(con, do_id_user); - + /* Free the whole list */ BLI_freelistN(list); } @@ -4547,11 +4547,11 @@ static bConstraint *add_new_constraint_internal(const char *name, short type) if (cti) { /* initialize constraint data */ con->data = MEM_callocN(cti->size, cti->structName); - + /* only constraints that change any settings need this */ if (cti->new_data) cti->new_data(con->data); - + /* if no name is provided, use the type of the constraint as the name */ newName = (name && name[0]) ? name : DATA_(cti->name); } @@ -4560,10 +4560,10 @@ static bConstraint *add_new_constraint_internal(const char *name, short type) /* NOTE: any constraint type that gets here really shouldn't get added... */ newName = (name && name[0]) ? name : DATA_("Const"); } - + /* copy the name */ BLI_strncpy(con->name, newName, sizeof(con->name)); - + /* return the new constraint */ return con; } @@ -4573,27 +4573,27 @@ static bConstraint *add_new_constraint(Object *ob, bPoseChannel *pchan, const ch { bConstraint *con; ListBase *list; - + /* add the constraint */ con = add_new_constraint_internal(name, type); - + /* find the constraint stack - bone or object? */ list = (pchan) ? (&pchan->constraints) : (&ob->constraints); - + if (list) { /* add new constraint to end of list of constraints before ensuring that it has a unique name * (otherwise unique-naming code will fail, since it assumes element exists in list) */ BLI_addtail(list, con); BKE_constraint_unique_name(con, list); - + /* if the target list is a list on some PoseChannel belonging to a proxy-protected * Armature layer, we must tag newly added constraints with a flag which allows them * to persist after proxy syncing has been done */ if (BKE_constraints_proxylocked_owner(ob, pchan)) con->flag |= CONSTRAINT_PROXY_LOCAL; - + /* make this constraint the active one */ BKE_constraints_active_set(list, con); } @@ -4612,7 +4612,7 @@ static bConstraint *add_new_constraint(Object *ob, bPoseChannel *pchan, const ch break; } } - + return con; } @@ -4623,7 +4623,7 @@ bConstraint *BKE_constraint_add_for_pose(Object *ob, bPoseChannel *pchan, const { if (pchan == NULL) return NULL; - + return add_new_constraint(ob, pchan, name, type); } @@ -4639,10 +4639,10 @@ bConstraint *BKE_constraint_add_for_object(Object *ob, const char *name, short t void BKE_constraints_id_loop(ListBase *conlist, ConstraintIDFunc func, void *userdata) { bConstraint *con; - + for (con = conlist->first; con; con = con->next) { const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con); - + if (cti) { if (cti->id_looper) cti->id_looper(con, func, userdata); @@ -4733,7 +4733,7 @@ bConstraint *BKE_constraints_find_name(ListBase *list, const char *name) bConstraint *BKE_constraints_active_get(ListBase *list) { bConstraint *con; - + /* search for the first constraint with the 'active' flag set */ if (list) { for (con = list->first; con; con = con->next) { @@ -4741,7 +4741,7 @@ bConstraint *BKE_constraints_active_get(ListBase *list) return con; } } - + /* no active constraint found */ return NULL; } @@ -4750,12 +4750,12 @@ bConstraint *BKE_constraints_active_get(ListBase *list) void BKE_constraints_active_set(ListBase *list, bConstraint *con) { bConstraint *c; - + if (list) { for (c = list->first; c; c = c->next) { - if (c == con) + if (c == con) c->flag |= CONSTRAINT_ACTIVE; - else + else c->flag &= ~CONSTRAINT_ACTIVE; } } @@ -4767,11 +4767,11 @@ void BKE_constraints_active_set(ListBase *list, bConstraint *con) void BKE_constraints_proxylocal_extract(ListBase *dst, ListBase *src) { bConstraint *con, *next; - + /* for each tagged constraint, remove from src and move to dst */ for (con = src->first; con; con = next) { next = con->next; - + /* check if tagged */ if (con->flag & CONSTRAINT_PROXY_LOCAL) { BLI_remlink(src, con); @@ -4787,7 +4787,7 @@ bool BKE_constraints_proxylocked_owner(Object *ob, bPoseChannel *pchan) if (ob && ob->proxy) { if (ob->pose && pchan) { bArmature *arm = ob->data; - + /* On bone-level, check if bone is on proxy-protected layer */ if ((pchan->bone) && (pchan->bone->layer & arm->layer_protected)) return true; @@ -4797,7 +4797,7 @@ bool BKE_constraints_proxylocked_owner(Object *ob, bPoseChannel *pchan) return true; } } - + return false; } @@ -4816,7 +4816,7 @@ void BKE_constraint_target_matrix_get(struct Depsgraph *depsgraph, Scene *scene, ListBase targets = {NULL, NULL}; bConstraintOb *cob; bConstraintTarget *ct; - + if (cti && cti->get_constraint_targets) { /* make 'constraint-ob' */ cob = MEM_callocN(sizeof(bConstraintOb), "tempConstraintOb"); @@ -4853,19 +4853,19 @@ void BKE_constraint_target_matrix_get(struct Depsgraph *depsgraph, Scene *scene, break; } } - + /* get targets - we only need the first one though (and there should only be one) */ cti->get_constraint_targets(con, &targets); - + /* only calculate the target matrix on the first target */ ct = (bConstraintTarget *)BLI_findlink(&targets, index); - + if (ct) { if (cti->get_target_matrix) cti->get_target_matrix(depsgraph, con, cob, ct, ctime); copy_m4_m4(mat, ct->matrix); } - + /* free targets + 'constraint-ob' */ if (cti->flush_constraint_targets) cti->flush_constraint_targets(con, &targets, 1); @@ -4881,17 +4881,17 @@ void BKE_constraint_target_matrix_get(struct Depsgraph *depsgraph, Scene *scene, void BKE_constraint_targets_for_solving_get(struct Depsgraph *depsgraph, bConstraint *con, bConstraintOb *cob, ListBase *targets, float ctime) { const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con); - + if (cti && cti->get_constraint_targets) { bConstraintTarget *ct; - - /* get targets + + /* get targets * - constraints should use ct->matrix, not directly accessing values - * - ct->matrix members have not yet been calculated here! + * - ct->matrix members have not yet been calculated here! */ cti->get_constraint_targets(con, targets); - - /* set matrices + + /* set matrices * - calculate if possible, otherwise just initialize as identity matrix */ if (cti->get_target_matrix) { @@ -4904,7 +4904,7 @@ void BKE_constraint_targets_for_solving_get(struct Depsgraph *depsgraph, bConstr } } } - + /* ---------- Evaluation ----------- */ /* This function is called whenever constraints need to be evaluated. Currently, all @@ -4922,12 +4922,12 @@ void BKE_constraints_solve(struct Depsgraph *depsgraph, ListBase *conlist, bCons /* check that there is a valid constraint object to evaluate */ if (cob == NULL) return; - + /* loop over available constraints, solving and blending them */ for (con = conlist->first; con; con = con->next) { const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con); ListBase targets = {NULL, NULL}; - + /* these we can skip completely (invalid constraints...) */ if (cti == NULL) continue; if (con->flag & (CONSTRAINT_DISABLE | CONSTRAINT_OFF)) continue; @@ -4935,37 +4935,37 @@ void BKE_constraints_solve(struct Depsgraph *depsgraph, ListBase *conlist, bCons if (cti->evaluate_constraint == NULL) continue; /* influence == 0 should be ignored */ if (con->enforce == 0.0f) continue; - + /* influence of constraint * - value should have been set from animation data already */ enf = con->enforce; - + /* make copy of worldspace matrix pre-constraint for use with blending later */ copy_m4_m4(oldmat, cob->matrix); - + /* move owner matrix into right space */ BKE_constraint_mat_convertspace(cob->ob, cob->pchan, cob->matrix, CONSTRAINT_SPACE_WORLD, con->ownspace, false); - + /* prepare targets for constraint solving */ BKE_constraint_targets_for_solving_get(depsgraph, con, cob, &targets, ctime); - + /* Solve the constraint and put result in cob->matrix */ cti->evaluate_constraint(con, cob, &targets); - - /* clear targets after use + + /* clear targets after use * - this should free temp targets but no data should be copied back * as constraints may have done some nasty things to it... */ if (cti->flush_constraint_targets) { cti->flush_constraint_targets(con, &targets, 1); } - + /* move owner back into worldspace for next constraint/other business */ - if ((con->flag & CONSTRAINT_SPACEONCE) == 0) + if ((con->flag & CONSTRAINT_SPACEONCE) == 0) BKE_constraint_mat_convertspace(cob->ob, cob->pchan, cob->matrix, con->ownspace, CONSTRAINT_SPACE_WORLD, false); - - /* Interpolate the enforcement, to blend result of constraint into final owner transform + + /* Interpolate the enforcement, to blend result of constraint into final owner transform * - all this happens in worldspace to prevent any weirdness creeping in ([#26014] and [#25725]), * since some constraints may not convert the solution back to the input space before blending * but all are guaranteed to end up in good "worldspace" result diff --git a/source/blender/blenkernel/intern/context.c b/source/blender/blenkernel/intern/context.c index 6314486d809..ee907fa496f 100644 --- a/source/blender/blenkernel/intern/context.c +++ b/source/blender/blenkernel/intern/context.c @@ -84,7 +84,7 @@ struct bContext { struct bContextStore *store; const char *operator_poll_msg; /* reason for poll failing */ } wm; - + /* data context */ struct { struct Main *main; @@ -94,7 +94,7 @@ struct bContext { int py_init; /* true if python is initialized */ void *py_context; } data; - + /* data evaluation */ #if 0 struct { @@ -108,7 +108,7 @@ struct bContext { bContext *CTX_create(void) { bContext *C; - + C = MEM_callocN(sizeof(bContext), "bContext"); return C; @@ -424,7 +424,7 @@ PointerRNA CTX_data_pointer_get_type(const bContext *C, const char *member, Stru __func__, member, RNA_struct_identifier(ptr.type), RNA_struct_identifier(type)); } } - + return PointerRNA_NULL; } @@ -465,13 +465,13 @@ int CTX_data_get(const bContext *C, const char *member, PointerRNA *r_ptr, ListB static void data_dir_add(ListBase *lb, const char *member, const bool use_all) { LinkData *link; - + if ((use_all == false) && STREQ(member, "scene")) /* exception */ return; if (BLI_findstring(lb, member, offsetof(LinkData, data))) return; - + link = MEM_callocN(sizeof(LinkData), "LinkData"); link->data = (void *)member; BLI_addtail(lb, link); diff --git a/source/blender/blenkernel/intern/curve.c b/source/blender/blenkernel/intern/curve.c index 01da9857864..f6dd630e077 100644 --- a/source/blender/blenkernel/intern/curve.c +++ b/source/blender/blenkernel/intern/curve.c @@ -1028,7 +1028,7 @@ static void basisNurb(float t, short order, int pnts, float *knots, float *basis /* this is for float inaccuracy */ if (t < knots[0]) t = knots[0]; - else if (t > knots[opp2]) + else if (t > knots[opp2]) t = knots[opp2]; /* this part is order '1' */ @@ -2138,7 +2138,7 @@ static void alfa_bezpart(BezTriple *prevbezt, BezTriple *bezt, Nurb *nu, float * if (tilt_array == NULL || nu->tilt_interp != nu->radius_interp) { key_curve_position_weights(fac, t, nu->radius_interp); } - *radius_array = + *radius_array = t[0] * pprev->radius + t[1] * prevbezt->radius + t[2] * bezt->radius + t[3] * next->radius; } @@ -2148,7 +2148,7 @@ static void alfa_bezpart(BezTriple *prevbezt, BezTriple *bezt, Nurb *nu, float * if (weight_array) { /* basic interpolation for now, could copy tilt interp too */ - *weight_array = + *weight_array = prevbezt->weight + (bezt->weight - prevbezt->weight) * (3.0f * fac * fac - 2.0f * fac * fac * fac); @@ -2683,10 +2683,10 @@ void BKE_curve_bevelList_make(Object *ob, ListBase *nurbs, bool for_render) } for (; nu; nu = nu->next) { - + if (nu->hide && is_editmode) continue; - + /* check if we will calculate tilt data */ do_tilt = CU_DO_TILT(cu, nu); do_radius = CU_DO_RADIUS(cu, nu); /* normal display uses the radius, better just to calculate them */ @@ -4962,7 +4962,7 @@ bool BKE_curve_minmax(Curve *cu, bool use_radius, float min[3], float max[3]) */ if (is_font) { nurb_lb = &temp_nurb_lb; - BKE_vfont_to_curve_ex(G.main, NULL, cu, FO_EDIT, nurb_lb, + BKE_vfont_to_curve_ex(NULL, cu, FO_EDIT, nurb_lb, NULL, NULL, NULL, NULL); use_radius = false; } diff --git a/source/blender/blenkernel/intern/customdata.c b/source/blender/blenkernel/intern/customdata.c index aa67eafaa98..b9328051699 100644 --- a/source/blender/blenkernel/intern/customdata.c +++ b/source/blender/blenkernel/intern/customdata.c @@ -526,7 +526,7 @@ static void layerSwap_mdisps(void *data, const int *ci) for (S = 0; S < corners; S++) memcpy(d + cornersize * S, s->disps + cornersize * ci[S], cornersize * 3 * sizeof(float)); - + MEM_freeN(s->disps); s->disps = d; } @@ -631,7 +631,7 @@ static void layerCopy_grid_paint_mask(const void *source, void *dest, int count) d[i].data = NULL; d[i].level = 0; } - + } } @@ -742,7 +742,7 @@ static void layerDoMinMax_mloopcol(const void *data, void *vmin, void *vmax) if (m->g < min->g) min->g = m->g; if (m->b < min->b) min->b = m->b; if (m->a < min->a) min->a = m->a; - + if (m->r > max->r) max->r = m->r; if (m->g > max->g) max->g = m->g; if (m->b > max->b) max->b = m->b; @@ -1005,7 +1005,7 @@ static void layerInterp_mcol( const float *sub_weight; if (count <= 0) return; - + sub_weight = sub_weights; for (i = 0; i < count; ++i) { float weight = weights ? weights[i] : 1; @@ -1033,7 +1033,7 @@ static void layerInterp_mcol( /* delay writing to the destination incase dest is in sources */ for (j = 0; j < 4; ++j) { - + /* Subdivide smooth or fractal can cause problems without clamping * although weights should also not cause this situation */ mc[j].a = round_fl_to_uchar_clamp(col[j].a); @@ -1078,7 +1078,7 @@ static void layerInterp_bweight( float f; float **in = (float **)sources; int i; - + if (count <= 0) return; f = 0.0f; @@ -1129,7 +1129,7 @@ static void layerDefault_mvert_skin(void *data, int count) { MVertSkin *vs = data; int i; - + for (i = 0; i < count; i++) { copy_v3_fl(vs[i].radius, 0.25f); vs[i].flag = 0; @@ -1224,18 +1224,18 @@ static const LayerTypeInfo LAYERTYPEINFO[CD_NUMTYPES] = { {sizeof(int), "", 0, NULL, NULL, NULL, NULL, NULL, NULL}, /* 16: CD_MLOOPUV */ {sizeof(MLoopUV), "MLoopUV", 1, N_("UVMap"), NULL, NULL, layerInterp_mloopuv, NULL, NULL, - layerEqual_mloopuv, layerMultiply_mloopuv, layerInitMinMax_mloopuv, + layerEqual_mloopuv, layerMultiply_mloopuv, layerInitMinMax_mloopuv, layerAdd_mloopuv, layerDoMinMax_mloopuv, layerCopyValue_mloopuv, NULL, NULL, NULL, layerMaxNum_tface}, /* 17: CD_MLOOPCOL */ {sizeof(MLoopCol), "MLoopCol", 1, N_("Col"), NULL, NULL, layerInterp_mloopcol, NULL, - layerDefault_mloopcol, layerEqual_mloopcol, layerMultiply_mloopcol, layerInitMinMax_mloopcol, + layerDefault_mloopcol, layerEqual_mloopcol, layerMultiply_mloopcol, layerInitMinMax_mloopcol, layerAdd_mloopcol, layerDoMinMax_mloopcol, layerCopyValue_mloopcol, NULL, NULL, NULL, layerMaxNum_mloopcol}, /* 18: CD_TANGENT */ {sizeof(float) * 4 * 4, "", 0, N_("Tangent"), NULL, NULL, NULL, NULL, NULL}, /* 19: CD_MDISPS */ {sizeof(MDisps), "MDisps", 1, NULL, layerCopy_mdisps, layerFree_mdisps, NULL, layerSwap_mdisps, NULL, - NULL, NULL, NULL, NULL, NULL, NULL, + NULL, NULL, NULL, NULL, NULL, NULL, layerRead_mdisps, layerWrite_mdisps, layerFilesize_mdisps}, /* 20: CD_PREVIEW_MCOL */ {sizeof(MCol) * 4, "MCol", 4, N_("PreviewCol"), NULL, NULL, layerInterp_mcol, @@ -1480,10 +1480,10 @@ bool CustomData_merge( else { newlayer = customData_add_layer__internal(dest, type, alloctype, data, totelem, layer->name); } - + if (newlayer) { newlayer->uid = layer->uid; - + newlayer->active = lastactive; newlayer->active_rnd = lastrender; newlayer->active_clone = lastclone; @@ -1562,7 +1562,7 @@ void CustomData_free(CustomData *data, int totelem) if (data->layers) MEM_freeN(data->layers); - + CustomData_external_free(data); CustomData_reset(data); } @@ -1866,7 +1866,7 @@ static CustomDataLayer *customData_add_layer__internal( return NULL; } } - + data->totlayer++; /* keep layers ordered by type */ @@ -1896,7 +1896,7 @@ static CustomDataLayer *customData_add_layer__internal( data->layers[index].active_clone = 0; data->layers[index].active_mask = 0; } - + customData_update_offsets(data); return &data->layers[index]; @@ -1908,7 +1908,7 @@ void *CustomData_add_layer( { CustomDataLayer *layer; const LayerTypeInfo *typeInfo = layerType_getInfo(type); - + layer = customData_add_layer__internal(data, type, alloctype, layerdata, totelem, typeInfo->defaultname); CustomData_update_typemap(data); @@ -1925,7 +1925,7 @@ void *CustomData_add_layer_named( void *layerdata, int totelem, const char *name) { CustomDataLayer *layer; - + layer = customData_add_layer__internal(data, type, alloctype, layerdata, totelem, name); CustomData_update_typemap(data); @@ -2010,7 +2010,7 @@ int CustomData_number_of_layers(const CustomData *data, int type) for (i = 0; i < data->totlayer; i++) if (data->layers[i].type == type) number++; - + return number; } @@ -2229,7 +2229,7 @@ void CustomData_copy_data(const CustomData *source, CustomData *dest, /* if we found a matching layer, copy the data */ if (dest->layers[dest_i].type == source->layers[src_i].type) { CustomData_copy_data_layer(source, dest, src_i, dest_i, source_index, dest_index, count); - + /* if there are multiple source & dest layers of the same type, * we don't want to copy all source layers to the same dest, so * increment dest_i @@ -2367,7 +2367,7 @@ void CustomData_swap(struct CustomData *data, const int index_a, const int index void *CustomData_get(const CustomData *data, int index, int type) { int layer_index; - + BLI_assert(index >= 0); /* get the layer index of the active layer of type */ @@ -2446,9 +2446,9 @@ bool CustomData_set_layer_name(const CustomData *data, int type, int n, const ch if ((layer_index == -1) || !name) return false; - + BLI_strncpy(data->layers[layer_index].name, name, sizeof(data->layers[layer_index].name)); - + return true; } @@ -2836,7 +2836,7 @@ void CustomData_bmesh_copy_data(const CustomData *source, CustomData *dest, if (*dest_block) memset(*dest_block, 0, dest->totsize); } - + /* copies a layer at a time */ dest_i = 0; for (src_i = 0; src_i < source->totlayer; ++src_i) { @@ -2878,7 +2878,7 @@ void CustomData_bmesh_copy_data(const CustomData *source, CustomData *dest, void *CustomData_bmesh_get(const CustomData *data, void *block, int type) { int layer_index; - + /* get the layer index of the first layer of type */ layer_index = CustomData_get_active_layer_index(data, type); if (layer_index == -1) return NULL; @@ -2889,7 +2889,7 @@ void *CustomData_bmesh_get(const CustomData *data, void *block, int type) void *CustomData_bmesh_get_n(const CustomData *data, void *block, int type, int n) { int layer_index; - + /* get the layer index of the first layer of type */ layer_index = CustomData_get_layer_index(data, type); if (layer_index == -1) return NULL; @@ -2908,13 +2908,13 @@ void *CustomData_bmesh_get_layer_n(const CustomData *data, void *block, int n) bool CustomData_layer_has_math(const struct CustomData *data, int layer_n) { const LayerTypeInfo *typeInfo = layerType_getInfo(data->layers[layer_n].type); - - if (typeInfo->equal && typeInfo->add && typeInfo->multiply && + + if (typeInfo->equal && typeInfo->add && typeInfo->multiply && typeInfo->initminmax && typeInfo->dominmax) { return true; } - + return false; } @@ -3187,7 +3187,7 @@ void CustomData_to_bmesh_block(const CustomData *source, CustomData *dest, if (*dest_block == NULL) CustomData_bmesh_alloc_block(dest, dest_block); - + /* copies a layer at a time */ dest_i = 0; for (src_i = 0; src_i < source->totlayer; ++src_i) { @@ -3389,7 +3389,7 @@ static bool cd_layer_find_dupe(CustomData *data, const char *name, int type, int for (i = 0; i < data->totlayer; i++) { if (i != index) { CustomDataLayer *layer = &data->layers[i]; - + if (CustomData_is_property_layer(type)) { if (CustomData_is_property_layer(layer->type) && STREQ(layer->name, name)) { return true; @@ -3402,7 +3402,7 @@ static bool cd_layer_find_dupe(CustomData *data, const char *name, int type, int } } } - + return false; } @@ -3413,7 +3413,7 @@ static bool customdata_unique_check(void *arg, const char *name) } void CustomData_set_layer_unique_name(CustomData *data, int index) -{ +{ CustomDataLayer *nlayer = &data->layers[index]; const LayerTypeInfo *typeInfo = layerType_getInfo(nlayer->type); @@ -3483,7 +3483,7 @@ bool CustomData_verify_versions(struct CustomData *data, int index) static void customdata_external_filename(char filename[FILE_MAX], ID *id, CustomDataExternal *external) { BLI_strncpy(filename, external->filename, FILE_MAX); - BLI_path_abs(filename, ID_BLEND_PATH(G.main, id)); + BLI_path_abs(filename, ID_BLEND_PATH_FROM_GLOBAL(id)); } void CustomData_external_reload(CustomData *data, ID *UNUSED(id), CustomDataMask mask, int totelem) @@ -3519,7 +3519,7 @@ void CustomData_external_read(CustomData *data, ID *id, CustomDataMask mask, int if (!external) return; - + for (i = 0; i < data->totlayer; i++) { layer = &data->layers[i]; typeInfo = layerType_getInfo(layer->type); diff --git a/source/blender/blenkernel/intern/customdata_file.c b/source/blender/blenkernel/intern/customdata_file.c index d17c9ef5cc6..aa762865a2a 100644 --- a/source/blender/blenkernel/intern/customdata_file.c +++ b/source/blender/blenkernel/intern/customdata_file.c @@ -115,7 +115,7 @@ static int cdf_data_type_size(int datatype) { if (datatype == CDF_DATA_FLOAT) return sizeof(float); - + return 0; } #endif @@ -156,7 +156,7 @@ static int cdf_read_header(CDataFile *cdf) if (!fread(header, sizeof(CDataFileHeader), 1, cdf->readf)) return 0; - + if (memcmp(header->ID, "BCDF", sizeof(header->ID)) != 0) return 0; if (header->version > CDF_VERSION) @@ -179,7 +179,7 @@ static int cdf_read_header(CDataFile *cdf) if (fseek(f, offset, SEEK_SET) != 0) return 0; - + if (header->type == CDF_TYPE_IMAGE) { image = &cdf->btype.image; if (!fread(image, sizeof(CDataFileImageHeader), 1, f)) @@ -258,7 +258,7 @@ static int cdf_write_header(CDataFile *cdf) if (!fwrite(header, sizeof(CDataFileHeader), 1, f)) return 0; - + if (header->type == CDF_TYPE_IMAGE) { image = &cdf->btype.image; if (!fwrite(image, sizeof(CDataFileImageHeader), 1, f)) @@ -287,7 +287,7 @@ bool cdf_read_open(CDataFile *cdf, const char *filename) f = BLI_fopen(filename, "rb"); if (!f) return 0; - + cdf->readf = f; if (!cdf_read_header(cdf)) { @@ -352,7 +352,7 @@ bool cdf_write_open(CDataFile *cdf, const char *filename) f = BLI_fopen(filename, "wb"); if (!f) return 0; - + cdf->writef = f; /* fill header */ @@ -424,7 +424,7 @@ CDataFileLayer *cdf_layer_find(CDataFile *cdf, int type, const char *name) if (layer->type == type && STREQ(layer->name, name)) return layer; } - + return NULL; } diff --git a/source/blender/blenkernel/intern/deform.c b/source/blender/blenkernel/intern/deform.c index d4ff9bd5c0c..2da157d5b88 100644 --- a/source/blender/blenkernel/intern/deform.c +++ b/source/blender/blenkernel/intern/deform.c @@ -1192,7 +1192,12 @@ bool data_transfer_layersmapping_vgroups( if (fromlayers >= 0) { idx_src = fromlayers; - BLI_assert(idx_src < BLI_listbase_count(&ob_src->defbase)); + if (idx_src >= BLI_listbase_count(&ob_src->defbase)) { + /* This can happen when vgroups are removed from source object... + * Remapping would be really tricky here, we'd need to go over all objects in Main everytime we delete + * a vgroup... for now, simpler and safer to abort. */ + return false; + } } else if ((idx_src = ob_src->actdef - 1) == -1) { return false; diff --git a/source/blender/blenkernel/intern/displist.c b/source/blender/blenkernel/intern/displist.c index 5e812d4e5d0..ad055a727a9 100644 --- a/source/blender/blenkernel/intern/displist.c +++ b/source/blender/blenkernel/intern/displist.c @@ -1573,7 +1573,7 @@ static void do_makeDispListCurveTypes( } if (ob->type == OB_FONT) { - BKE_vfont_to_curve_nubase(G.main, ob, FO_EDIT, &nubase); + BKE_vfont_to_curve_nubase(ob, FO_EDIT, &nubase); } else { BKE_nurbList_duplicate(&nubase, BKE_curve_nurbs_get(cu)); diff --git a/source/blender/blenkernel/intern/dynamicpaint.c b/source/blender/blenkernel/intern/dynamicpaint.c index 0b2c65a7b8d..ed2566c9bb5 100644 --- a/source/blender/blenkernel/intern/dynamicpaint.c +++ b/source/blender/blenkernel/intern/dynamicpaint.c @@ -490,9 +490,9 @@ static void scene_setSubframe(Scene *scene, float subframe) scene->r.subframe = subframe; } -static int surface_getBrushFlags(DynamicPaintSurface *surface, const ViewLayer *view_layer) +static int surface_getBrushFlags(DynamicPaintSurface *surface, const Depsgraph *depsgraph) { - Base *base = BKE_collection_or_layer_objects(NULL, NULL, view_layer, surface->brush_group); + Base *base = BKE_collection_or_layer_objects(depsgraph, NULL, NULL, surface->brush_group); Object *brushObj = NULL; ModifierData *md = NULL; @@ -5758,7 +5758,7 @@ static void dynamic_paint_generate_bake_data_cb( } } -static int dynamicPaint_generateBakeData(DynamicPaintSurface *surface, const ViewLayer *view_layer, Object *ob) +static int dynamicPaint_generateBakeData(DynamicPaintSurface *surface, const Depsgraph *depsgraph, Object *ob) { PaintSurfaceData *sData = surface->data; PaintBakeData *bData = sData->bData; @@ -5766,7 +5766,7 @@ static int dynamicPaint_generateBakeData(DynamicPaintSurface *surface, const Vie int index; bool new_bdata = false; const bool do_velocity_data = ((surface->effect & MOD_DPAINT_EFFECT_DO_DRIP) || - (surface_getBrushFlags(surface, view_layer) & BRUSH_USES_VELOCITY)); + (surface_getBrushFlags(surface, depsgraph) & BRUSH_USES_VELOCITY)); const bool do_accel_data = (surface->effect & MOD_DPAINT_EFFECT_DO_DRIP) != 0; int canvasNumOfVerts = dm->getNumVerts(dm); @@ -5912,8 +5912,7 @@ static int dynamicPaint_doStep( { Object *brushObj = NULL; ModifierData *md = NULL; - ViewLayer *view_layer = DEG_get_evaluated_view_layer(depsgraph); - Base *base = BKE_collection_or_layer_objects(NULL, NULL, view_layer, surface->brush_group); + Base *base = BKE_collection_or_layer_objects(depsgraph, NULL, NULL, surface->brush_group); /* backup current scene frame */ int scene_frame = scene->r.cfra; @@ -6051,8 +6050,7 @@ int dynamicPaint_calculateFrame( dynamicPaint_applySurfaceDisplace(surface, surface->canvas->dm); /* update bake data */ - ViewLayer *view_layer = DEG_get_evaluated_view_layer(depsgraph); - dynamicPaint_generateBakeData(surface, view_layer, cObject); + dynamicPaint_generateBakeData(surface, depsgraph, cObject); /* don't do substeps for first frame */ if (surface->substeps && (frame != surface->start_frame)) { diff --git a/source/blender/blenkernel/intern/editmesh_bvh.c b/source/blender/blenkernel/intern/editmesh_bvh.c index e68f11f6274..c1121d5b1ea 100644 --- a/source/blender/blenkernel/intern/editmesh_bvh.c +++ b/source/blender/blenkernel/intern/editmesh_bvh.c @@ -147,9 +147,9 @@ BMBVHTree *BKE_bmbvh_new_ex( BLI_bvhtree_insert(bmtree->tree, i, (float *)cos, 3); } - + BLI_bvhtree_balance(bmtree->tree); - + return bmtree; } @@ -188,11 +188,11 @@ BMBVHTree *BKE_bmbvh_new( void BKE_bmbvh_free(BMBVHTree *bmtree) { BLI_bvhtree_free(bmtree->tree); - + if (bmtree->cos_cage && bmtree->cos_cage_free) { MEM_freeN((void *)bmtree->cos_cage); } - + MEM_freeN(bmtree); } @@ -313,7 +313,7 @@ BMFace *BKE_bmbvh_ray_cast(BMBVHTree *bmtree, const float co[3], const float dir /* ok to leave 'uv' uninitialized */ bmcb_data.looptris = (const BMLoop *(*)[3])bmtree->looptris; bmcb_data.cos_cage = (const float (*)[3])bmtree->cos_cage; - + BLI_bvhtree_ray_cast(bmtree->tree, co, dir, radius, &hit, bmbvh_ray_cast_cb, &bmcb_data); if (hit.index != -1 && hit.dist != dist) { diff --git a/source/blender/blenkernel/intern/effect.c b/source/blender/blenkernel/intern/effect.c index bdf6e84a3b1..7e506570b7e 100644 --- a/source/blender/blenkernel/intern/effect.c +++ b/source/blender/blenkernel/intern/effect.c @@ -219,10 +219,6 @@ ListBase *pdInitEffectors( ListBase *effectors = NULL; for (; base; base = base->next) { - if ((base->flag & BASE_VISIBLED) == 0) { - continue; - } - if (base->object->pd && base->object->pd->forcefield) { add_object_to_effectors(&effectors, depsgraph, scene, weights, base->object, ob_src, for_simulation); } @@ -318,7 +314,7 @@ void pd_point_from_particle(ParticleSimulationData *sim, ParticleData *pa, Parti point->index = pa - sim->psys->particles; point->size = pa->size; point->charge = 0.0f; - + if (part->pd && part->pd->forcefield == PFIELD_CHARGE) point->charge += part->pd->f_strength; @@ -377,7 +373,7 @@ void pd_point_from_soft(Scene *scene, float *loc, float *vel, int index, Effecte // triangle - ray callback function static void eff_tri_ray_hit(void *UNUSED(userData), int UNUSED(index), const BVHTreeRay *UNUSED(ray), BVHTreeRayHit *hit) -{ +{ /* whenever we hit a bounding box, we don't check further */ hit->dist = -1; hit->index = 1; @@ -391,7 +387,7 @@ static float eff_calc_visibility(ListBase *colliders, EffectorCache *eff, Effect ColliderCache *col; float norm[3], len = 0.0; float visibility = 1.0, absorption = 0.0; - + if (!(eff->pd->flag & PFIELD_VISIBILITY)) return visibility; @@ -403,7 +399,7 @@ static float eff_calc_visibility(ListBase *colliders, EffectorCache *eff, Effect negate_v3_v3(norm, efd->vec_to_point); len = normalize_v3(norm); - + /* check all collision objects */ for (col = colls->first; col; col = col->next) { CollisionModifierData *collmd = col->collmd; @@ -426,7 +422,7 @@ static float eff_calc_visibility(ListBase *colliders, EffectorCache *eff, Effect /* visibility is only between 0 and 1, calculated from 1-absorption */ visibility *= CLAMPIS(1.0f-absorption, 0.0f, 1.0f); - + if (visibility <= 0.0f) break; } @@ -435,7 +431,7 @@ static float eff_calc_visibility(ListBase *colliders, EffectorCache *eff, Effect if (!colliders) free_collider_cache(&colls); - + return visibility; } @@ -446,11 +442,11 @@ static float wind_func(struct RNG *rng, float strength) float force = BLI_rng_get_float(rng) + 1.0f; float ret; float sign = 0; - + sign = ((float)random > 64.0f) ? 1.0f: -1.0f; // dividing by 2 is not giving equal sign distribution - + ret = sign*((float)random / force)*strength/128.0f; - + return ret; } @@ -543,7 +539,7 @@ int closest_point_on_surface(SurfaceModifierData *surmd, const float co[3], floa if (surface_vel) { const MLoop *mloop = surmd->bvhtree->loop; const MLoopTri *lt = &surmd->bvhtree->looptri[nearest.index]; - + copy_v3_v3(surface_vel, surmd->v[mloop[lt->tri[0]].v].co); add_v3_v3(surface_vel, surmd->v[mloop[lt->tri[1]].v].co); add_v3_v3(surface_vel, surmd->v[mloop[lt->tri[2]].v].co); @@ -625,7 +621,7 @@ int get_effector_data(EffectorCache *eff, EffectorData *efd, EffectedPoint *poin efd->nor[0] = 1.f; efd->nor[1] = efd->nor[2] = 0.f; mul_qt_v3(state.rot, efd->nor); - + if (real_velocity) copy_v3_v3(efd->vel, state.vel); @@ -698,9 +694,9 @@ static void get_effector_tot(EffectorCache *eff, EffectorData *efd, EffectedPoin } else if (eff->psys) { *tot = eff->psys->totpart; - + if (eff->pd->forcefield == PFIELD_CHARGE) { - /* Only the charge of the effected particle is used for + /* Only the charge of the effected particle is used for * interaction, not fall-offs. If the fall-offs aren't the * same this will be unphysical, but for animation this * could be the wanted behavior. If you want physical @@ -862,10 +858,10 @@ static void do_physical_effector(EffectorCache *eff, EffectorData *efd, Effected /* new vortex force */ cross_v3_v3v3(temp, efd->nor2, efd->vec_to_point2); mul_v3_fl(temp, strength * efd->falloff); - + cross_v3_v3v3(force, efd->nor2, temp); mul_v3_fl(force, strength * efd->falloff); - + madd_v3_v3fl(temp, point->vel, -point->vel_to_sec); add_v3_v3(force, temp); } @@ -893,7 +889,7 @@ static void do_physical_effector(EffectorCache *eff, EffectorData *efd, Effected break; case PFIELD_LENNARDJ: fac = pow((efd->size + point->size) / efd->distance, 6.0); - + fac = - fac * (1.0f - fac) / efd->distance; /* limit the repulsive term drastically to avoid huge forces */ @@ -998,7 +994,7 @@ void pdDoEffectors(ListBase *effectors, ListBase *colliders, EffectorWeights *we /* Cycle through collected objects, get total of (1/(gravity_strength * dist^gravity_power)) */ /* Check for min distance here? (yes would be cool to add that, ton) */ - + if (effectors) for (eff = effectors->first; eff; eff=eff->next) { /* object effectors were fully checked to be OK to evaluate! */ @@ -1007,7 +1003,7 @@ void pdDoEffectors(ListBase *effectors, ListBase *colliders, EffectorWeights *we for (; p<tot; p+=step) { if (get_effector_data(eff, &efd, point, 0)) { efd.falloff= effector_falloff(eff, &efd, point, weights); - + if (efd.falloff > 0.0f) efd.falloff *= eff_calc_visibility(colliders, eff, &efd, point); @@ -1022,7 +1018,7 @@ void pdDoEffectors(ListBase *effectors, ListBase *colliders, EffectorWeights *we copy_v3_v3(temp1, force); do_physical_effector(eff, &efd, point, force); - + /* for softbody backward compatibility */ if (point->flag & PE_WIND_AS_SPEED && impulse) { sub_v3_v3v3(temp2, force, temp1); @@ -1135,14 +1131,14 @@ void BKE_sim_debug_data_add_element(int type, const float v1[3], const float v2[ { unsigned int category_hash = BLI_ghashutil_strhash_p(category); SimDebugElement *elem; - + if (!_sim_debug_data) { if (G.debug & G_DEBUG_SIMDATA) BKE_sim_debug_data_set_enabled(true); else return; } - + elem = MEM_callocN(sizeof(SimDebugElement), "sim debug data element"); elem->type = type; elem->category_hash = category_hash; @@ -1162,7 +1158,7 @@ void BKE_sim_debug_data_add_element(int type, const float v1[3], const float v2[ BLI_strncpy(elem->str, str, sizeof(elem->str)); else elem->str[0] = '\0'; - + debug_data_insert(_sim_debug_data, elem); } @@ -1171,7 +1167,7 @@ void BKE_sim_debug_data_remove_element(unsigned int hash) SimDebugElement dummy; if (!_sim_debug_data) return; - + dummy.hash = hash; BLI_ghash_remove(_sim_debug_data->gh, &dummy, NULL, debug_element_free); } @@ -1180,7 +1176,7 @@ void BKE_sim_debug_data_clear(void) { if (!_sim_debug_data) return; - + if (_sim_debug_data->gh) BLI_ghash_clear(_sim_debug_data->gh, NULL, debug_element_free); } @@ -1188,17 +1184,17 @@ void BKE_sim_debug_data_clear(void) void BKE_sim_debug_data_clear_category(const char *category) { int category_hash = (int)BLI_ghashutil_strhash_p(category); - + if (!_sim_debug_data) return; - + if (_sim_debug_data->gh) { GHashIterator iter; BLI_ghashIterator_init(&iter, _sim_debug_data->gh); while (!BLI_ghashIterator_done(&iter)) { const SimDebugElement *elem = BLI_ghashIterator_getValue(&iter); BLI_ghashIterator_step(&iter); /* removing invalidates the current iterator, so step before removing */ - + if (elem->category_hash == category_hash) BLI_ghash_remove(_sim_debug_data->gh, elem, NULL, debug_element_free); } diff --git a/source/blender/blenkernel/intern/fcurve.c b/source/blender/blenkernel/intern/fcurve.c index 0de04e31be9..e63d99a35ee 100644 --- a/source/blender/blenkernel/intern/fcurve.c +++ b/source/blender/blenkernel/intern/fcurve.c @@ -29,7 +29,7 @@ * \ingroup bke */ - + #include <math.h> #include <stdio.h> @@ -58,7 +58,7 @@ #include "BKE_armature.h" #include "BKE_constraint.h" #include "BKE_context.h" -#include "BKE_curve.h" +#include "BKE_curve.h" #include "BKE_global.h" #include "BKE_object.h" #include "BKE_nla.h" @@ -66,7 +66,7 @@ #include "RNA_access.h" #ifdef WITH_PYTHON -#include "BPY_extern.h" +#include "BPY_extern.h" #endif #define SMALL -1.0e-10 @@ -83,20 +83,20 @@ static ThreadMutex python_driver_lock = BLI_MUTEX_INITIALIZER; /* Frees the F-Curve itself too, so make sure BLI_remlink is called before calling this... */ void free_fcurve(FCurve *fcu) { - if (fcu == NULL) + if (fcu == NULL) return; /* free curve data */ MEM_SAFE_FREE(fcu->bezt); MEM_SAFE_FREE(fcu->fpt); - + /* free RNA-path, as this were allocated when getting the path string */ MEM_SAFE_FREE(fcu->rna_path); - + /* free extra data - i.e. modifiers, and driver */ fcurve_free_driver(fcu); free_fmodifiers(&fcu->modifiers); - + /* free f-curve itself */ MEM_freeN(fcu); } @@ -105,12 +105,12 @@ void free_fcurve(FCurve *fcu) void free_fcurves(ListBase *list) { FCurve *fcu, *fcn; - + /* sanity check */ if (list == NULL) return; - - /* free data - no need to call remlink before freeing each curve, + + /* free data - no need to call remlink before freeing each curve, * as we store reference to next, and freeing only touches the curve * it's given */ @@ -118,10 +118,10 @@ void free_fcurves(ListBase *list) fcn = fcu->next; free_fcurve(fcu); } - + /* clear pointers just in case */ BLI_listbase_clear(list); -} +} /* ---------------------- Copy --------------------------- */ @@ -129,30 +129,30 @@ void free_fcurves(ListBase *list) FCurve *copy_fcurve(const FCurve *fcu) { FCurve *fcu_d; - + /* sanity check */ if (fcu == NULL) return NULL; - + /* make a copy */ fcu_d = MEM_dupallocN(fcu); - + fcu_d->next = fcu_d->prev = NULL; fcu_d->grp = NULL; - + /* copy curve data */ fcu_d->bezt = MEM_dupallocN(fcu_d->bezt); fcu_d->fpt = MEM_dupallocN(fcu_d->fpt); - + /* copy rna-path */ fcu_d->rna_path = MEM_dupallocN(fcu_d->rna_path); - + /* copy driver */ fcu_d->driver = fcurve_copy_driver(fcu_d->driver); - + /* copy modifiers */ copy_fmodifiers(&fcu_d->modifiers, &fcu->modifiers); - + /* return new data */ return fcu_d; } @@ -161,14 +161,14 @@ FCurve *copy_fcurve(const FCurve *fcu) void copy_fcurves(ListBase *dst, ListBase *src) { FCurve *dfcu, *sfcu; - + /* sanity checks */ if (ELEM(NULL, dst, src)) return; - + /* clear destination list first */ BLI_listbase_clear(dst); - + /* copy one-by-one */ for (sfcu = src->first; sfcu; sfcu = sfcu->next) { dfcu = copy_fcurve(sfcu); @@ -192,22 +192,22 @@ FCurve *id_data_find_fcurve(ID *id, void *data, StructRNA *type, const char *pro if (r_driven) *r_driven = false; - + /* only use the current action ??? */ if (ELEM(NULL, adt, adt->action)) return NULL; - + RNA_pointer_create(id, type, data, &ptr); prop = RNA_struct_find_property(&ptr, prop_name); - + if (prop) { path = RNA_path_from_ID_to_property(&ptr, prop); - + if (path) { /* animation takes priority over drivers */ if ((adt->action) && (adt->action->curves.first)) fcu = list_find_fcurve(&adt->action->curves, path, index); - + /* if not animated, check if driven */ if ((fcu == NULL) && (adt->drivers.first)) { fcu = list_find_fcurve(&adt->drivers, path, index); @@ -215,7 +215,7 @@ FCurve *id_data_find_fcurve(ID *id, void *data, StructRNA *type, const char *pro *r_driven = true; fcu = NULL; } - + MEM_freeN(path); } } @@ -228,11 +228,11 @@ FCurve *id_data_find_fcurve(ID *id, void *data, StructRNA *type, const char *pro FCurve *list_find_fcurve(ListBase *list, const char rna_path[], const int array_index) { FCurve *fcu; - + /* sanity checks */ if (ELEM(NULL, list, rna_path) || (array_index < 0) ) return NULL; - + /* check paths of curves, then array indices... */ for (fcu = list->first; fcu; fcu = fcu->next) { /* simple string-compare (this assumes that they have the same root...) */ @@ -242,7 +242,7 @@ FCurve *list_find_fcurve(ListBase *list, const char rna_path[], const int array_ return fcu; } } - + /* return */ return NULL; } @@ -251,7 +251,7 @@ FCurve *list_find_fcurve(ListBase *list, const char rna_path[], const int array_ FCurve *iter_step_fcurve(FCurve *fcu_iter, const char rna_path[]) { FCurve *fcu; - + /* sanity checks */ if (ELEM(NULL, fcu_iter, rna_path)) return NULL; @@ -268,7 +268,7 @@ FCurve *iter_step_fcurve(FCurve *fcu_iter, const char rna_path[]) return NULL; } -/* Get list of LinkData's containing pointers to the F-Curves which control the types of data indicated +/* Get list of LinkData's containing pointers to the F-Curves which control the types of data indicated * Lists... * - dst: list of LinkData's matching the criteria returned. * List must be freed after use, and is assumed to be empty when passed. @@ -281,36 +281,36 @@ int list_find_data_fcurves(ListBase *dst, ListBase *src, const char *dataPrefix, { FCurve *fcu; int matches = 0; - + /* sanity checks */ if (ELEM(NULL, dst, src, dataPrefix, dataName)) return 0; else if ((dataPrefix[0] == 0) || (dataName[0] == 0)) return 0; - + /* search each F-Curve one by one */ for (fcu = src->first; fcu; fcu = fcu->next) { /* check if quoted string matches the path */ if ((fcu->rna_path) && strstr(fcu->rna_path, dataPrefix)) { char *quotedName = BLI_str_quoted_substrN(fcu->rna_path, dataPrefix); - + if (quotedName) { /* check if the quoted name matches the required name */ if (STREQ(quotedName, dataName)) { LinkData *ld = MEM_callocN(sizeof(LinkData), __func__); - + ld->data = fcu; BLI_addtail(dst, ld); - + matches++; } - + /* always free the quoted string, since it needs freeing */ MEM_freeN(quotedName); } } } - + /* return the number of matches */ return matches; } @@ -328,39 +328,39 @@ FCurve *rna_get_fcurve_context_ui( { FCurve *fcu = NULL; PointerRNA tptr = *ptr; - + *r_driven = false; *r_special = false; - + if (r_animdata) *r_animdata = NULL; if (r_action) *r_action = NULL; - + /* Special case for NLA Control Curves... */ if (BKE_nlastrip_has_curves_for_property(ptr, prop)) { NlaStrip *strip = (NlaStrip *)ptr->data; - + /* Set the special flag, since it cannot be a normal action/driver * if we've been told to start looking here... */ *r_special = true; - + /* The F-Curve either exists or it doesn't here... */ fcu = list_find_fcurve(&strip->fcurves, RNA_property_identifier(prop), rnaindex); return fcu; } - + /* there must be some RNA-pointer + property combon */ if (prop && tptr.id.data && RNA_property_animateable(&tptr, prop)) { AnimData *adt = BKE_animdata_from_id(tptr.id.data); int step = C ? 2 : 1; /* Always 1 in case we have no context (can't check in 'ancestors' of given RNA ptr). */ char *path = NULL; - + if (!adt && C) { path = BKE_animdata_driver_path_hack(C, &tptr, prop, NULL); adt = BKE_animdata_from_id(tptr.id.data); step--; } - + /* Standard F-Curve - Animation (Action) or Drivers */ while (adt && step--) { if ((adt->action && adt->action->curves.first) || (adt->drivers.first)) { @@ -368,27 +368,27 @@ FCurve *rna_get_fcurve_context_ui( if (step) { path = RNA_path_from_ID_to_property(&tptr, prop); } - + // XXX: the logic here is duplicated with a function up above if (path) { /* animation takes priority over drivers */ if (adt->action && adt->action->curves.first) { fcu = list_find_fcurve(&adt->action->curves, path, rnaindex); - + if (fcu && r_action) *r_action = adt->action; } - + /* if not animated, check if driven */ if (!fcu && (adt->drivers.first)) { fcu = list_find_fcurve(&adt->drivers, path, rnaindex); - + if (fcu) { if (r_animdata) *r_animdata = adt; *r_driven = true; } } - + if (fcu && r_action) { if (r_animdata) *r_animdata = adt; *r_action = adt->action; @@ -410,7 +410,7 @@ FCurve *rna_get_fcurve_context_ui( } MEM_SAFE_FREE(path); } - + return fcu; } @@ -423,10 +423,10 @@ static int binarysearch_bezt_index_ex(BezTriple array[], float frame, int arrayl { int start = 0, end = arraylen; int loopbreaker = 0, maxloop = arraylen * 2; - + /* initialize replace-flag first */ *r_replace = false; - + /* sneaky optimizations (don't go through searching process if...): * - keyframe to be added is to be added out of current bounds * - keyframe to be added would replace one of the existing ones on bounds @@ -438,7 +438,7 @@ static int binarysearch_bezt_index_ex(BezTriple array[], float frame, int arrayl else { /* check whether to add before/after/on */ float framenum; - + /* 'First' Keyframe (when only one keyframe, this case is used) */ framenum = array[0].vec[1][0]; if (IS_EQT(frame, framenum, threshold)) { @@ -447,7 +447,7 @@ static int binarysearch_bezt_index_ex(BezTriple array[], float frame, int arrayl } else if (frame < framenum) return 0; - + /* 'Last' Keyframe */ framenum = array[(arraylen - 1)].vec[1][0]; if (IS_EQT(frame, framenum, threshold)) { @@ -457,37 +457,37 @@ static int binarysearch_bezt_index_ex(BezTriple array[], float frame, int arrayl else if (frame > framenum) return arraylen; } - - + + /* most of the time, this loop is just to find where to put it - * 'loopbreaker' is just here to prevent infinite loops + * 'loopbreaker' is just here to prevent infinite loops */ for (loopbreaker = 0; (start <= end) && (loopbreaker < maxloop); loopbreaker++) { /* compute and get midpoint */ int mid = start + ((end - start) / 2); /* we calculate the midpoint this way to avoid int overflows... */ float midfra = array[mid].vec[1][0]; - + /* check if exactly equal to midpoint */ if (IS_EQT(frame, midfra, threshold)) { *r_replace = true; return mid; } - + /* repeat in upper/lower half */ if (frame > midfra) start = mid + 1; else if (frame < midfra) end = mid - 1; } - + /* print error if loop-limit exceeded */ if (loopbreaker == (maxloop - 1)) { printf("Error: binarysearch_bezt_index() was taking too long\n"); - + /* include debug info */ printf("\tround = %d: start = %d, end = %d, arraylen = %d\n", loopbreaker, start, end, arraylen); } - + /* not found, so return where to place it */ return start; } @@ -509,20 +509,20 @@ static short get_fcurve_end_keyframes(FCurve *fcu, BezTriple **first, BezTriple const bool do_sel_only) { bool found = false; - + /* init outputs */ *first = NULL; *last = NULL; - + /* sanity checks */ if (fcu->bezt == NULL) return found; - + /* only include selected items? */ if (do_sel_only) { BezTriple *bezt; unsigned int i; - + /* find first selected */ bezt = fcu->bezt; for (i = 0; i < fcu->totvert; bezt++, i++) { @@ -532,7 +532,7 @@ static short get_fcurve_end_keyframes(FCurve *fcu, BezTriple **first, BezTriple break; } } - + /* find last selected */ bezt = ARRAY_LAST_ITEM(fcu->bezt, BezTriple, fcu->totvert); for (i = 0; i < fcu->totvert; bezt--, i++) { @@ -549,7 +549,7 @@ static short get_fcurve_end_keyframes(FCurve *fcu, BezTriple **first, BezTriple *last = ARRAY_LAST_ITEM(fcu->bezt, BezTriple, fcu->totvert); found = true; } - + return found; } @@ -562,18 +562,18 @@ bool calc_fcurve_bounds(FCurve *fcu, float *xmin, float *xmax, float *ymin, floa float yminv = 999999999.0f, ymaxv = -999999999.0f; bool foundvert = false; unsigned int i; - + if (fcu->totvert) { if (fcu->bezt) { BezTriple *bezt_first = NULL, *bezt_last = NULL; - + if (xmin || xmax) { /* get endpoint keyframes */ foundvert = get_fcurve_end_keyframes(fcu, &bezt_first, &bezt_last, do_sel_only); - + if (bezt_first) { BLI_assert(bezt_last != NULL); - + if (include_handles) { xminv = min_fff(xminv, bezt_first->vec[0][0], bezt_first->vec[1][0]); xmaxv = max_fff(xmaxv, bezt_last->vec[1][0], bezt_last->vec[2][0]); @@ -584,33 +584,33 @@ bool calc_fcurve_bounds(FCurve *fcu, float *xmin, float *xmax, float *ymin, floa } } } - + /* only loop over keyframes to find extents for values if needed */ if (ymin || ymax) { BezTriple *bezt, *prevbezt = NULL; - + for (bezt = fcu->bezt, i = 0; i < fcu->totvert; prevbezt = bezt, bezt++, i++) { if ((do_sel_only == false) || BEZT_ISSEL_ANY(bezt)) { /* keyframe itself */ yminv = min_ff(yminv, bezt->vec[1][1]); ymaxv = max_ff(ymaxv, bezt->vec[1][1]); - + if (include_handles) { - /* left handle - only if applicable + /* left handle - only if applicable * NOTE: for the very first keyframe, the left handle actually has no bearings on anything */ if (prevbezt && (prevbezt->ipo == BEZT_IPO_BEZ)) { yminv = min_ff(yminv, bezt->vec[0][1]); ymaxv = max_ff(ymaxv, bezt->vec[0][1]); } - + /* right handle - only if applicable */ if (bezt->ipo == BEZT_IPO_BEZ) { yminv = min_ff(yminv, bezt->vec[2][1]); ymaxv = max_ff(ymaxv, bezt->vec[2][1]); } } - + foundvert = true; } } @@ -622,41 +622,41 @@ bool calc_fcurve_bounds(FCurve *fcu, float *xmin, float *xmax, float *ymin, floa xminv = min_ff(xminv, fcu->fpt[0].vec[0]); xmaxv = max_ff(xmaxv, fcu->fpt[fcu->totvert - 1].vec[0]); } - + /* only loop over keyframes to find extents for values if needed */ if (ymin || ymax) { FPoint *fpt; - + for (fpt = fcu->fpt, i = 0; i < fcu->totvert; fpt++, i++) { if (fpt->vec[1] < yminv) yminv = fpt->vec[1]; if (fpt->vec[1] > ymaxv) ymaxv = fpt->vec[1]; - + foundvert = true; } } } } - + if (foundvert) { if (xmin) *xmin = xminv; if (xmax) *xmax = xmaxv; - + if (ymin) *ymin = yminv; if (ymax) *ymax = ymaxv; } else { if (G.debug & G_DEBUG) printf("F-Curve calc bounds didn't find anything, so assuming minimum bounds of 1.0\n"); - + if (xmin) *xmin = 0.0f; if (xmax) *xmax = 1.0f; - + if (ymin) *ymin = 0.0f; if (ymax) *ymax = 1.0f; } - + return foundvert; } @@ -670,28 +670,28 @@ bool calc_fcurve_range(FCurve *fcu, float *start, float *end, if (fcu->totvert) { if (fcu->bezt) { BezTriple *bezt_first = NULL, *bezt_last = NULL; - + /* get endpoint keyframes */ get_fcurve_end_keyframes(fcu, &bezt_first, &bezt_last, do_sel_only); - + if (bezt_first) { BLI_assert(bezt_last != NULL); - + min = min_ff(min, bezt_first->vec[1][0]); max = max_ff(max, bezt_last->vec[1][0]); - + foundvert = true; } } else if (fcu->fpt) { min = min_ff(min, fcu->fpt[0].vec[0]); max = max_ff(max, fcu->fpt[fcu->totvert - 1].vec[0]); - + foundvert = true; } - + } - + if (foundvert == false) { min = max = 0.0f; } @@ -711,7 +711,7 @@ bool calc_fcurve_range(FCurve *fcu, float *start, float *end, /* ----------------- Status Checks -------------------------- */ -/* Are keyframes on F-Curve of any use? +/* Are keyframes on F-Curve of any use? * Usability of keyframes refers to whether they should be displayed, * and also whether they will have any influence on the final result. */ @@ -720,11 +720,11 @@ bool fcurve_are_keyframes_usable(FCurve *fcu) /* F-Curve must exist */ if (fcu == NULL) return false; - + /* F-Curve must not have samples - samples are mutually exclusive of keyframes */ if (fcu->fpt) return false; - + /* if it has modifiers, none of these should "drastically" alter the curve */ if (fcu->modifiers.first) { FModifier *fcm; @@ -735,7 +735,7 @@ bool fcurve_are_keyframes_usable(FCurve *fcu) /* ignore if muted/disabled */ if (fcm->flag & (FMODIFIER_FLAG_DISABLED | FMODIFIER_FLAG_MUTED)) continue; - + /* type checks */ switch (fcm->type) { /* clearly harmless - do nothing */ @@ -743,12 +743,12 @@ bool fcurve_are_keyframes_usable(FCurve *fcu) case FMODIFIER_TYPE_STEPPED: case FMODIFIER_TYPE_NOISE: break; - + /* sometimes harmful - depending on whether they're "additive" or not */ case FMODIFIER_TYPE_GENERATOR: { FMod_Generator *data = (FMod_Generator *)fcm->data; - + if ((data->flag & FCM_GENERATOR_ADDITIVE) == 0) return false; break; @@ -756,7 +756,7 @@ bool fcurve_are_keyframes_usable(FCurve *fcu) case FMODIFIER_TYPE_FN_GENERATOR: { FMod_FunctionGenerator *data = (FMod_FunctionGenerator *)fcm->data; - + if ((data->flag & FCM_GENERATOR_ADDITIVE) == 0) return false; break; @@ -767,7 +767,7 @@ bool fcurve_are_keyframes_usable(FCurve *fcu) } } } - + /* keyframes are usable */ return true; } @@ -778,7 +778,7 @@ bool BKE_fcurve_is_protected(FCurve *fcu) ((fcu->grp) && (fcu->grp->flag & AGRP_PROTECTED))); } -/* Can keyframes be added to F-Curve? +/* Can keyframes be added to F-Curve? * Keyframes can only be added if they are already visible */ bool fcurve_is_keyframable(FCurve *fcu) @@ -786,11 +786,11 @@ bool fcurve_is_keyframable(FCurve *fcu) /* F-Curve's keyframes must be "usable" (i.e. visible + have an effect on final result) */ if (fcurve_are_keyframes_usable(fcu) == 0) return false; - + /* F-Curve must currently be editable too */ if (BKE_fcurve_is_protected(fcu)) return false; - + /* F-Curve is keyframable */ return true; } @@ -801,7 +801,7 @@ bool fcurve_is_keyframable(FCurve *fcu) void bezt_add_to_cfra_elem(ListBase *lb, BezTriple *bezt) { CfraElem *ce, *cen; - + for (ce = lb->first; ce; ce = ce->next) { /* double key? */ if (IS_EQT(ce->cfra, bezt->vec[1][0], BEZT_BINARYSEARCH_THRESH)) { @@ -811,7 +811,7 @@ void bezt_add_to_cfra_elem(ListBase *lb, BezTriple *bezt) /* should key be inserted before this column? */ else if (ce->cfra > bezt->vec[1][0]) break; } - + /* create a new column */ cen = MEM_callocN(sizeof(CfraElem), "add_to_cfra_elem"); if (ce) BLI_insertlinkbefore(lb, ce, cen); @@ -826,26 +826,26 @@ void bezt_add_to_cfra_elem(ListBase *lb, BezTriple *bezt) * data imported from BVH/Mocap files), which are specialized for use with high density datasets, * which BezTriples/Keyframe data are ill equipped to do. */ - - -/* Basic sampling callback which acts as a wrapper for evaluate_fcurve() + + +/* Basic sampling callback which acts as a wrapper for evaluate_fcurve() * 'data' arg here is unneeded here... */ float fcurve_samplingcb_evalcurve(FCurve *fcu, void *UNUSED(data), float evaltime) { /* assume any interference from drivers on the curve is intended... */ return evaluate_fcurve(fcu, evaltime); -} +} - -/* Main API function for creating a set of sampled curve data, given some callback function + +/* Main API function for creating a set of sampled curve data, given some callback function * used to retrieve the values to store. */ void fcurve_store_samples(FCurve *fcu, void *data, int start, int end, FcuSampleFunc sample_cb) { FPoint *fpt, *new_fpt; int cfra; - + /* sanity checks */ /* TODO: make these tests report errors using reports not printf's */ if (ELEM(NULL, fcu, sample_cb)) { @@ -856,20 +856,20 @@ void fcurve_store_samples(FCurve *fcu, void *data, int start, int end, FcuSample printf("Error: Frame range for Sampled F-Curve creation is inappropriate\n"); return; } - + /* set up sample data */ fpt = new_fpt = MEM_callocN(sizeof(FPoint) * (end - start + 1), "FPoint Samples"); - + /* use the sampling callback at 1-frame intervals from start to end frames */ for (cfra = start; cfra <= end; cfra++, fpt++) { fpt->vec[0] = (float)cfra; fpt->vec[1] = sample_cb(fcu, data, (float)cfra); } - + /* free any existing sample/keyframe data on curve */ if (fcu->bezt) MEM_freeN(fcu->bezt); if (fcu->fpt) MEM_freeN(fcu->fpt); - + /* store the samples */ fcu->bezt = NULL; fcu->fpt = new_fpt; @@ -922,7 +922,7 @@ static BezTriple *cycle_offset_triple(bool cycle, BezTriple *out, const BezTripl return out; } -/* This function recalculates the handles of an F-Curve +/* This function recalculates the handles of an F-Curve * If the BezTriples have been rearranged, sort them first before using this. */ void calchandles_fcurve(FCurve *fcu) @@ -935,7 +935,7 @@ void calchandles_fcurve(FCurve *fcu) * - need bezier keys * - only bezier-interpolation has handles (for now) */ - if (ELEM(NULL, fcu, fcu->bezt) || (a < 2) /*|| ELEM(fcu->ipo, BEZT_IPO_CONST, BEZT_IPO_LIN)*/) + if (ELEM(NULL, fcu, fcu->bezt) || (a < 2) /*|| ELEM(fcu->ipo, BEZT_IPO_CONST, BEZT_IPO_LIN)*/) return; /* if the first modifier is Cycles, smooth the curve through the cycle */ @@ -948,16 +948,16 @@ void calchandles_fcurve(FCurve *fcu) bezt = fcu->bezt; prev = cycle_offset_triple(cycle, &tmp, &fcu->bezt[fcu->totvert - 2], last, first); next = (bezt + 1); - + /* loop over all beztriples, adjusting handles */ while (a--) { /* clamp timing of handles to be on either side of beztriple */ if (bezt->vec[0][0] > bezt->vec[1][0]) bezt->vec[0][0] = bezt->vec[1][0]; if (bezt->vec[2][0] < bezt->vec[1][0]) bezt->vec[2][0] = bezt->vec[1][0]; - + /* calculate auto-handles */ BKE_nurb_handle_calc(bezt, prev, next, true, fcu->auto_smoothing); - + /* for automatic ease in and out */ if (BEZT_IS_AUTOH(bezt) && !cycle) { /* only do this on first or last beztriple */ @@ -975,7 +975,7 @@ void calchandles_fcurve(FCurve *fcu) if (prev && prev->vec[1][0] >= bezt->vec[1][0]) { prev->f5 = bezt->f5 = HD_AUTOTYPE_SPECIAL; } - + /* advance pointers for next iteration */ prev = bezt; @@ -1026,16 +1026,16 @@ void testhandles_fcurve(FCurve *fcu, const bool use_handle) void sort_time_fcurve(FCurve *fcu) { bool ok = true; - + /* keep adjusting order of beztriples until nothing moves (bubble-sort) */ while (ok) { ok = 0; - + /* currently, will only be needed when there are beztriples */ if (fcu->bezt) { BezTriple *bezt; unsigned int a; - + /* loop over ALL points to adjust position in array and recalculate handles */ for (a = 0, bezt = fcu->bezt; a < fcu->totvert; a++, bezt++) { /* check if thee's a next beztriple which we could try to swap with current */ @@ -1045,7 +1045,7 @@ void sort_time_fcurve(FCurve *fcu) SWAP(BezTriple, *bezt, *(bezt + 1)); ok = 1; } - + /* if either one of both of the points exceeds crosses over the keyframe time... */ if ( (bezt->vec[0][0] > bezt->vec[1][0]) && (bezt->vec[2][0] < bezt->vec[1][0]) ) { /* swap handles if they have switched sides for some reason */ @@ -1066,15 +1066,15 @@ void sort_time_fcurve(FCurve *fcu) short test_time_fcurve(FCurve *fcu) { unsigned int a; - + /* sanity checks */ if (fcu == NULL) return 0; - + /* currently, only need to test beztriples */ if (fcu->bezt) { BezTriple *bezt; - + /* loop through all BezTriples, stopping when one exceeds the one after it */ for (a = 0, bezt = fcu->bezt; a < (fcu->totvert - 1); a++, bezt++) { if (bezt->vec[1][0] > (bezt + 1)->vec[1][0]) @@ -1083,14 +1083,14 @@ short test_time_fcurve(FCurve *fcu) } else if (fcu->fpt) { FPoint *fpt; - + /* loop through all FPoints, stopping when one exceeds the one after it */ for (a = 0, fpt = fcu->fpt; a < (fcu->totvert - 1); a++, fpt++) { if (fpt->vec[0] > (fpt + 1)->vec[0]) return 1; } } - + /* none need any swapping */ return 0; } @@ -1103,7 +1103,7 @@ short test_time_fcurve(FCurve *fcu) typedef struct DriverVarTypeInfo { /* evaluation callback */ float (*get_value)(ChannelDriver *driver, DriverVar *dvar); - + /* allocation of target slots */ int num_targets; /* number of target slots required */ const char *target_names[MAX_DRIVER_TARGETS]; /* UI names that should be given to the slots */ @@ -1113,7 +1113,7 @@ typedef struct DriverVarTypeInfo { /* Macro to begin definitions */ #define BEGIN_DVAR_TYPEDEF(type) \ { - + /* Macro to end definitions */ #define END_DVAR_TYPEDEF \ } @@ -1135,27 +1135,27 @@ static float dtar_get_prop_val(ChannelDriver *driver, DriverTarget *dtar) ID *id; int index = -1; float value = 0.0f; - + /* sanity check */ if (ELEM(NULL, driver, dtar)) return 0.0f; - + id = dtar_id_ensure_proxy_from(dtar->id); - + /* error check for missing pointer... */ if (id == NULL) { if (G.debug & G_DEBUG) { printf("Error: driver has an invalid target to use (path = %s)\n", dtar->rna_path); } - + driver->flag |= DRIVER_FLAG_INVALID; dtar->flag |= DTAR_FLAG_INVALID; return 0.0f; } - + /* get RNA-pointer for the ID-block given in target */ RNA_id_pointer_create(id, &id_ptr); - + /* get property to read from, and get value as appropriate */ if (RNA_path_resolve_property_full(&id_ptr, dtar->rna_path, &ptr, &prop, &index)) { if (RNA_property_array_check(prop)) { @@ -1178,10 +1178,10 @@ static float dtar_get_prop_val(ChannelDriver *driver, DriverTarget *dtar) else { /* out of bounds */ if (G.debug & G_DEBUG) { - printf("Driver Evaluation Error: array index is out of bounds for %s -> %s (%d)", + printf("Driver Evaluation Error: array index is out of bounds for %s -> %s (%d)", id->name, dtar->rna_path, index); } - + driver->flag |= DRIVER_FLAG_INVALID; dtar->flag |= DTAR_FLAG_INVALID; return 0.0f; @@ -1212,12 +1212,12 @@ static float dtar_get_prop_val(ChannelDriver *driver, DriverTarget *dtar) if (G.debug & G_DEBUG) { printf("Driver Evaluation Error: cannot resolve target for %s -> %s\n", id->name, dtar->rna_path); } - + driver->flag |= DRIVER_FLAG_INVALID; dtar->flag |= DTAR_FLAG_INVALID; return 0.0f; } - + /* if we're still here, we should be ok... */ dtar->flag &= ~DTAR_FLAG_INVALID; return value; @@ -1302,7 +1302,7 @@ static bPoseChannel *dtar_get_pchan_ptr(ChannelDriver *driver, DriverTarget *dta /* check if the ID here is a valid object */ if (id && GS(id->name)) { Object *ob = (Object *)id; - + /* get pose, and subsequently, posechannel */ return BKE_pose_channel_find_name(ob->pose, dtar->pchan_name); } @@ -1426,24 +1426,24 @@ static float dvar_eval_locDiff(ChannelDriver *driver, DriverVar *dvar) Object *ob = (Object *)dtar_id_ensure_proxy_from(dtar->id); bPoseChannel *pchan; float tmp_loc[3]; - + /* after the checks above, the targets should be valid here... */ BLI_assert((ob != NULL) && (GS(ob->id.name) == ID_OB)); - + /* try to get posechannel */ pchan = BKE_pose_channel_find_name(ob->pose, dtar->pchan_name); - + /* check if object or bone */ if (pchan) { /* bone */ if (dtar->flag & DTAR_FLAG_LOCALSPACE) { if (dtar->flag & DTAR_FLAG_LOCAL_CONSTS) { float mat[4][4]; - + /* extract transform just like how the constraints do it! */ copy_m4_m4(mat, pchan->pose_mat); BKE_constraint_mat_convertspace(ob, pchan, mat, CONSTRAINT_SPACE_POSE, CONSTRAINT_SPACE_LOCAL, false); - + /* ... and from that, we get our transform */ copy_v3_v3(tmp_loc, mat[3]); } @@ -1464,11 +1464,11 @@ static float dvar_eval_locDiff(ChannelDriver *driver, DriverVar *dvar) if (dtar->flag & DTAR_FLAG_LOCAL_CONSTS) { /* XXX: this should practically be the same as transform space... */ float mat[4][4]; - + /* extract transform just like how the constraints do it! */ copy_m4_m4(mat, ob->obmat); BKE_constraint_mat_convertspace(ob, NULL, mat, CONSTRAINT_SPACE_WORLD, CONSTRAINT_SPACE_LOCAL, false); - + /* ... and from that, we get our transform */ copy_v3_v3(tmp_loc, mat[3]); } @@ -1482,7 +1482,7 @@ static float dvar_eval_locDiff(ChannelDriver *driver, DriverVar *dvar) copy_v3_v3(tmp_loc, ob->obmat[3]); } } - + /* copy the location to the right place */ if (tarIndex) { copy_v3_v3(loc2, tmp_loc); @@ -1492,10 +1492,10 @@ static float dvar_eval_locDiff(ChannelDriver *driver, DriverVar *dvar) } } DRIVER_TARGETS_LOOPER_END - - + + /* if we're still here, there should now be two targets to use, - * so just take the length of the vector between these points + * so just take the length of the vector between these points */ return len_v3v3(loc1, loc2); } @@ -1510,7 +1510,7 @@ static float dvar_eval_transChan(ChannelDriver *driver, DriverVar *dvar) float oldEul[3] = {0.0f, 0.0f, 0.0f}; bool use_eulers = false; short rot_order = ROT_MODE_EUL; - + /* check if this target has valid data */ if ((ob == NULL) || (GS(ob->id.name) != ID_OB)) { /* invalid target, so will not have enough targets */ @@ -1522,11 +1522,11 @@ static float dvar_eval_transChan(ChannelDriver *driver, DriverVar *dvar) /* target should be valid now */ dtar->flag &= ~DTAR_FLAG_INVALID; } - + /* try to get posechannel */ pchan = BKE_pose_channel_find_name(ob->pose, dtar->pchan_name); - - /* check if object or bone, and get transform matrix accordingly + + /* check if object or bone, and get transform matrix accordingly * - "useEulers" code is used to prevent the problems associated with non-uniqueness * of euler decomposition from matrices [#20870] * - localspace is for [#21384], where parent results are not wanted @@ -1539,7 +1539,7 @@ static float dvar_eval_transChan(ChannelDriver *driver, DriverVar *dvar) rot_order = pchan->rotmode; use_eulers = true; } - + if (dtar->flag & DTAR_FLAG_LOCALSPACE) { if (dtar->flag & DTAR_FLAG_LOCAL_CONSTS) { /* just like how the constraints do it! */ @@ -1547,7 +1547,7 @@ static float dvar_eval_transChan(ChannelDriver *driver, DriverVar *dvar) BKE_constraint_mat_convertspace(ob, pchan, mat, CONSTRAINT_SPACE_POSE, CONSTRAINT_SPACE_LOCAL, false); } else { - /* specially calculate local matrix, since chan_mat is not valid + /* specially calculate local matrix, since chan_mat is not valid * since it stores delta transform of pose_mat so that deforms work * so it cannot be used here for "transform" space */ @@ -1566,7 +1566,7 @@ static float dvar_eval_transChan(ChannelDriver *driver, DriverVar *dvar) rot_order = ob->rotmode; use_eulers = true; } - + if (dtar->flag & DTAR_FLAG_LOCALSPACE) { if (dtar->flag & DTAR_FLAG_LOCAL_CONSTS) { /* just like how the constraints do it! */ @@ -1583,7 +1583,7 @@ static float dvar_eval_transChan(ChannelDriver *driver, DriverVar *dvar) copy_m4_m4(mat, ob->obmat); } } - + /* check which transform */ if (dtar->transChan >= MAX_DTAR_TRANSCHAN_TYPES) { /* not valid channel */ @@ -1595,22 +1595,22 @@ static float dvar_eval_transChan(ChannelDriver *driver, DriverVar *dvar) return len_v3(mat[dtar->transChan - DTAR_TRANSCHAN_SCALEX]); } else if (dtar->transChan >= DTAR_TRANSCHAN_ROTX) { - /* extract rotation as eulers (if needed) + /* extract rotation as eulers (if needed) * - definitely if rotation order isn't eulers already * - if eulers, then we have 2 options: * a) decompose transform matrix as required, then try to make eulers from * there compatible with original values - * b) [NOT USED] directly use the original values (no decomposition) + * b) [NOT USED] directly use the original values (no decomposition) * - only an option for "transform space", if quality is really bad with a) */ float eul[3]; - + mat4_to_eulO(eul, rot_order, mat); - + if (use_eulers) { compatible_eul(eul, oldEul); } - + return eul[dtar->transChan - DTAR_TRANSCHAN_ROTX]; } else { @@ -1629,21 +1629,21 @@ static DriverVarTypeInfo dvar_types[MAX_DVAR_TYPES] = { {"Property"}, /* UI names for targets */ {0} /* flags */ END_DVAR_TYPEDEF, - + BEGIN_DVAR_TYPEDEF(DVAR_TYPE_ROT_DIFF) dvar_eval_rotDiff, /* eval callback */ 2, /* number of targets used */ {"Object/Bone 1", "Object/Bone 2"}, /* UI names for targets */ {DTAR_FLAG_STRUCT_REF | DTAR_FLAG_ID_OB_ONLY, DTAR_FLAG_STRUCT_REF | DTAR_FLAG_ID_OB_ONLY} /* flags */ END_DVAR_TYPEDEF, - + BEGIN_DVAR_TYPEDEF(DVAR_TYPE_LOC_DIFF) dvar_eval_locDiff, /* eval callback */ 2, /* number of targets used */ {"Object/Bone 1", "Object/Bone 2"}, /* UI names for targets */ {DTAR_FLAG_STRUCT_REF | DTAR_FLAG_ID_OB_ONLY, DTAR_FLAG_STRUCT_REF | DTAR_FLAG_ID_OB_ONLY} /* flags */ END_DVAR_TYPEDEF, - + BEGIN_DVAR_TYPEDEF(DVAR_TYPE_TRANSFORM_CHAN) dvar_eval_transChan, /* eval callback */ 1, /* number of targets used */ @@ -1670,20 +1670,20 @@ void driver_free_variable(ListBase *variables, DriverVar *dvar) /* sanity checks */ if (dvar == NULL) return; - - /* free target vars + + /* free target vars * - need to go over all of them, not just up to the ones that are used - * currently, since there may be some lingering RNA paths from + * currently, since there may be some lingering RNA paths from * previous users needing freeing */ - DRIVER_TARGETS_LOOPER(dvar) + DRIVER_TARGETS_LOOPER(dvar) { /* free RNA path if applicable */ if (dtar->rna_path) MEM_freeN(dtar->rna_path); } DRIVER_TARGETS_LOOPER_END - + /* remove the variable from the driver */ BLI_freelinkN(variables, dvar); } @@ -1693,7 +1693,7 @@ void driver_free_variable_ex(ChannelDriver *driver, DriverVar *dvar) { /* remove and free the driver variable */ driver_free_variable(&driver->variables, dvar); - + #ifdef WITH_PYTHON /* since driver variables are cached, the expression needs re-compiling too */ if (driver->type == DRIVER_TYPE_PYTHON) @@ -1706,10 +1706,10 @@ void driver_variables_copy(ListBase *dst_vars, const ListBase *src_vars) { BLI_assert(BLI_listbase_is_empty(dst_vars)); BLI_duplicatelist(dst_vars, src_vars); - + for (DriverVar *dvar = dst_vars->first; dvar; dvar = dvar->next) { /* need to go over all targets so that we don't leave any dangling paths */ - DRIVER_TARGETS_LOOPER(dvar) + DRIVER_TARGETS_LOOPER(dvar) { /* make a copy of target's rna path if available */ if (dtar->rna_path) @@ -1723,25 +1723,25 @@ void driver_variables_copy(ListBase *dst_vars, const ListBase *src_vars) void driver_change_variable_type(DriverVar *dvar, int type) { const DriverVarTypeInfo *dvti = get_dvar_typeinfo(type); - + /* sanity check */ if (ELEM(NULL, dvar, dvti)) return; - + /* set the new settings */ dvar->type = type; dvar->num_targets = dvti->num_targets; - - /* make changes to the targets based on the defines for these types + + /* make changes to the targets based on the defines for these types * NOTE: only need to make sure the ones we're using here are valid... */ DRIVER_TARGETS_USED_LOOPER(dvar) { short flags = dvti->target_flags[tarIndex]; - + /* store the flags */ dtar->flag = flags; - + /* object ID types only, or idtype not yet initialized */ if ((flags & DTAR_FLAG_ID_OB_ONLY) || (dtar->idtype == 0)) dtar->idtype = ID_OB; @@ -1758,19 +1758,19 @@ void driver_variable_name_validate(DriverVar *dvar) '/', '\\', '?', ':', ';', '<', '>', '{', '}', '[', ']', '|', ' ', '.', '\t', '\n', '\r' }; - + /* sanity checks */ if (dvar == NULL) return; - + /* clear all invalid-name flags */ dvar->flag &= ~DVAR_ALL_INVALID_FLAGS; - + /* 0) Zero-length identifiers are not allowed */ if (dvar->name[0] == '\0') { dvar->flag |= DVAR_FLAG_INVALID_EMPTY; } - + /* 1) Must start with a letter */ /* XXX: We assume that valid unicode letters in other languages are ok too, hence the blacklisting */ if (IN_RANGE_INCL(dvar->name[0], '0', '9')) { @@ -1780,7 +1780,7 @@ void driver_variable_name_validate(DriverVar *dvar) /* NOTE: We don't allow names to start with underscores (i.e. it helps when ruling out security risks) */ dvar->flag |= DVAR_FLAG_INVALID_START_CHAR; } - + /* 2) Must not contain invalid stuff in the middle of the string */ if (strchr(dvar->name, ' ')) { dvar->flag |= DVAR_FLAG_INVALID_HAS_SPACE; @@ -1788,17 +1788,17 @@ void driver_variable_name_validate(DriverVar *dvar) if (strchr(dvar->name, '.')) { dvar->flag |= DVAR_FLAG_INVALID_HAS_DOT; } - + /* 3) Check for special characters - Either at start, or in the middle */ for (int i = 0; i < sizeof(special_char_blacklist); i++) { char *match = strchr(dvar->name, special_char_blacklist[i]); - + if (match == dvar->name) dvar->flag |= DVAR_FLAG_INVALID_START_CHAR; else if (match != NULL) dvar->flag |= DVAR_FLAG_INVALID_HAS_SPECIAL; } - + /* 4) Check if the name is a reserved keyword * NOTE: These won't confuse Python, but it will be impossible to use the variable * in an expression without Python misinterpreting what these are for @@ -1818,29 +1818,29 @@ void driver_variable_name_validate(DriverVar *dvar) DriverVar *driver_add_new_variable(ChannelDriver *driver) { DriverVar *dvar; - + /* sanity checks */ if (driver == NULL) return NULL; - + /* make a new variable */ dvar = MEM_callocN(sizeof(DriverVar), "DriverVar"); BLI_addtail(&driver->variables, dvar); - + /* give the variable a 'unique' name */ strcpy(dvar->name, CTX_DATA_(BLT_I18NCONTEXT_ID_ACTION, "var")); BLI_uniquename(&driver->variables, dvar, CTX_DATA_(BLT_I18NCONTEXT_ID_ACTION, "var"), '_', offsetof(DriverVar, name), sizeof(dvar->name)); - + /* set the default type to 'single prop' */ driver_change_variable_type(dvar, DVAR_TYPE_SINGLE_PROP); - + #ifdef WITH_PYTHON /* since driver variables are cached, the expression needs re-compiling too */ if (driver->type == DRIVER_TYPE_PYTHON) driver->flag |= DRIVER_FLAG_RENAMEVAR; #endif - + /* return the target */ return dvar; } @@ -1850,12 +1850,12 @@ void fcurve_free_driver(FCurve *fcu) { ChannelDriver *driver; DriverVar *dvar, *dvarn; - + /* sanity checks */ if (ELEM(NULL, fcu, fcu->driver)) return; driver = fcu->driver; - + /* free driver targets */ for (dvar = driver->variables.first; dvar; dvar = dvarn) { dvarn = dvar->next; @@ -1877,19 +1877,19 @@ void fcurve_free_driver(FCurve *fcu) ChannelDriver *fcurve_copy_driver(const ChannelDriver *driver) { ChannelDriver *ndriver; - + /* sanity checks */ if (driver == NULL) return NULL; - + /* copy all data */ ndriver = MEM_dupallocN(driver); ndriver->expr_comp = NULL; - + /* copy variables */ - BLI_listbase_clear(&ndriver->variables); /* to get rid of refs to non-copied data (that's still used on original) */ + BLI_listbase_clear(&ndriver->variables); /* to get rid of refs to non-copied data (that's still used on original) */ driver_variables_copy(&ndriver->variables, &driver->variables); - + /* return the new driver */ return ndriver; } @@ -1904,33 +1904,34 @@ float driver_get_variable_value(ChannelDriver *driver, DriverVar *dvar) /* sanity check */ if (ELEM(NULL, driver, dvar)) return 0.0f; - - /* call the relevant callbacks to get the variable value + + /* call the relevant callbacks to get the variable value * using the variable type info, storing the obtained value * in dvar->curval so that drivers can be debugged */ dvti = get_dvar_typeinfo(dvar->type); - + if (dvti && dvti->get_value) dvar->curval = dvti->get_value(driver, dvar); else dvar->curval = 0.0f; - + return dvar->curval; } /* Evaluate an Channel-Driver to get a 'time' value to use instead of "evaltime" * - "evaltime" is the frame at which F-Curve is being evaluated * - has to return a float value + * - driver_orig is where we cache Python expressions, in case of COW */ -float evaluate_driver(PathResolvedRNA *anim_rna, ChannelDriver *driver, const float evaltime) +float evaluate_driver(PathResolvedRNA *anim_rna, ChannelDriver *driver, ChannelDriver *driver_orig, const float evaltime) { DriverVar *dvar; - + /* check if driver can be evaluated */ - if (driver->flag & DRIVER_FLAG_INVALID) + if (driver_orig->flag & DRIVER_FLAG_INVALID) return 0.0f; - + switch (driver->type) { case DRIVER_TYPE_AVERAGE: /* average values of driver targets */ case DRIVER_TYPE_SUM: /* sum values of driver targets */ @@ -1945,13 +1946,13 @@ float evaluate_driver(PathResolvedRNA *anim_rna, ChannelDriver *driver, const fl /* more than one target, so average the values of the targets */ float value = 0.0f; int tot = 0; - + /* loop through targets, adding (hopefully we don't get any overflow!) */ for (dvar = driver->variables.first; dvar; dvar = dvar->next) { value += driver_get_variable_value(driver, dvar); tot++; } - + /* perform operations on the total if appropriate */ if (driver->type == DRIVER_TYPE_AVERAGE) driver->curval = tot ? (value / (float)tot) : 0.0f; @@ -1964,23 +1965,23 @@ float evaluate_driver(PathResolvedRNA *anim_rna, ChannelDriver *driver, const fl case DRIVER_TYPE_MAX: /* largest value */ { float value = 0.0f; - + /* loop through the variables, getting the values and comparing them to existing ones */ for (dvar = driver->variables.first; dvar; dvar = dvar->next) { /* get value */ float tmp_val = driver_get_variable_value(driver, dvar); - + /* store this value if appropriate */ if (dvar->prev) { /* check if greater/smaller than the baseline */ if (driver->type == DRIVER_TYPE_MAX) { /* max? */ - if (tmp_val > value) + if (tmp_val > value) value = tmp_val; } else { /* min? */ - if (tmp_val < value) + if (tmp_val < value) value = tmp_val; } } @@ -1989,7 +1990,7 @@ float evaluate_driver(PathResolvedRNA *anim_rna, ChannelDriver *driver, const fl value = tmp_val; } } - + /* store value in driver */ driver->curval = value; break; @@ -1998,8 +1999,8 @@ float evaluate_driver(PathResolvedRNA *anim_rna, ChannelDriver *driver, const fl { #ifdef WITH_PYTHON /* check for empty or invalid expression */ - if ( (driver->expression[0] == '\0') || - (driver->flag & DRIVER_FLAG_INVALID) ) + if ( (driver_orig->expression[0] == '\0') || + (driver_orig->flag & DRIVER_FLAG_INVALID) ) { driver->curval = 0.0f; } @@ -2009,7 +2010,7 @@ float evaluate_driver(PathResolvedRNA *anim_rna, ChannelDriver *driver, const fl */ BLI_mutex_lock(&python_driver_lock); - driver->curval = BPY_driver_exec(anim_rna, driver, evaltime); + driver->curval = BPY_driver_exec(anim_rna, driver, driver_orig, evaltime); BLI_mutex_unlock(&python_driver_lock); } @@ -2020,14 +2021,14 @@ float evaluate_driver(PathResolvedRNA *anim_rna, ChannelDriver *driver, const fl } default: { - /* special 'hack' - just use stored value + /* special 'hack' - just use stored value * This is currently used as the mechanism which allows animated settings to be able * to be changed via the UI. */ break; } } - + /* return value for driver */ return driver->curval; } @@ -2041,15 +2042,15 @@ float evaluate_driver(PathResolvedRNA *anim_rna, ChannelDriver *driver, const fl void correct_bezpart(float v1[2], float v2[2], float v3[2], float v4[2]) { float h1[2], h2[2], len1, len2, len, fac; - + /* calculate handle deltas */ h1[0] = v1[0] - v2[0]; h1[1] = v1[1] - v2[1]; - + h2[0] = v4[0] - v3[0]; h2[1] = v4[1] - v3[1]; - - /* calculate distances: + + /* calculate distances: * - len = span of time between keyframes * - len1 = length of handle of start key * - len2 = length of handle of end key @@ -2057,20 +2058,20 @@ void correct_bezpart(float v1[2], float v2[2], float v3[2], float v4[2]) len = v4[0] - v1[0]; len1 = fabsf(h1[0]); len2 = fabsf(h2[0]); - + /* if the handles have no length, no need to do any corrections */ if ((len1 + len2) == 0.0f) return; - + /* the two handles cross over each other, so force them - * apart using the proportion they overlap + * apart using the proportion they overlap */ if ((len1 + len2) > len) { fac = len / (len1 + len2); - + v2[0] = (v1[0] - fac * h1[0]); v2[1] = (v1[1] - fac * h1[1]); - + v3[0] = (v4[0] - fac * h2[0]); v3[1] = (v4[1] - fac * h2[1]); } @@ -2086,7 +2087,7 @@ static int findzero(float x, float q0, float q1, float q2, float q3, float *o) c1 = 3.0f * (q1 - q0); c2 = 3.0f * (q0 - 2.0f * q1 + q2); c3 = q3 - q0 + 3.0f * (q1 - q2); - + if (c3 != 0.0) { a = c2 / c3; b = c1 / c3; @@ -2096,21 +2097,21 @@ static int findzero(float x, float q0, float q1, float q2, float q3, float *o) p = b / 3 - a * a; q = (2 * a * a * a - a * b + c) / 2; d = q * q + p * p * p; - + if (d > 0.0) { t = sqrt(d); o[0] = (float)(sqrt3d(-q + t) + sqrt3d(-q - t) - a); - + if ((o[0] >= (float)SMALL) && (o[0] <= 1.000001f)) return 1; else return 0; } else if (d == 0.0) { t = sqrt3d(-q); o[0] = (float)(2 * t - a); - + if ((o[0] >= (float)SMALL) && (o[0] <= 1.000001f)) nr++; o[nr] = (float)(-t - a); - + if ((o[nr] >= (float)SMALL) && (o[nr] <= 1.000001f)) return nr + 1; else return nr; } @@ -2120,13 +2121,13 @@ static int findzero(float x, float q0, float q1, float q2, float q3, float *o) p = cos(phi / 3); q = sqrt(3 - 3 * p * p); o[0] = (float)(2 * t * p - a); - + if ((o[0] >= (float)SMALL) && (o[0] <= 1.000001f)) nr++; o[nr] = (float)(-t * (p + q) - a); - + if ((o[nr] >= (float)SMALL) && (o[nr] <= 1.000001f)) nr++; o[nr] = (float)(-t * (p - q) - a); - + if ((o[nr] >= (float)SMALL) && (o[nr] <= 1.000001f)) return nr + 1; else return nr; } @@ -2135,18 +2136,18 @@ static int findzero(float x, float q0, float q1, float q2, float q3, float *o) a = c2; b = c1; c = c0; - + if (a != 0.0) { /* discriminant */ p = b * b - 4 * a * c; - + if (p > 0) { p = sqrt(p); o[0] = (float)((-b - p) / (2 * a)); - + if ((o[0] >= (float)SMALL) && (o[0] <= 1.000001f)) nr++; o[nr] = (float)((-b + p) / (2 * a)); - + if ((o[nr] >= (float)SMALL) && (o[nr] <= 1.000001f)) return nr + 1; else return nr; } @@ -2158,7 +2159,7 @@ static int findzero(float x, float q0, float q1, float q2, float q3, float *o) } else if (b != 0.0) { o[0] = (float)(-c / b); - + if ((o[0] >= (float)SMALL) && (o[0] <= 1.000001f)) return 1; else return 0; } @@ -2166,7 +2167,7 @@ static int findzero(float x, float q0, float q1, float q2, float q3, float *o) o[0] = 0.0; return 1; } - + return 0; } } @@ -2217,13 +2218,13 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime unsigned int a; int b; float cvalue = 0.0f; - + /* get pointers */ a = fcu->totvert - 1; prevbezt = bezts; bezt = prevbezt + 1; lastbezt = prevbezt + a; - + /* evaluation time at or past endpoints? */ if (prevbezt->vec[1][0] >= evaltime) { /* before or on first keyframe */ @@ -2233,7 +2234,7 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime /* linear or bezier interpolation */ if (prevbezt->ipo == BEZT_IPO_LIN) { /* Use the next center point instead of our own handle for - * linear interpolated extrapolate + * linear interpolated extrapolate */ if (fcu->totvert == 1) { cvalue = prevbezt->vec[1][1]; @@ -2242,7 +2243,7 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime bezt = prevbezt + 1; dx = prevbezt->vec[1][0] - evaltime; fac = bezt->vec[1][0] - prevbezt->vec[1][0]; - + /* prevent division by zero */ if (fac) { fac = (bezt->vec[1][1] - prevbezt->vec[1][1]) / fac; @@ -2259,7 +2260,7 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime */ dx = prevbezt->vec[1][0] - evaltime; fac = prevbezt->vec[1][0] - prevbezt->vec[0][0]; - + /* prevent division by zero */ if (fac) { fac = (prevbezt->vec[1][1] - prevbezt->vec[0][1]) / fac; @@ -2271,8 +2272,8 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime } } else { - /* constant (BEZT_IPO_HORIZ) extrapolation or constant interpolation, - * so just extend first keyframe's value + /* constant (BEZT_IPO_HORIZ) extrapolation or constant interpolation, + * so just extend first keyframe's value */ cvalue = prevbezt->vec[1][1]; } @@ -2285,7 +2286,7 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime /* linear or bezier interpolation */ if (lastbezt->ipo == BEZT_IPO_LIN) { /* Use the next center point instead of our own handle for - * linear interpolated extrapolate + * linear interpolated extrapolate */ if (fcu->totvert == 1) { cvalue = lastbezt->vec[1][1]; @@ -2294,7 +2295,7 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime prevbezt = lastbezt - 1; dx = evaltime - lastbezt->vec[1][0]; fac = lastbezt->vec[1][0] - prevbezt->vec[1][0]; - + /* prevent division by zero */ if (fac) { fac = (lastbezt->vec[1][1] - prevbezt->vec[1][1]) / fac; @@ -2311,7 +2312,7 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime */ dx = evaltime - lastbezt->vec[1][0]; fac = lastbezt->vec[2][0] - lastbezt->vec[1][0]; - + /* prevent division by zero */ if (fac) { fac = (lastbezt->vec[2][1] - lastbezt->vec[1][1]) / fac; @@ -2323,8 +2324,8 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime } } else { - /* constant (BEZT_IPO_HORIZ) extrapolation or constant interpolation, - * so just extend last keyframe's value + /* constant (BEZT_IPO_HORIZ) extrapolation or constant interpolation, + * so just extend last keyframe's value */ cvalue = lastbezt->vec[1][1]; } @@ -2332,9 +2333,9 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime else { /* evaltime occurs somewhere in the middle of the curve */ bool exact = false; - + /* Use binary search to find appropriate keyframes... - * + * * The threshold here has the following constraints: * - 0.001 is too coarse -> We get artifacts with 2cm driver movements at 1BU = 1m (see T40332) * - 0.00001 is too fine -> Weird errors, like selecting the wrong keyframe range (see T39207), occur. @@ -2342,9 +2343,9 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime */ a = binarysearch_bezt_index_ex(bezts, evaltime, fcu->totvert, 0.0001, &exact); if (G.debug & G_DEBUG) printf("eval fcurve '%s' - %f => %u/%u, %d\n", fcu->rna_path, evaltime, a, fcu->totvert, exact); - + if (exact) { - /* index returned must be interpreted differently when it sits on top of an existing keyframe + /* index returned must be interpreted differently when it sits on top of an existing keyframe * - that keyframe is the start of the segment we need (see action_bug_2.blend in T39207) */ prevbezt = bezts + a; @@ -2357,7 +2358,7 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime bezt = bezts + a; prevbezt = (a > 0) ? (bezt - 1) : bezt; } - + /* use if the key is directly on the frame, rare cases this is needed else we get 0.0 instead. */ /* XXX: consult T39207 for examples of files where failure of these checks can cause issues */ if (exact) { @@ -2374,7 +2375,7 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime const float time = evaltime - prevbezt->vec[1][0]; const float amplitude = prevbezt->amplitude; const float period = prevbezt->period; - + /* value depends on interpolation mode */ if ((prevbezt->ipo == BEZT_IPO_CONST) || (fcu->flag & FCURVE_DISCRETE_VALUES) || (duration == 0)) { /* constant (evaltime not relevant, so no interpolation needed) */ @@ -2395,7 +2396,7 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime v3[1] = bezt->vec[0][1]; v4[0] = bezt->vec[1][0]; v4[1] = bezt->vec[1][1]; - + if (fabsf(v1[1] - v4[1]) < FLT_EPSILON && fabsf(v2[1] - v3[1]) < FLT_EPSILON && fabsf(v3[1] - v4[1]) < FLT_EPSILON) @@ -2408,7 +2409,7 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime else { /* adjust handles so that they don't overlap (forming a loop) */ correct_bezpart(v1, v2, v3, v4); - + /* try to get a value for this position - if failure, try another set of points */ b = findzero(evaltime, v1[0], v2[0], v3[0], v4[0], opl); if (b) { @@ -2421,12 +2422,12 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime } } break; - + case BEZT_IPO_LIN: /* linear - simply linearly interpolate between values of the two keyframes */ cvalue = BLI_easing_linear_ease(time, begin, change, duration); break; - + /* easing ............................................ */ case BEZT_IPO_BACK: switch (prevbezt->easing) { @@ -2439,13 +2440,13 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime case BEZT_IPO_EASE_IN_OUT: cvalue = BLI_easing_back_ease_in_out(time, begin, change, duration, prevbezt->back); break; - + default: /* default/auto: same as ease out */ cvalue = BLI_easing_back_ease_out(time, begin, change, duration, prevbezt->back); break; } break; - + case BEZT_IPO_BOUNCE: switch (prevbezt->easing) { case BEZT_IPO_EASE_IN: @@ -2457,13 +2458,13 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime case BEZT_IPO_EASE_IN_OUT: cvalue = BLI_easing_bounce_ease_in_out(time, begin, change, duration); break; - + default: /* default/auto: same as ease out */ cvalue = BLI_easing_bounce_ease_out(time, begin, change, duration); break; } break; - + case BEZT_IPO_CIRC: switch (prevbezt->easing) { case BEZT_IPO_EASE_IN: @@ -2475,7 +2476,7 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime case BEZT_IPO_EASE_IN_OUT: cvalue = BLI_easing_circ_ease_in_out(time, begin, change, duration); break; - + default: /* default/auto: same as ease in */ cvalue = BLI_easing_circ_ease_in(time, begin, change, duration); break; @@ -2493,13 +2494,13 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime case BEZT_IPO_EASE_IN_OUT: cvalue = BLI_easing_cubic_ease_in_out(time, begin, change, duration); break; - + default: /* default/auto: same as ease in */ cvalue = BLI_easing_cubic_ease_in(time, begin, change, duration); break; } break; - + case BEZT_IPO_ELASTIC: switch (prevbezt->easing) { case BEZT_IPO_EASE_IN: @@ -2511,13 +2512,13 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime case BEZT_IPO_EASE_IN_OUT: cvalue = BLI_easing_elastic_ease_in_out(time, begin, change, duration, amplitude, period); break; - + default: /* default/auto: same as ease out */ cvalue = BLI_easing_elastic_ease_out(time, begin, change, duration, amplitude, period); break; } break; - + case BEZT_IPO_EXPO: switch (prevbezt->easing) { case BEZT_IPO_EASE_IN: @@ -2529,13 +2530,13 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime case BEZT_IPO_EASE_IN_OUT: cvalue = BLI_easing_expo_ease_in_out(time, begin, change, duration); break; - + default: /* default/auto: same as ease in */ cvalue = BLI_easing_expo_ease_in(time, begin, change, duration); break; } break; - + case BEZT_IPO_QUAD: switch (prevbezt->easing) { case BEZT_IPO_EASE_IN: @@ -2547,13 +2548,13 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime case BEZT_IPO_EASE_IN_OUT: cvalue = BLI_easing_quad_ease_in_out(time, begin, change, duration); break; - + default: /* default/auto: same as ease in */ cvalue = BLI_easing_quad_ease_in(time, begin, change, duration); break; } break; - + case BEZT_IPO_QUART: switch (prevbezt->easing) { case BEZT_IPO_EASE_IN: @@ -2565,13 +2566,13 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime case BEZT_IPO_EASE_IN_OUT: cvalue = BLI_easing_quart_ease_in_out(time, begin, change, duration); break; - + default: /* default/auto: same as ease in */ cvalue = BLI_easing_quart_ease_in(time, begin, change, duration); break; } break; - + case BEZT_IPO_QUINT: switch (prevbezt->easing) { case BEZT_IPO_EASE_IN: @@ -2583,13 +2584,13 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime case BEZT_IPO_EASE_IN_OUT: cvalue = BLI_easing_quint_ease_in_out(time, begin, change, duration); break; - + default: /* default/auto: same as ease in */ cvalue = BLI_easing_quint_ease_in(time, begin, change, duration); break; } break; - + case BEZT_IPO_SINE: switch (prevbezt->easing) { case BEZT_IPO_EASE_IN: @@ -2601,14 +2602,14 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime case BEZT_IPO_EASE_IN_OUT: cvalue = BLI_easing_sine_ease_in_out(time, begin, change, duration); break; - + default: /* default/auto: same as ease in */ cvalue = BLI_easing_sine_ease_in(time, begin, change, duration); break; } break; - - + + default: cvalue = prevbezt->vec[1][1]; break; @@ -2619,7 +2620,7 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime if (G.debug & G_DEBUG) printf(" ERROR: failed eval - p=%f b=%f, t=%f (%f)\n", prevbezt->vec[1][0], bezt->vec[1][0], evaltime, fabsf(bezt->vec[1][0] - evaltime)); } } - + /* return value */ return cvalue; } @@ -2629,11 +2630,11 @@ static float fcurve_eval_samples(FCurve *fcu, FPoint *fpts, float evaltime) { FPoint *prevfpt, *lastfpt, *fpt; float cvalue = 0.0f; - + /* get pointers */ prevfpt = fpts; lastfpt = prevfpt + fcu->totvert - 1; - + /* evaluation time at or past endpoints? */ if (prevfpt->vec[0] >= evaltime) { /* before or on first sample, so just extend value */ @@ -2645,24 +2646,24 @@ static float fcurve_eval_samples(FCurve *fcu, FPoint *fpts, float evaltime) } else { float t = fabsf(evaltime - floorf(evaltime)); - + /* find the one on the right frame (assume that these are spaced on 1-frame intervals) */ fpt = prevfpt + ((int)evaltime - (int)prevfpt->vec[0]); - + /* if not exactly on the frame, perform linear interpolation with the next one */ if ((t != 0.0f) && (t < 1.0f)) cvalue = interpf(fpt->vec[1], (fpt + 1)->vec[1], 1.0f - t); else cvalue = fpt->vec[1]; } - + /* return value */ return cvalue; } /* ***************************** F-Curve - Evaluation ********************************* */ -/* Evaluate and return the value of the given F-Curve at the specified frame ("evaltime") +/* Evaluate and return the value of the given F-Curve at the specified frame ("evaltime") * Note: this is also used for drivers */ static float evaluate_fcurve_ex(FCurve *fcu, float evaltime, float cvalue) @@ -2673,16 +2674,16 @@ static float evaluate_fcurve_ex(FCurve *fcu, float evaltime, float cvalue) /* evaluate modifiers which modify time to evaluate the base curve at */ storage = evaluate_fmodifiers_storage_new(&fcu->modifiers); devaltime = evaluate_time_fmodifiers(storage, &fcu->modifiers, fcu, cvalue, evaltime); - - /* evaluate curve-data - * - 'devaltime' instead of 'evaltime', as this is the time that the last time-modifying + + /* evaluate curve-data + * - 'devaltime' instead of 'evaltime', as this is the time that the last time-modifying * F-Curve modifier on the stack requested the curve to be evaluated at */ if (fcu->bezt) cvalue = fcurve_eval_keyframes(fcu, fcu->bezt, devaltime); else if (fcu->fpt) cvalue = fcurve_eval_samples(fcu, fcu->fpt, devaltime); - + /* evaluate modifiers */ evaluate_value_fmodifiers(storage, &fcu->modifiers, fcu, &cvalue, devaltime); @@ -2693,7 +2694,7 @@ static float evaluate_fcurve_ex(FCurve *fcu, float evaltime, float cvalue) */ if (fcu->flag & FCURVE_INT_VALUES) cvalue = floorf(cvalue + 0.5f); - + /* return evaluated value */ return cvalue; } @@ -2705,7 +2706,7 @@ float evaluate_fcurve(FCurve *fcu, float evaltime) return evaluate_fcurve_ex(fcu, evaltime, 0.0); } -float evaluate_fcurve_driver(PathResolvedRNA *anim_rna, FCurve *fcu, float evaltime) +float evaluate_fcurve_driver(PathResolvedRNA *anim_rna, FCurve *fcu, ChannelDriver *driver_orig, float evaltime) { BLI_assert(fcu->driver != NULL); float cvalue = 0.0f; @@ -2715,7 +2716,7 @@ float evaluate_fcurve_driver(PathResolvedRNA *anim_rna, FCurve *fcu, float evalt */ if (fcu->driver) { /* evaltime now serves as input for the curve */ - evaltime = evaluate_driver(anim_rna, fcu->driver, evaltime); + evaltime = evaluate_driver(anim_rna, fcu->driver, driver_orig, evaltime); /* only do a default 1-1 mapping if it's unlikely that anything else will set a value... */ if (fcu->totvert == 0) { @@ -2753,7 +2754,7 @@ float evaluate_fcurve_driver(PathResolvedRNA *anim_rna, FCurve *fcu, float evalt /* Calculate the value of the given F-Curve at the given frame, and set its curval */ float calculate_fcurve(PathResolvedRNA *anim_rna, FCurve *fcu, float evaltime) { - /* only calculate + set curval (overriding the existing value) if curve has + /* only calculate + set curval (overriding the existing value) if curve has * any data which warrants this... */ if ((fcu->totvert) || (fcu->driver && !(fcu->driver->flag & DRIVER_FLAG_INVALID)) || @@ -2762,7 +2763,7 @@ float calculate_fcurve(PathResolvedRNA *anim_rna, FCurve *fcu, float evaltime) /* calculate and set curval (evaluates driver too if necessary) */ float curval; if (fcu->driver) { - curval = evaluate_fcurve_driver(anim_rna, fcu, evaltime); + curval = evaluate_fcurve_driver(anim_rna, fcu, fcu->driver, evaltime); } else { curval = evaluate_fcurve(fcu, evaltime); diff --git a/source/blender/blenkernel/intern/fmodifier.c b/source/blender/blenkernel/intern/fmodifier.c index f3d0a5fe085..b69bce088d2 100644 --- a/source/blender/blenkernel/intern/fmodifier.c +++ b/source/blender/blenkernel/intern/fmodifier.c @@ -67,7 +67,7 @@ void *fmodifiers_storage_get(FModifierStackStorage *storage, FModifier *fcm); * times. In addition to this, each modifier should have a type-info struct, where * its functions are attached for use. */ - + /* Template for type-info data: * - make a copy of this when creating new modifiers, and just change the functions * pointed to as necessary @@ -110,7 +110,7 @@ static FModifierTypeInfo FMI_MODNAME = { static void fcm_generator_free(FModifier *fcm) { FMod_Generator *data = (FMod_Generator *)fcm->data; - + /* free polynomial coefficients array */ if (data->coefficients) MEM_freeN(data->coefficients); @@ -120,7 +120,7 @@ static void fcm_generator_copy(FModifier *fcm, const FModifier *src) { FMod_Generator *gen = (FMod_Generator *)fcm->data; FMod_Generator *ogen = (FMod_Generator *)src->data; - + /* copy coefficients array? */ if (ogen->coefficients) gen->coefficients = MEM_dupallocN(ogen->coefficients); @@ -130,19 +130,19 @@ static void fcm_generator_new_data(void *mdata) { FMod_Generator *data = (FMod_Generator *)mdata; float *cp; - + /* set default generator to be linear 0-1 (gradient = 1, y-offset = 0) */ data->poly_order = 1; data->arraysize = 2; cp = data->coefficients = MEM_callocN(sizeof(float) * 2, "FMod_Generator_Coefs"); - cp[0] = 0; // y-offset + cp[0] = 0; // y-offset cp[1] = 1; // gradient } static void fcm_generator_verify(FModifier *fcm) { FMod_Generator *data = (FMod_Generator *)fcm->data; - + /* requirements depend on mode */ switch (data->mode) { case FCM_GENERATOR_POLYNOMIAL: /* expanded polynomial expression */ @@ -173,8 +173,8 @@ static void fcm_generator_verify(FModifier *fcm) static void fcm_generator_evaluate(FCurve *UNUSED(fcu), FModifier *fcm, float *cvalue, float evaltime) { FMod_Generator *data = (FMod_Generator *)fcm->data; - - /* behavior depends on mode + + /* behavior depends on mode * NOTE: the data in its default state is fine too */ switch (data->mode) { @@ -184,8 +184,8 @@ static void fcm_generator_evaluate(FCurve *UNUSED(fcu), FModifier *fcm, float *c float *powers = MEM_callocN(sizeof(float) * data->arraysize, "Poly Powers"); float value = 0.0f; unsigned int i; - - /* for each x^n, precalculate value based on previous one first... this should be + + /* for each x^n, precalculate value based on previous one first... this should be * faster that calling pow() for each entry */ for (i = 0; i < data->arraysize; i++) { @@ -195,11 +195,11 @@ static void fcm_generator_evaluate(FCurve *UNUSED(fcu), FModifier *fcm, float *c else powers[0] = 1; } - + /* for each coefficient, add to value, which we'll write to *cvalue in one go */ for (i = 0; i < data->arraysize; i++) value += data->coefficients[i] * powers[i]; - + /* only if something changed, write *cvalue in one go */ if (data->poly_order) { if (data->flag & FCM_GENERATOR_ADDITIVE) @@ -207,9 +207,9 @@ static void fcm_generator_evaluate(FCurve *UNUSED(fcu), FModifier *fcm, float *c else *cvalue = value; } - + /* cleanup */ - if (powers) + if (powers) MEM_freeN(powers); break; } @@ -217,11 +217,11 @@ static void fcm_generator_evaluate(FCurve *UNUSED(fcu), FModifier *fcm, float *c { float value = 1.0f, *cp = NULL; unsigned int i; - + /* for each coefficient pair, solve for that bracket before accumulating in value by multiplying */ for (cp = data->coefficients, i = 0; (cp) && (i < (unsigned int)data->poly_order); cp += 2, i++) value *= (cp[0] * evaltime + cp[1]); - + /* only if something changed, write *cvalue in one go */ if (data->poly_order) { if (data->flag & FCM_GENERATOR_ADDITIVE) @@ -266,7 +266,7 @@ static FModifierTypeInfo FMI_GENERATOR = { static void fcm_fn_generator_new_data(void *mdata) { FMod_FunctionGenerator *data = (FMod_FunctionGenerator *)mdata; - + /* set amplitude and phase multiplier to 1.0f so that something is generated */ data->amplitude = 1.0f; data->phase_multiplier = 1.0f; @@ -289,9 +289,9 @@ static void fcm_fn_generator_evaluate(FCurve *UNUSED(fcu), FModifier *fcm, float FMod_FunctionGenerator *data = (FMod_FunctionGenerator *)fcm->data; double arg = data->phase_multiplier * evaltime + data->phase_offset; double (*fn)(double v) = NULL; - + /* get function pointer to the func to use: - * WARNING: must perform special argument validation hereto guard against crashes + * WARNING: must perform special argument validation hereto guard against crashes */ switch (data->type) { /* simple ones */ @@ -304,7 +304,7 @@ static void fcm_fn_generator_evaluate(FCurve *UNUSED(fcu), FModifier *fcm, float case FCM_GENERATOR_FN_SINC: /* normalized sine wave */ fn = sinc; break; - + /* validation required */ case FCM_GENERATOR_FN_TAN: /* tangent wave */ { @@ -346,11 +346,11 @@ static void fcm_fn_generator_evaluate(FCurve *UNUSED(fcu), FModifier *fcm, float break; } - + /* execute function callback to set value if appropriate */ if (fn) { float value = (float)(data->amplitude * (float)fn(arg) + data->value_offset); - + if (data->flag & FCM_GENERATOR_ADDITIVE) *cvalue += value; else @@ -380,7 +380,7 @@ static FModifierTypeInfo FMI_FN_GENERATOR = { static void fcm_envelope_free(FModifier *fcm) { FMod_Envelope *env = (FMod_Envelope *)fcm->data; - + /* free envelope data array */ if (env->data) MEM_freeN(env->data); @@ -390,7 +390,7 @@ static void fcm_envelope_copy(FModifier *fcm, const FModifier *src) { FMod_Envelope *env = (FMod_Envelope *)fcm->data; FMod_Envelope *oenv = (FMod_Envelope *)src->data; - + /* copy envelope data array */ if (oenv->data) env->data = MEM_dupallocN(oenv->data); @@ -399,7 +399,7 @@ static void fcm_envelope_copy(FModifier *fcm, const FModifier *src) static void fcm_envelope_new_data(void *mdata) { FMod_Envelope *env = (FMod_Envelope *)mdata; - + /* set default min/max ranges */ env->min = -1.0f; env->max = 1.0f; @@ -408,7 +408,7 @@ static void fcm_envelope_new_data(void *mdata) static void fcm_envelope_verify(FModifier *fcm) { FMod_Envelope *env = (FMod_Envelope *)fcm->data; - + /* if the are points, perform bubble-sort on them, as user may have changed the order */ if (env->data) { /* XXX todo... */ @@ -421,13 +421,13 @@ static void fcm_envelope_evaluate(FCurve *UNUSED(fcu), FModifier *fcm, float *cv FCM_EnvelopeData *fed, *prevfed, *lastfed; float min = 0.0f, max = 0.0f, fac = 0.0f; int a; - + /* get pointers */ if (env->data == NULL) return; prevfed = env->data; fed = prevfed + 1; lastfed = prevfed + (env->totvert - 1); - + /* get min/max values for envelope at evaluation time (relative to mid-value) */ if (prevfed->time >= evaltime) { /* before or on first sample, so just extend value */ @@ -446,20 +446,20 @@ static void fcm_envelope_evaluate(FCurve *UNUSED(fcu), FModifier *fcm, float *cv /* evaltime occurs within the interval defined by these two envelope points */ if ((prevfed->time <= evaltime) && (fed->time >= evaltime)) { float afac, bfac, diff; - + diff = fed->time - prevfed->time; afac = (evaltime - prevfed->time) / diff; bfac = (fed->time - evaltime) / diff; - + min = bfac * prevfed->min + afac * fed->min; max = bfac * prevfed->max + afac * fed->max; - + break; } } } - - /* adjust *cvalue + + /* adjust *cvalue * - fac is the ratio of how the current y-value corresponds to the reference range * - thus, the new value is found by mapping the old range to the new! */ @@ -572,7 +572,7 @@ int BKE_fcm_envelope_find_index(FCM_EnvelopeData array[], float frame, int array /* Cycles F-Curve Modifier --------------------------- */ -/* This modifier changes evaltime to something that exists within the curve's frame-range, +/* This modifier changes evaltime to something that exists within the curve's frame-range, * then re-evaluates modifier stack up to this point using the new time. This re-entrant behavior * is very likely to be more time-consuming than the original approach... (which was tightly integrated into * the calculation code...). @@ -588,11 +588,11 @@ int BKE_fcm_envelope_find_index(FCM_EnvelopeData array[], float frame, int array typedef struct tFCMED_Cycles { float cycyofs; /* y-offset to apply */ } tFCMED_Cycles; - + static void fcm_cycles_new_data(void *mdata) { FMod_Cycles *data = (FMod_Cycles *)mdata; - + /* turn on cycles by default */ data->before_mode = data->after_mode = FCM_EXTRAPOLATE_CYCLIC; } @@ -605,38 +605,38 @@ static float fcm_cycles_time(FModifierStackStorage *storage, FCurve *fcu, FModif short side = 0, mode = 0; int cycles = 0; float ofs = 0; - + /* check if modifier is first in stack, otherwise disable ourself... */ /* FIXME... */ if (fcm->prev) { fcm->flag |= FMODIFIER_FLAG_DISABLED; return evaltime; } - + /* calculate new evaltime due to cyclic interpolation */ if (fcu && fcu->bezt) { BezTriple *prevbezt = fcu->bezt; BezTriple *lastbezt = prevbezt + fcu->totvert - 1; - + prevkey[0] = prevbezt->vec[1][0]; prevkey[1] = prevbezt->vec[1][1]; - + lastkey[0] = lastbezt->vec[1][0]; lastkey[1] = lastbezt->vec[1][1]; } else if (fcu && fcu->fpt) { FPoint *prevfpt = fcu->fpt; FPoint *lastfpt = prevfpt + fcu->totvert - 1; - + prevkey[0] = prevfpt->vec[0]; prevkey[1] = prevfpt->vec[1]; - + lastkey[0] = lastfpt->vec[0]; lastkey[1] = lastfpt->vec[1]; } else return evaltime; - + /* check if modifier will do anything * 1) if in data range, definitely don't do anything * 2) if before first frame or after last frame, make sure some cycling is in use @@ -659,26 +659,26 @@ static float fcm_cycles_time(FModifierStackStorage *storage, FCurve *fcu, FModif } if ((ELEM(0, side, mode))) return evaltime; - + /* find relative place within a cycle */ { float cycdx = 0, cycdy = 0; float cycle = 0, cyct = 0; - + /* calculate period and amplitude (total height) of a cycle */ cycdx = lastkey[0] - prevkey[0]; cycdy = lastkey[1] - prevkey[1]; - + /* check if cycle is infinitely small, to be point of being impossible to use */ if (cycdx == 0) return evaltime; - + /* calculate the 'number' of the cycle */ cycle = ((float)side * (evaltime - ofs) / cycdx); - + /* calculate the time inside the cycle */ cyct = fmod(evaltime - ofs, cycdx); - + /* check that cyclic is still enabled for the specified time */ if (cycles == 0) { /* catch this case so that we don't exit when we have (cycles = 0) @@ -687,11 +687,11 @@ static float fcm_cycles_time(FModifierStackStorage *storage, FCurve *fcu, FModif } else if (cycle > cycles) { /* we are too far away from range to evaluate - * TODO: but we should still hold last value... + * TODO: but we should still hold last value... */ return evaltime; } - + /* check if 'cyclic extrapolation', and thus calculate y-offset for this cycle */ if (mode == FCM_EXTRAPOLATE_CYCLIC_OFFSET) { if (side < 0) @@ -700,17 +700,17 @@ static float fcm_cycles_time(FModifierStackStorage *storage, FCurve *fcu, FModif cycyofs = (float)ceil((evaltime - ofs) / cycdx); cycyofs *= cycdy; } - + /* special case for cycle start/end */ if (cyct == 0.0f) { evaltime = (side == 1 ? lastkey[0] : prevkey[0]); - + if ((mode == FCM_EXTRAPOLATE_MIRROR) && ((int)cycle % 2)) evaltime = (side == 1 ? prevkey[0] : lastkey[0]); } /* calculate where in the cycle we are (overwrite evaltime to reflect this) */ else if ((mode == FCM_EXTRAPOLATE_MIRROR) && ((int)(cycle + 1) % 2)) { - /* when 'mirror' option is used and cycle number is odd, this cycle is played in reverse + /* when 'mirror' option is used and cycle number is odd, this cycle is played in reverse * - for 'before' extrapolation, we need to flip in a different way, otherwise values past * then end of the curve get referenced (result of fmod will be negative, and with different phase) */ @@ -725,22 +725,22 @@ static float fcm_cycles_time(FModifierStackStorage *storage, FCurve *fcu, FModif } if (evaltime < prevkey[0]) evaltime += cycdx; } - + /* store temp data if needed */ if (mode == FCM_EXTRAPOLATE_CYCLIC_OFFSET) { tFCMED_Cycles *edata; - + /* for now, this is just a float, but we could get more stuff... */ edata = MEM_callocN(sizeof(tFCMED_Cycles), "tFCMED_Cycles"); edata->cycyofs = cycyofs; fmodifiers_storage_put(storage, fcm, edata); } - + /* return the new frame to evaluate */ return evaltime; } - + static void fcm_cycles_evaluate(FModifierStackStorage *storage, FCurve *UNUSED(fcu), FModifier *fcm, float *cvalue, float UNUSED(evaltime)) { @@ -750,7 +750,7 @@ static void fcm_cycles_evaluate(FModifierStackStorage *storage, FCurve *UNUSED(f if (edata) { /* add cyclic offset - no need to check for now, otherwise the data wouldn't exist! */ *cvalue += edata->cycyofs; - + /* free temp data */ MEM_freeN(edata); fmodifiers_storage_remove(storage, fcm); @@ -779,7 +779,7 @@ static FModifierTypeInfo FMI_CYCLES = { static void fcm_noise_new_data(void *mdata) { FMod_Noise *data = (FMod_Noise *)mdata; - + /* defaults */ data->size = 1.0f; data->strength = 1.0f; @@ -788,18 +788,18 @@ static void fcm_noise_new_data(void *mdata) data->depth = 0; data->modification = FCM_NOISE_MODIF_REPLACE; } - + static void fcm_noise_evaluate(FCurve *UNUSED(fcu), FModifier *fcm, float *cvalue, float evaltime) { FMod_Noise *data = (FMod_Noise *)fcm->data; float noise; - + /* generate noise using good ol' Blender Noise * - 0.1 is passed as the 'z' value, otherwise evaluation fails for size = phase = 1 * with evaltime being an integer (which happens when evaluating on frame by frame basis) */ noise = BLI_turbulence(data->size, evaltime - data->offset, data->phase, 0.1f, data->depth); - + /* combine the noise with existing motion data */ switch (data->modification) { case FCM_NOISE_MODIF_ADD: @@ -837,7 +837,7 @@ static FModifierTypeInfo FMI_NOISE = { /* Filter F-Curve Modifier --------------------------- */ -#if 0 // XXX not yet implemented +#if 0 // XXX not yet implemented static FModifierTypeInfo FMI_FILTER = { FMODIFIER_TYPE_FILTER, /* type */ sizeof(FMod_Filter), /* size */ @@ -862,7 +862,7 @@ static FModifierTypeInfo FMI_FILTER = { static void fcm_python_free(FModifier *fcm) { FMod_Python *data = (FMod_Python *)fcm->data; - + /* id-properties */ IDP_FreeProperty(data->prop); MEM_freeN(data->prop); @@ -871,7 +871,7 @@ static void fcm_python_free(FModifier *fcm) static void fcm_python_new_data(void *mdata) { FMod_Python *data = (FMod_Python *)mdata; - + /* everything should be set correctly by calloc, except for the prop->type constant.*/ data->prop = MEM_callocN(sizeof(IDProperty), "PyFModifierProps"); data->prop->type = IDP_GROUP; @@ -881,7 +881,7 @@ static void fcm_python_copy(FModifier *fcm, const FModifier *src) { FMod_Python *pymod = (FMod_Python *)fcm->data; FMod_Python *opymod = (FMod_Python *)src->data; - + pymod->prop = IDP_CopyProperty(opymod->prop); } @@ -889,9 +889,9 @@ static void fcm_python_evaluate(FCurve *UNUSED(fcu), FModifier *UNUSED(fcm), flo { #ifdef WITH_PYTHON //FMod_Python *data = (FMod_Python *)fcm->data; - + /* FIXME... need to implement this modifier... - * It will need it execute a script using the custom properties + * It will need it execute a script using the custom properties */ #endif /* WITH_PYTHON */ } @@ -919,13 +919,13 @@ static FModifierTypeInfo FMI_PYTHON = { static float fcm_limits_time(FCurve *UNUSED(fcu), FModifier *fcm, float UNUSED(cvalue), float evaltime) { FMod_Limits *data = (FMod_Limits *)fcm->data; - + /* check for the time limits */ if ((data->flag & FCM_LIMIT_XMIN) && (evaltime < data->rect.xmin)) return data->rect.xmin; if ((data->flag & FCM_LIMIT_XMAX) && (evaltime > data->rect.xmax)) return data->rect.xmax; - + /* modifier doesn't change time */ return evaltime; } @@ -933,7 +933,7 @@ static float fcm_limits_time(FCurve *UNUSED(fcu), FModifier *fcm, float UNUSED(c static void fcm_limits_evaluate(FCurve *UNUSED(fcu), FModifier *fcm, float *cvalue, float UNUSED(evaltime)) { FMod_Limits *data = (FMod_Limits *)fcm->data; - + /* value limits now */ if ((data->flag & FCM_LIMIT_YMIN) && (*cvalue < data->rect.ymin)) *cvalue = data->rect.ymin; @@ -944,7 +944,7 @@ static void fcm_limits_evaluate(FCurve *UNUSED(fcu), FModifier *fcm, float *cval static FModifierTypeInfo FMI_LIMITS = { FMODIFIER_TYPE_LIMITS, /* type */ sizeof(FMod_Limits), /* size */ - FMI_TYPE_GENERATE_CURVE, /* action type */ /* XXX... err... */ + FMI_TYPE_GENERATE_CURVE, /* action type */ /* XXX... err... */ FMI_REQUIRES_RUNTIME_CHECK, /* requirements */ N_("Limits"), /* name */ "FMod_Limits", /* struct name */ @@ -963,7 +963,7 @@ static FModifierTypeInfo FMI_LIMITS = { static void fcm_stepped_new_data(void *mdata) { FMod_Stepped *data = (FMod_Stepped *)mdata; - + /* just need to set the step-size to 2-frames by default */ /* XXX: or would 5 be more normal? */ data->step_size = 2.0f; @@ -973,7 +973,7 @@ static float fcm_stepped_time(FCurve *UNUSED(fcu), FModifier *fcm, float UNUSED( { FMod_Stepped *data = (FMod_Stepped *)fcm->data; int snapblock; - + /* check range clamping to see if we should alter the timing to achieve the desired results */ if (data->flag & FCM_STEPPED_NO_BEFORE) { if (evaltime < data->start_frame) @@ -983,15 +983,15 @@ static float fcm_stepped_time(FCurve *UNUSED(fcu), FModifier *fcm, float UNUSED( if (evaltime > data->end_frame) return evaltime; } - - /* we snap to the start of the previous closest block of 'step_size' frames - * after the start offset has been discarded + + /* we snap to the start of the previous closest block of 'step_size' frames + * after the start offset has been discarded * - i.e. round down */ snapblock = (int)((evaltime - data->offset) / data->step_size); - - /* reapply the offset, and multiple the snapblock by the size of the steps to get - * the new time to evaluate at + + /* reapply the offset, and multiple the snapblock by the size of the steps to get + * the new time to evaluate at */ return ((float)snapblock * data->step_size) + data->offset; } @@ -999,7 +999,7 @@ static float fcm_stepped_time(FCurve *UNUSED(fcu), FModifier *fcm, float UNUSED( static FModifierTypeInfo FMI_STEPPED = { FMODIFIER_TYPE_STEPPED, /* type */ sizeof(FMod_Limits), /* size */ - FMI_TYPE_GENERATE_CURVE, /* action type */ /* XXX... err... */ + FMI_TYPE_GENERATE_CURVE, /* action type */ /* XXX... err... */ FMI_REQUIRES_RUNTIME_CHECK, /* requirements */ N_("Stepped"), /* name */ "FMod_Stepped", /* struct name */ @@ -1047,7 +1047,7 @@ const FModifierTypeInfo *get_fmodifier_typeinfo(const int type) fmods_init_typeinfo(); FMI_INIT = 0; } - + /* only return for valid types */ if ((type >= FMODIFIER_TYPE_NULL) && (type < FMODIFIER_NUM_TYPES)) @@ -1058,10 +1058,10 @@ const FModifierTypeInfo *get_fmodifier_typeinfo(const int type) else { printf("No valid F-Curve Modifier type-info data available. Type = %i\n", type); } - + return NULL; -} - +} + /* This function should always be used to get the appropriate type-info, as it * has checks which prevent segfaults in some weird cases. */ @@ -1081,11 +1081,11 @@ FModifier *add_fmodifier(ListBase *modifiers, int type, FCurve *owner_fcu) { const FModifierTypeInfo *fmi = get_fmodifier_typeinfo(type); FModifier *fcm; - + /* sanity checks */ if (ELEM(NULL, modifiers, fmi)) return NULL; - + /* special checks for whether modifier can be added */ if ((modifiers->first) && (type == FMODIFIER_TYPE_CYCLES)) { /* cycles modifier must be first in stack, so for now, don't add if it can't be */ @@ -1093,7 +1093,7 @@ FModifier *add_fmodifier(ListBase *modifiers, int type, FCurve *owner_fcu) printf("Error: Cannot add 'Cycles' modifier to F-Curve, as 'Cycles' modifier can only be first in stack.\n"); return NULL; } - + /* add modifier itself */ fcm = MEM_callocN(sizeof(FModifier), "F-Curve Modifier"); fcm->type = type; @@ -1101,14 +1101,14 @@ FModifier *add_fmodifier(ListBase *modifiers, int type, FCurve *owner_fcu) fcm->curve = owner_fcu; fcm->influence = 1.0f; BLI_addtail(modifiers, fcm); - + /* tag modifier as "active" if no other modifiers exist in the stack yet */ if (BLI_listbase_is_single(modifiers)) fcm->flag |= FMODIFIER_FLAG_ACTIVE; - + /* add modifier's data */ fcm->data = MEM_callocN(fmi->size, fmi->structName); - + /* init custom settings if necessary */ if (fmi->new_data) fmi->new_data(fcm->data); @@ -1116,7 +1116,7 @@ FModifier *add_fmodifier(ListBase *modifiers, int type, FCurve *owner_fcu) /* update the fcurve if the Cycles modifier is added */ if ((owner_fcu) && (type == FMODIFIER_TYPE_CYCLES)) calchandles_fcurve(owner_fcu); - + /* return modifier for further editing */ return fcm; } @@ -1126,23 +1126,23 @@ FModifier *copy_fmodifier(const FModifier *src) { const FModifierTypeInfo *fmi = fmodifier_get_typeinfo(src); FModifier *dst; - + /* sanity check */ if (src == NULL) return NULL; - + /* copy the base data, clearing the links */ dst = MEM_dupallocN(src); dst->next = dst->prev = NULL; dst->curve = NULL; - + /* make a new copy of the F-Modifier's data */ dst->data = MEM_dupallocN(src->data); - + /* only do specific constraints if required */ if (fmi && fmi->copy_data) fmi->copy_data(dst, src); - + /* return the new modifier */ return dst; } @@ -1151,20 +1151,20 @@ FModifier *copy_fmodifier(const FModifier *src) void copy_fmodifiers(ListBase *dst, const ListBase *src) { FModifier *fcm, *srcfcm; - + if (ELEM(NULL, dst, src)) return; - + BLI_listbase_clear(dst); BLI_duplicatelist(dst, src); - + for (fcm = dst->first, srcfcm = src->first; fcm && srcfcm; srcfcm = srcfcm->next, fcm = fcm->next) { const FModifierTypeInfo *fmi = fmodifier_get_typeinfo(fcm); - + /* make a new copy of the F-Modifier's data */ fcm->data = MEM_dupallocN(fcm->data); fcm->curve = NULL; - + /* only do specific constraints if required */ if (fmi && fmi->copy_data) fmi->copy_data(fcm, srcfcm); @@ -1175,11 +1175,11 @@ void copy_fmodifiers(ListBase *dst, const ListBase *src) bool remove_fmodifier(ListBase *modifiers, FModifier *fcm) { const FModifierTypeInfo *fmi = fmodifier_get_typeinfo(fcm); - + /* sanity check */ if (fcm == NULL) return false; - + /* removing the cycles modifier requires a handle update */ FCurve *update_fcu = (fcm->type == FMODIFIER_TYPE_CYCLES) ? fcm->curve : NULL; @@ -1187,11 +1187,11 @@ bool remove_fmodifier(ListBase *modifiers, FModifier *fcm) if (fcm->data) { if (fmi && fmi->free_data) fmi->free_data(fcm); - + /* free modifier's data (fcm->data) */ MEM_freeN(fcm->data); } - + /* remove modifier from stack */ if (modifiers) { BLI_freelinkN(modifiers, fcm); @@ -1214,11 +1214,11 @@ bool remove_fmodifier(ListBase *modifiers, FModifier *fcm) void free_fmodifiers(ListBase *modifiers) { FModifier *fcm, *fmn; - + /* sanity check */ if (modifiers == NULL) return; - + /* free each modifier in order - modifier is unlinked from list and freed */ for (fcm = modifiers->first; fcm; fcm = fmn) { fmn = fcm->next; @@ -1230,17 +1230,17 @@ void free_fmodifiers(ListBase *modifiers) FModifier *find_active_fmodifier(ListBase *modifiers) { FModifier *fcm; - + /* sanity checks */ if (ELEM(NULL, modifiers, modifiers->first)) return NULL; - + /* loop over modifiers until 'active' one is found */ for (fcm = modifiers->first; fcm; fcm = fcm->next) { if (fcm->flag & FMODIFIER_FLAG_ACTIVE) return fcm; } - + /* no modifier is active */ return NULL; } @@ -1249,55 +1249,55 @@ FModifier *find_active_fmodifier(ListBase *modifiers) void set_active_fmodifier(ListBase *modifiers, FModifier *fcm) { FModifier *fm; - + /* sanity checks */ if (ELEM(NULL, modifiers, modifiers->first)) return; - + /* deactivate all, and set current one active */ for (fm = modifiers->first; fm; fm = fm->next) fm->flag &= ~FMODIFIER_FLAG_ACTIVE; - + /* make given modifier active */ if (fcm) fcm->flag |= FMODIFIER_FLAG_ACTIVE; } -/* Do we have any modifiers which match certain criteria +/* Do we have any modifiers which match certain criteria * - mtype - type of modifier (if 0, doesn't matter) * - acttype - type of action to perform (if -1, doesn't matter) */ bool list_has_suitable_fmodifier(ListBase *modifiers, int mtype, short acttype) { FModifier *fcm; - + /* if there are no specific filtering criteria, just skip */ if ((mtype == 0) && (acttype == 0)) return (modifiers && modifiers->first); - + /* sanity checks */ if (ELEM(NULL, modifiers, modifiers->first)) return false; - + /* find the first mdifier fitting these criteria */ for (fcm = modifiers->first; fcm; fcm = fcm->next) { const FModifierTypeInfo *fmi = fmodifier_get_typeinfo(fcm); short mOk = 1, aOk = 1; /* by default 1, so that when only one test, won't fail */ - + /* check if applicable ones are fullfilled */ if (mtype) mOk = (fcm->type == mtype); if (acttype > -1) aOk = (fmi->acttype == acttype); - + /* if both are ok, we've found a hit */ if (mOk && aOk) return true; } - + /* no matches */ return false; -} +} /* Evaluation API --------------------------- */ @@ -1359,19 +1359,19 @@ void *fmodifiers_storage_get(FModifierStackStorage *storage, FModifier *fcm) static float eval_fmodifier_influence(FModifier *fcm, float evaltime) { float influence; - + /* sanity check */ - if (fcm == NULL) + if (fcm == NULL) return 0.0f; - - /* should we use influence stored in modifier or not + + /* should we use influence stored in modifier or not * NOTE: this is really just a hack so that we don't need to version patch old files ;) */ if (fcm->flag & FMODIFIER_FLAG_USEINFLUENCE) influence = fcm->influence; else influence = 1.0f; - + /* restricted range or full range? */ if (fcm->flag & FMODIFIER_FLAG_RANGERESTRICT) { if ((evaltime <= fcm->sfra) || (evaltime >= fcm->efra)) { @@ -1391,7 +1391,7 @@ static float eval_fmodifier_influence(FModifier *fcm, float evaltime) return influence * (evaltime - a) / (b - a); } } - + /* just return the influence of the modifier */ return influence; } @@ -1411,7 +1411,7 @@ float evaluate_time_fmodifiers(FModifierStackStorage *storage, ListBase *modifie FCurve *fcu, float cvalue, float evaltime) { FModifier *fcm; - + /* sanity checks */ if (ELEM(NULL, modifiers, modifiers->last)) return evaltime; @@ -1419,22 +1419,22 @@ float evaluate_time_fmodifiers(FModifierStackStorage *storage, ListBase *modifie if (fcu && fcu->flag & FCURVE_MOD_OFF) return evaltime; - /* Starting from the end of the stack, calculate the time effects of various stacked modifiers - * on the time the F-Curve should be evaluated at. + /* Starting from the end of the stack, calculate the time effects of various stacked modifiers + * on the time the F-Curve should be evaluated at. * * This is done in reverse order to standard evaluation, as when this is done in standard * order, each modifier would cause jumps to other points in the curve, forcing all - * previous ones to be evaluated again for them to be correct. However, if we did in the + * previous ones to be evaluated again for them to be correct. However, if we did in the * reverse order as we have here, we can consider them a macro to micro type of waterfall * effect, which should get us the desired effects when using layered time manipulations * (such as multiple 'stepped' modifiers in sequence, causing different stepping rates) */ for (fcm = modifiers->last; fcm; fcm = fcm->prev) { const FModifierTypeInfo *fmi = fmodifier_get_typeinfo(fcm); - - if (fmi == NULL) + + if (fmi == NULL) continue; - + /* if modifier cannot be applied on this frame (whatever scale it is on, it won't affect the results) * hence we shouldn't bother seeing what it would do given the chance */ @@ -1453,13 +1453,13 @@ float evaluate_time_fmodifiers(FModifierStackStorage *storage, ListBase *modifie else { nval = fmi->evaluate_modifier_time_storage(storage, fcu, fcm, cvalue, evaltime); } - + evaltime = interpf(nval, evaltime, influence); } } } } - + /* return the modified evaltime */ return evaltime; } @@ -1471,21 +1471,21 @@ void evaluate_value_fmodifiers(FModifierStackStorage *storage, ListBase *modifie FCurve *fcu, float *cvalue, float evaltime) { FModifier *fcm; - + /* sanity checks */ if (ELEM(NULL, modifiers, modifiers->first)) return; if (fcu->flag & FCURVE_MOD_OFF) return; - + /* evaluate modifiers */ for (fcm = modifiers->first; fcm; fcm = fcm->next) { const FModifierTypeInfo *fmi = fmodifier_get_typeinfo(fcm); - - if (fmi == NULL) + + if (fmi == NULL) continue; - + /* only evaluate if there's a callback for this, and if F-Modifier can be evaluated on this frame */ if ((fcm->flag & FMODIFIER_FLAG_RANGERESTRICT) == 0 || ((fcm->sfra <= evaltime) && (fcm->efra >= evaltime)) ) @@ -1507,7 +1507,7 @@ void evaluate_value_fmodifiers(FModifierStackStorage *storage, ListBase *modifie } } } -} +} /* ---------- */ @@ -1517,24 +1517,24 @@ void evaluate_value_fmodifiers(FModifierStackStorage *storage, ListBase *modifie void fcurve_bake_modifiers(FCurve *fcu, int start, int end) { ChannelDriver *driver; - + /* sanity checks */ /* TODO: make these tests report errors using reports not printf's */ if (ELEM(NULL, fcu, fcu->modifiers.first)) { printf("Error: No F-Curve with F-Curve Modifiers to Bake\n"); return; } - + /* temporarily, disable driver while we sample, so that they don't influence the outcome */ driver = fcu->driver; fcu->driver = NULL; - + /* bake the modifiers, by sampling the curve at each frame */ fcurve_store_samples(fcu, NULL, start, end, fcurve_samplingcb_evalcurve); - + /* free the modifiers now */ free_fmodifiers(&fcu->modifiers); - + /* restore driver */ fcu->driver = driver; } diff --git a/source/blender/blenkernel/intern/font.c b/source/blender/blenkernel/intern/font.c index f7ab5415d1c..36633663f9d 100644 --- a/source/blender/blenkernel/intern/font.c +++ b/source/blender/blenkernel/intern/font.c @@ -148,12 +148,12 @@ static PackedFile *get_builtin_packedfile(void) void *mem = MEM_mallocN(builtin_font_size, "vfd_builtin"); memcpy(mem, builtin_font_data, builtin_font_size); - + return newPackedFileMemory(mem, builtin_font_size); } } -static VFontData *vfont_get_data(Main *bmain, VFont *vfont) +static VFontData *vfont_get_data(VFont *vfont) { if (vfont == NULL) { return NULL; @@ -188,10 +188,10 @@ static VFontData *vfont_get_data(Main *bmain, VFont *vfont) } } else { - pf = newPackedFile(NULL, vfont->name, ID_BLEND_PATH(bmain, &vfont->id)); + pf = newPackedFile(NULL, vfont->name, ID_BLEND_PATH_FROM_GLOBAL(&vfont->id)); if (vfont->temp_pf == NULL) { - vfont->temp_pf = newPackedFile(NULL, vfont->name, ID_BLEND_PATH(bmain, &vfont->id)); + vfont->temp_pf = newPackedFile(NULL, vfont->name, ID_BLEND_PATH_FROM_GLOBAL(&vfont->id)); } } if (!pf) { @@ -205,7 +205,7 @@ static VFontData *vfont_get_data(Main *bmain, VFont *vfont) pf = get_builtin_packedfile(); } } - + if (pf) { vfont->data = BLI_vfontdata_from_freetypefont(pf); if (pf != vfont->packedfile) { @@ -246,10 +246,10 @@ VFont *BKE_vfont_load(Main *bmain, const char *filepath) PackedFile *pf; PackedFile *temp_pf = NULL; bool is_builtin; - + if (STREQ(filepath, FO_BUILTIN_NAME)) { BLI_strncpy(filename, filepath, sizeof(filename)); - + pf = get_builtin_packedfile(); is_builtin = true; } @@ -257,7 +257,7 @@ VFont *BKE_vfont_load(Main *bmain, const char *filepath) BLI_split_file_part(filepath, filename, sizeof(filename)); pf = newPackedFile(NULL, filepath, BKE_main_blendfile_path(bmain)); temp_pf = newPackedFile(NULL, filepath, BKE_main_blendfile_path(bmain)); - + is_builtin = false; } @@ -291,7 +291,7 @@ VFont *BKE_vfont_load(Main *bmain, const char *filepath) freePackedFile(pf); } } - + return vfont; } @@ -348,14 +348,14 @@ static VFont *which_vfont(Curve *cu, CharInfo *info) VFont *BKE_vfont_builtin_get(void) { VFont *vfont; - - for (vfont = G.main->vfont.first; vfont; vfont = vfont->id.next) { + + for (vfont = G_MAIN->vfont.first; vfont; vfont = vfont->id.next) { if (BKE_vfont_is_builtin(vfont)) { return vfont; } } - - return BKE_vfont_load(G.main, FO_BUILTIN_NAME); + + return BKE_vfont_load(G_MAIN, FO_BUILTIN_NAME); } static VChar *find_vfont_char(VFontData *vfd, unsigned int character) @@ -368,7 +368,7 @@ static void build_underline(Curve *cu, ListBase *nubase, const rctf *rect, { Nurb *nu2; BPoint *bp; - + nu2 = (Nurb *) MEM_callocN(sizeof(Nurb), "underline_nurb"); nu2->resolu = cu->resolu; nu2->bezt = NULL; @@ -423,7 +423,7 @@ static void build_underline(Curve *cu, ListBase *nubase, const rctf *rect, mul_v2_fl(bp[3].vec, cu->fsize); } -static void buildchar(Main *bmain, Curve *cu, ListBase *nubase, unsigned int character, CharInfo *info, +static void buildchar(Curve *cu, ListBase *nubase, unsigned int character, CharInfo *info, float ofsx, float ofsy, float rot, int charidx) { BezTriple *bezt1, *bezt2; @@ -433,7 +433,7 @@ static void buildchar(Main *bmain, Curve *cu, ListBase *nubase, unsigned int cha VChar *che = NULL; int i; - vfd = vfont_get_data(bmain, which_vfont(cu, info)); + vfd = vfont_get_data(which_vfont(cu, info)); if (!vfd) return; #if 0 @@ -454,7 +454,7 @@ static void buildchar(Main *bmain, Curve *cu, ListBase *nubase, unsigned int cha co = cosf(rot); che = find_vfont_char(vfd, character); - + /* Select the glyph data */ if (che) nu1 = che->nurbsbase.first; @@ -488,10 +488,10 @@ static void buildchar(Main *bmain, Curve *cu, ListBase *nubase, unsigned int cha } memcpy(bezt2, bezt1, i * sizeof(struct BezTriple)); nu2->bezt = bezt2; - + if (shear != 0.0f) { bezt2 = nu2->bezt; - + for (i = nu2->pntsu; i > 0; i--) { bezt2->vec[0][0] += shear * bezt2->vec[0][1]; bezt2->vec[1][0] += shear * bezt2->vec[1][1]; @@ -544,10 +544,10 @@ static void buildchar(Main *bmain, Curve *cu, ListBase *nubase, unsigned int cha fp[7] = (fp[7] + ofsy) * fsize; bezt2++; } - + BLI_addtail(nubase, nu2); } - + nu1 = nu1->next; } } @@ -557,7 +557,7 @@ int BKE_vfont_select_get(Object *ob, int *r_start, int *r_end) Curve *cu = ob->data; EditFont *ef = cu->editfont; int start, end, direction; - + if ((ob->type != OB_FONT) || (ef == NULL)) return 0; BLI_assert(ef->len >= 0); @@ -635,7 +635,7 @@ struct TempLineInfo { int wspace_nr; /* number of whitespaces of line */ }; -bool BKE_vfont_to_curve_ex(Main *bmain, Object *ob, Curve *cu, int mode, ListBase *r_nubase, +bool BKE_vfont_to_curve_ex(Object *ob, Curve *cu, int mode, ListBase *r_nubase, const wchar_t **r_text, int *r_text_len, bool *r_text_free, struct CharTrans **r_chartransdata) { @@ -677,11 +677,11 @@ bool BKE_vfont_to_curve_ex(Main *bmain, Object *ob, Curve *cu, int mode, ListBas if (cu->str == NULL) return ok; if (vfont == NULL) return ok; - vfd = vfont_get_data(bmain, vfont); + vfd = vfont_get_data(vfont); /* The VFont Data can not be found */ if (!vfd) return ok; - + if (ef) { slen = ef->len; mem = ef->textbuf; @@ -734,9 +734,9 @@ bool BKE_vfont_to_curve_ex(Main *bmain, Object *ob, Curve *cu, int mode, ListBas /* We assume the worst case: 1 character per line (is freed at end anyway) */ lineinfo = MEM_malloc_arrayN((slen * 2 + 1), sizeof(*lineinfo), "lineinfo"); - + linedist = cu->linedist; - + curbox = 0; textbox_scale(&tb_scale, &cu->tb[curbox], 1.0f / cu->fsize); use_textbox = (tb_scale.w != 0.0f); @@ -770,7 +770,7 @@ makebreak: if (vfont == NULL) break; if (vfont != oldvfont) { - vfd = vfont_get_data(bmain, vfont); + vfd = vfont_get_data(vfont); oldvfont = vfont; } @@ -886,7 +886,7 @@ makebreak: } else if (ascii == 9) { /* TAB */ float tabfac; - + ct->xof = xof; ct->yof = yof; ct->linenr = lnr; @@ -911,27 +911,27 @@ makebreak: sb->h = linedist * cu->fsize; sb->w = xof * cu->fsize; } - + if (ascii == 32) { - wsfac = cu->wordspace; + wsfac = cu->wordspace; wsnr++; } else { wsfac = 1.0f; } - + /* Set the width of the character */ twidth = char_width(cu, che, info); xof += (twidth * wsfac * (1.0f + (info->kern / 40.0f)) ) + xtrax; - + if (sb) { sb->w = (xof * cu->fsize) - sb->w; } } ct++; } - + cu->lines = 1; for (i = 0; i <= slen; i++) { ascii = mem[i]; @@ -1092,7 +1092,7 @@ makebreak: copy_m3_m4(cmat, cu->textoncurve->obmat); mul_m3_m3m3(cmat, cmat, imat3); sizefac = normalize_v3(cmat[0]) / cu->fsize; - + minx = miny = 1.0e20f; maxx = maxy = -1.0e20f; ct = chartransdata; @@ -1102,17 +1102,17 @@ makebreak: if (miny > ct->yof) miny = ct->yof; if (maxy < ct->yof) maxy = ct->yof; } - + /* we put the x-coordinaat exact at the curve, the y is rotated */ - + /* length correction */ distfac = sizefac * cu->textoncurve->curve_cache->path->totdist / (maxx - minx); timeofs = 0.0f; - + if (distfac > 1.0f) { /* path longer than text: spacemode involves */ distfac = 1.0f / distfac; - + if (cu->spacemode == CU_ALIGN_X_RIGHT) { timeofs = 1.0f - distfac; } @@ -1128,14 +1128,14 @@ makebreak: } distfac /= (maxx - minx); - + timeofs += distfac * cu->xof; /* not cyclic */ - + ct = chartransdata; for (i = 0; i < slen; i++, ct++) { float ctime, dtime, vec[4], tvec[4], rotvec[3]; float si, co; - + /* rotate around center character */ info = &custrinfo[i]; ascii = mem[i]; @@ -1144,7 +1144,7 @@ makebreak: } che = find_vfont_char(vfd, ascii); - + twidth = char_width(cu, che, info); dtime = distfac * 0.5f * twidth; @@ -1156,16 +1156,16 @@ makebreak: /* vec, tvec need 4 items */ where_on_path(cu->textoncurve, ctime, vec, tvec, NULL, NULL, NULL); where_on_path(cu->textoncurve, ctime + dtime, tvec, rotvec, NULL, NULL, NULL); - + mul_v3_fl(vec, sizefac); - + ct->rot = (float)M_PI - atan2f(rotvec[1], rotvec[0]); si = sinf(ct->rot); co = cosf(ct->rot); yof = ct->yof; - + ct->xof = vec[0] + si * yof; ct->yof = vec[1] + co * yof; @@ -1224,29 +1224,29 @@ makebreak: } } } - + /* cursor first */ if (ef) { float si, co; - + ct = &chartransdata[ef->pos]; si = sinf(ct->rot); co = cosf(ct->rot); f = ef->textcurs[0]; - + f[0] = cu->fsize * (-0.1f * co + ct->xof); f[1] = cu->fsize * ( 0.1f * si + ct->yof); - + f[2] = cu->fsize * ( 0.1f * co + ct->xof); f[3] = cu->fsize * (-0.1f * si + ct->yof); - + f[4] = cu->fsize * ( 0.1f * co + 0.8f * si + ct->xof); f[5] = cu->fsize * (-0.1f * si + 0.8f * co + ct->yof); - + f[6] = cu->fsize * (-0.1f * co + 0.8f * si + ct->xof); f[7] = cu->fsize * ( 0.1f * si + 0.8f * co + ct->yof); - + } if (mode == FO_SELCHANGE) { @@ -1258,7 +1258,7 @@ makebreak: if (mode == FO_EDIT) { /* make nurbdata */ BKE_nurbList_free(r_nubase); - + ct = chartransdata; for (i = 0; i < slen; i++) { unsigned int cha = (unsigned int) mem[i]; @@ -1274,7 +1274,7 @@ makebreak: } /* We do not want to see any character for \n or \r */ if (cha != '\n') - buildchar(bmain, cu, r_nubase, cha, info, ct->xof, ct->yof, ct->rot, i); + buildchar(cu, r_nubase, cha, info, ct->xof, ct->yof, ct->rot, i); if ((info->flag & CU_CHINFO_UNDERLINE) && (cha != '\n')) { float ulwidth, uloverlap = 0.0f; @@ -1340,19 +1340,19 @@ finally: } -bool BKE_vfont_to_curve_nubase(Main *bmain, Object *ob, int mode, ListBase *r_nubase) +bool BKE_vfont_to_curve_nubase(Object *ob, int mode, ListBase *r_nubase) { BLI_assert(ob->type == OB_FONT); - return BKE_vfont_to_curve_ex(bmain, ob, ob->data, mode, r_nubase, + return BKE_vfont_to_curve_ex(ob, ob->data, mode, r_nubase, NULL, NULL, NULL, NULL); } -bool BKE_vfont_to_curve(Main *bmain, Object *ob, int mode) +bool BKE_vfont_to_curve(Object *ob, int mode) { Curve *cu = ob->data; - return BKE_vfont_to_curve_ex(bmain, ob, ob->data, mode, &cu->nurb, NULL, NULL, NULL, NULL); + return BKE_vfont_to_curve_ex(ob, ob->data, mode, &cu->nurb, NULL, NULL, NULL, NULL); } diff --git a/source/blender/blenkernel/intern/gpencil.c b/source/blender/blenkernel/intern/gpencil.c index ee0d0b41898..e89508fd6c0 100644 --- a/source/blender/blenkernel/intern/gpencil.c +++ b/source/blender/blenkernel/intern/gpencil.c @@ -27,7 +27,7 @@ * \ingroup bke */ - + #include <stdio.h> #include <string.h> #include <stdlib.h> @@ -96,14 +96,14 @@ bool BKE_gpencil_free_strokes(bGPDframe *gpf) void BKE_gpencil_free_frames(bGPDlayer *gpl) { bGPDframe *gpf_next; - + /* error checking */ if (gpl == NULL) return; - + /* free frames */ for (bGPDframe *gpf = gpl->frames.first; gpf; gpf = gpf_next) { gpf_next = gpf->next; - + /* free strokes and their associated memory */ BKE_gpencil_free_strokes(gpf); BLI_freelinkN(&gpl->frames, gpf); @@ -177,14 +177,14 @@ void BKE_gpencil_free_brushes(ListBase *list) void BKE_gpencil_free_layers(ListBase *list) { bGPDlayer *gpl_next; - + /* error checking */ if (list == NULL) return; - + /* delete layers */ for (bGPDlayer *gpl = list->first; gpl; gpl = gpl_next) { gpl_next = gpl->next; - + /* free layers and their data */ BKE_gpencil_free_frames(gpl); BLI_freelinkN(list, gpl); @@ -212,15 +212,15 @@ bGPDframe *BKE_gpencil_frame_addnew(bGPDlayer *gpl, int cframe) { bGPDframe *gpf = NULL, *gf = NULL; short state = 0; - + /* error checking */ if (gpl == NULL) return NULL; - + /* allocate memory for this frame */ gpf = MEM_callocN(sizeof(bGPDframe), "bGPDframe"); gpf->framenum = cframe; - + /* find appropriate place to add frame */ if (gpl->frames.first) { for (gf = gpl->frames.first; gf; gf = gf->next) { @@ -229,7 +229,7 @@ bGPDframe *BKE_gpencil_frame_addnew(bGPDlayer *gpl, int cframe) state = -1; break; } - + /* if current frame has already exceeded the frame to add, add before */ if (gf->framenum > cframe) { BLI_insertlinkbefore(&gpl->frames, gf, gpf); @@ -238,14 +238,14 @@ bGPDframe *BKE_gpencil_frame_addnew(bGPDlayer *gpl, int cframe) } } } - + /* check whether frame was added successfully */ if (state == -1) { printf("Error: Frame (%d) existed already for this layer. Using existing frame\n", cframe); - + /* free the newly created one, and use the old one instead */ MEM_freeN(gpf); - + /* return existing frame instead... */ BLI_assert(gf != NULL); gpf = gf; @@ -254,7 +254,7 @@ bGPDframe *BKE_gpencil_frame_addnew(bGPDlayer *gpl, int cframe) /* add to end then! */ BLI_addtail(&gpl->frames, gpf); } - + /* return frame */ return gpf; } @@ -264,7 +264,7 @@ bGPDframe *BKE_gpencil_frame_addcopy(bGPDlayer *gpl, int cframe) { bGPDframe *new_frame; bool found = false; - + /* Error checking/handling */ if (gpl == NULL) { /* no layer */ @@ -274,16 +274,16 @@ bGPDframe *BKE_gpencil_frame_addcopy(bGPDlayer *gpl, int cframe) /* no active frame, so just create a new one from scratch */ return BKE_gpencil_frame_addnew(gpl, cframe); } - + /* Create a copy of the frame */ new_frame = BKE_gpencil_frame_duplicate(gpl->actframe); - + /* Find frame to insert it before */ for (bGPDframe *gpf = gpl->frames.first; gpf; gpf = gpf->next) { if (gpf->framenum > cframe) { /* Add it here */ BLI_insertlinkbefore(&gpl->frames, gpf, new_frame); - + found = true; break; } @@ -294,23 +294,23 @@ bGPDframe *BKE_gpencil_frame_addcopy(bGPDlayer *gpl, int cframe) BKE_gpencil_free_strokes(new_frame); MEM_freeN(new_frame); new_frame = NULL; - + found = true; break; } } - + if (found == false) { /* Add new frame to the end */ BLI_addtail(&gpl->frames, new_frame); } - + /* Ensure that frame is set up correctly, and return it */ if (new_frame) { new_frame->framenum = cframe; gpl->actframe = new_frame; } - + return new_frame; } @@ -318,17 +318,17 @@ bGPDframe *BKE_gpencil_frame_addcopy(bGPDlayer *gpl, int cframe) bGPDlayer *BKE_gpencil_layer_addnew(bGPdata *gpd, const char *name, bool setactive) { bGPDlayer *gpl; - + /* check that list is ok */ if (gpd == NULL) return NULL; - + /* allocate memory for frame and add to end of list */ gpl = MEM_callocN(sizeof(bGPDlayer), "bGPDlayer"); - + /* add to datablock */ BLI_addtail(&gpd->layers, gpl); - + /* set basic settings */ copy_v4_v4(gpl->color, U.gpencil_new_layer_col); /* Since GPv2 thickness must be 0 */ @@ -339,23 +339,23 @@ bGPDlayer *BKE_gpencil_layer_addnew(bGPdata *gpd, const char *name, bool setacti /* onion-skinning settings */ if (gpd->flag & GP_DATA_SHOW_ONIONSKINS) gpl->flag |= GP_LAYER_ONIONSKIN; - + gpl->flag |= (GP_LAYER_GHOST_PREVCOL | GP_LAYER_GHOST_NEXTCOL); - + ARRAY_SET_ITEMS(gpl->gcolor_prev, 0.145098f, 0.419608f, 0.137255f); /* green */ ARRAY_SET_ITEMS(gpl->gcolor_next, 0.125490f, 0.082353f, 0.529412f); /* blue */ - + /* high quality fill by default */ gpl->flag |= GP_LAYER_HQ_FILL; - + /* auto-name */ BLI_strncpy(gpl->info, name, sizeof(gpl->info)); BLI_uniquename(&gpd->layers, gpl, DATA_("GP_Layer"), '.', offsetof(bGPDlayer, info), sizeof(gpl->info)); - + /* make this one the active one */ if (setactive) BKE_gpencil_layer_setactive(gpd, gpl); - + /* return layer */ return gpl; } @@ -622,21 +622,21 @@ bGPDpalettecolor *BKE_gpencil_palettecolor_addnew(bGPDpalette *palette, const ch } /* add a new gp-datablock */ -bGPdata *BKE_gpencil_data_addnew(const char name[]) +bGPdata *BKE_gpencil_data_addnew(Main *bmain, const char name[]) { bGPdata *gpd; - + /* allocate memory for a new block */ - gpd = BKE_libblock_alloc(G.main, ID_GD, name, 0); - + gpd = BKE_libblock_alloc(bmain, ID_GD, name, 0); + /* initial settings */ gpd->flag = (GP_DATA_DISPINFO | GP_DATA_EXPAND); - + /* for now, stick to view is also enabled by default * since this is more useful... */ gpd->flag |= GP_DATA_VIEWALIGN; - + return gpd; } @@ -647,16 +647,16 @@ bGPDframe *BKE_gpencil_frame_duplicate(const bGPDframe *gpf_src) { bGPDstroke *gps_dst; bGPDframe *gpf_dst; - + /* error checking */ if (gpf_src == NULL) { return NULL; } - + /* make a copy of the source frame */ gpf_dst = MEM_dupallocN(gpf_src); gpf_dst->prev = gpf_dst->next = NULL; - + /* copy strokes */ BLI_listbase_clear(&gpf_dst->strokes); for (bGPDstroke *gps_src = gpf_src->strokes.first; gps_src; gps_src = gps_src->next) { @@ -667,7 +667,7 @@ bGPDframe *BKE_gpencil_frame_duplicate(const bGPDframe *gpf_src) gps_dst->flag |= GP_STROKE_RECALC_CACHES; BLI_addtail(&gpf_dst->strokes, gps_dst); } - + /* return new frame */ return gpf_dst; } @@ -727,28 +727,28 @@ bGPDlayer *BKE_gpencil_layer_duplicate(const bGPDlayer *gpl_src) const bGPDframe *gpf_src; bGPDframe *gpf_dst; bGPDlayer *gpl_dst; - + /* error checking */ if (gpl_src == NULL) { return NULL; } - + /* make a copy of source layer */ gpl_dst = MEM_dupallocN(gpl_src); gpl_dst->prev = gpl_dst->next = NULL; - + /* copy frames */ BLI_listbase_clear(&gpl_dst->frames); for (gpf_src = gpl_src->frames.first; gpf_src; gpf_src = gpf_src->next) { /* make a copy of source frame */ gpf_dst = BKE_gpencil_frame_duplicate(gpf_src); BLI_addtail(&gpl_dst->frames, gpf_dst); - + /* if source frame was the current layer's 'active' frame, reassign that too */ if (gpf_src == gpl_dst->actframe) gpl_dst->actframe = gpf_dst; } - + /* return new layer */ return gpl_dst; } @@ -805,6 +805,7 @@ bGPdata *BKE_gpencil_data_duplicate(Main *bmain, const bGPdata *gpd_src, bool in return gpd_dst; } else { + BLI_assert(bmain != NULL); bGPdata *gpd_copy; BKE_id_copy_ex(bmain, &gpd_src->id, (ID **)&gpd_copy, 0, false); return gpd_copy; @@ -823,16 +824,16 @@ void BKE_gpencil_stroke_sync_selection(bGPDstroke *gps) { bGPDspoint *pt; int i; - + /* error checking */ if (gps == NULL) return; - + /* we'll stop when we find the first selected point, * so initially, we must deselect */ gps->flag &= ~GP_STROKE_SELECT; - + for (i = 0, pt = gps->points; i < gps->totpoints; i++, pt++) { if (pt->flag & GP_SPOINT_SELECT) { gps->flag |= GP_STROKE_SELECT; @@ -848,16 +849,16 @@ void BKE_gpencil_frame_delete_laststroke(bGPDlayer *gpl, bGPDframe *gpf) { bGPDstroke *gps = (gpf) ? gpf->strokes.last : NULL; int cfra = (gpf) ? gpf->framenum : 0; /* assume that the current frame was not locked */ - + /* error checking */ if (ELEM(NULL, gpf, gps)) return; - + /* free the stroke and its data */ MEM_freeN(gps->points); MEM_freeN(gps->triangles); BLI_freelinkN(&gpf->strokes, gps); - + /* if frame has no strokes after this, delete it */ if (BLI_listbase_is_empty(&gpf->strokes)) { BKE_gpencil_layer_delframe(gpl, gpf); @@ -873,7 +874,7 @@ bool gpencil_layer_is_editable(const bGPDlayer *gpl) /* Sanity check */ if (gpl == NULL) return false; - + /* Layer must be: Visible + Editable */ if ((gpl->flag & (GP_LAYER_HIDE | GP_LAYER_LOCKED)) == 0) { /* Opacity must be sufficiently high that it is still "visible" @@ -883,7 +884,7 @@ bool gpencil_layer_is_editable(const bGPDlayer *gpl) return true; } } - + /* Something failed */ return false; } @@ -892,7 +893,7 @@ bool gpencil_layer_is_editable(const bGPDlayer *gpl) bGPDframe *BKE_gpencil_layer_find_frame(bGPDlayer *gpl, int cframe) { bGPDframe *gpf; - + /* Search in reverse order, since this is often used for playback/adding, * where it's less likely that we're interested in the earlier frames */ @@ -901,7 +902,7 @@ bGPDframe *BKE_gpencil_layer_find_frame(bGPDlayer *gpl, int cframe) return gpf; } } - + return NULL; } @@ -913,23 +914,23 @@ bGPDframe *BKE_gpencil_layer_getframe(bGPDlayer *gpl, int cframe, eGP_GetFrame_M { bGPDframe *gpf = NULL; short found = 0; - + /* error checking */ if (gpl == NULL) return NULL; - + /* check if there is already an active frame */ if (gpl->actframe) { gpf = gpl->actframe; - + /* do not allow any changes to layer's active frame if layer is locked from changes * or if the layer has been set to stay on the current frame */ if (gpl->flag & GP_LAYER_FRAMELOCK) return gpf; /* do not allow any changes to actframe if frame has painting tag attached to it */ - if (gpf->flag & GP_FRAME_PAINT) + if (gpf->flag & GP_FRAME_PAINT) return gpf; - + /* try to find matching frame */ if (gpf->framenum < cframe) { for (; gpf; gpf = gpf->next) { @@ -942,7 +943,7 @@ bGPDframe *BKE_gpencil_layer_getframe(bGPDlayer *gpl, int cframe, eGP_GetFrame_M break; } } - + /* set the appropriate frame */ if (addnew) { if ((found) && (gpf->framenum == cframe)) @@ -964,7 +965,7 @@ bGPDframe *BKE_gpencil_layer_getframe(bGPDlayer *gpl, int cframe, eGP_GetFrame_M break; } } - + /* set the appropriate frame */ if (addnew) { if ((found) && (gpf->framenum == cframe)) @@ -984,7 +985,7 @@ bGPDframe *BKE_gpencil_layer_getframe(bGPDlayer *gpl, int cframe, eGP_GetFrame_M /* check which of the ends to start checking from */ const int first = ((bGPDframe *)(gpl->frames.first))->framenum; const int last = ((bGPDframe *)(gpl->frames.last))->framenum; - + if (abs(cframe - first) > abs(cframe - last)) { /* find gp-frame which is less than or equal to cframe */ for (gpf = gpl->frames.last; gpf; gpf = gpf->prev) { @@ -1003,7 +1004,7 @@ bGPDframe *BKE_gpencil_layer_getframe(bGPDlayer *gpl, int cframe, eGP_GetFrame_M } } } - + /* set the appropriate frame */ if (addnew) { if ((found) && (gpf->framenum == cframe)) @@ -1028,7 +1029,7 @@ bGPDframe *BKE_gpencil_layer_getframe(bGPDlayer *gpl, int cframe, eGP_GetFrame_M /* gpl->actframe should still be NULL */ } } - + /* return */ return gpl->actframe; } @@ -1037,23 +1038,23 @@ bGPDframe *BKE_gpencil_layer_getframe(bGPDlayer *gpl, int cframe, eGP_GetFrame_M bool BKE_gpencil_layer_delframe(bGPDlayer *gpl, bGPDframe *gpf) { bool changed = false; - + /* error checking */ if (ELEM(NULL, gpl, gpf)) return false; - - /* if this frame was active, make the previous frame active instead + + /* if this frame was active, make the previous frame active instead * since it's tricky to set active frame otherwise */ if (gpl->actframe == gpf) gpl->actframe = gpf->prev; else gpl->actframe = NULL; - + /* free the frame and its data */ changed = BKE_gpencil_free_strokes(gpf); BLI_freelinkN(&gpl->frames, gpf); - + return changed; } @@ -1061,17 +1062,17 @@ bool BKE_gpencil_layer_delframe(bGPDlayer *gpl, bGPDframe *gpf) bGPDlayer *BKE_gpencil_layer_getactive(bGPdata *gpd) { bGPDlayer *gpl; - + /* error checking */ if (ELEM(NULL, gpd, gpd->layers.first)) return NULL; - + /* loop over layers until found (assume only one active) */ for (gpl = gpd->layers.first; gpl; gpl = gpl->next) { if (gpl->flag & GP_LAYER_ACTIVE) return gpl; } - + /* no active layer found */ return NULL; } @@ -1080,15 +1081,15 @@ bGPDlayer *BKE_gpencil_layer_getactive(bGPdata *gpd) void BKE_gpencil_layer_setactive(bGPdata *gpd, bGPDlayer *active) { bGPDlayer *gpl; - + /* error checking */ if (ELEM(NULL, gpd, gpd->layers.first, active)) return; - + /* loop over layers deactivating all */ for (gpl = gpd->layers.first; gpl; gpl = gpl->next) gpl->flag &= ~GP_LAYER_ACTIVE; - + /* set as active one */ active->flag |= GP_LAYER_ACTIVE; } @@ -1097,9 +1098,9 @@ void BKE_gpencil_layer_setactive(bGPdata *gpd, bGPDlayer *active) void BKE_gpencil_layer_delete(bGPdata *gpd, bGPDlayer *gpl) { /* error checking */ - if (ELEM(NULL, gpd, gpl)) + if (ELEM(NULL, gpd, gpl)) return; - + /* free layer */ BKE_gpencil_free_frames(gpl); BLI_freelinkN(&gpd->layers, gpl); @@ -1280,11 +1281,11 @@ void BKE_gpencil_palettecolor_changename(bGPdata *gpd, char *oldname, const char bGPDlayer *gpl; bGPDframe *gpf; bGPDstroke *gps; - + /* Sanity checks (gpd may not be set in the RNA pointers sometimes) */ if (ELEM(NULL, gpd, oldname, newname)) return; - + for (gpl = gpd->layers.first; gpl; gpl = gpl->next) { for (gpf = gpl->frames.first; gpf; gpf = gpf->next) { for (gps = gpf->strokes.first; gps; gps = gps->next) { @@ -1294,7 +1295,7 @@ void BKE_gpencil_palettecolor_changename(bGPdata *gpd, char *oldname, const char } } } - + } /* Delete all strokes of the color */ @@ -1303,11 +1304,11 @@ void BKE_gpencil_palettecolor_delete_strokes(struct bGPdata *gpd, char *name) bGPDlayer *gpl; bGPDframe *gpf; bGPDstroke *gps, *gpsn; - + /* Sanity checks (gpd may not be set in the RNA pointers sometimes) */ if (ELEM(NULL, gpd, name)) return; - + for (gpl = gpd->layers.first; gpl; gpl = gpl->next) { for (gpf = gpl->frames.first; gpf; gpf = gpf->next) { for (gps = gpf->strokes.first; gps; gps = gpsn) { diff --git a/source/blender/blenkernel/intern/icons.c b/source/blender/blenkernel/intern/icons.c index e409f8c91f0..37f53e81236 100644 --- a/source/blender/blenkernel/intern/icons.c +++ b/source/blender/blenkernel/intern/icons.c @@ -119,7 +119,7 @@ static void icon_free(void *val) } } -static void icon_free_data(Icon *icon) +static void icon_free_data(int icon_id, Icon *icon) { if (icon->obj_type == ICON_DATA_ID) { ((ID *)(icon->obj))->icon_id = 0; @@ -130,6 +130,12 @@ static void icon_free_data(Icon *icon) else if (icon->obj_type == ICON_DATA_GEOM) { ((struct Icon_Geom *)(icon->obj))->icon_id = 0; } + else if (icon->obj_type == ICON_DATA_STUDIOLIGHT) { + StudioLight *sl = icon->obj; + if (sl != NULL) { + BKE_studiolight_unset_icon_id(sl, icon_id); + } + } else { BLI_assert(0); } @@ -145,7 +151,7 @@ static int get_next_free_id(void) /* if we haven't used up the int number range, we just return the next int */ if (gNextIconId >= gFirstIconId) return gNextIconId++; - + /* now we try to find the smallest icon id not stored in the gIcons hash */ while (BLI_ghash_lookup(gIcons, SET_INT_IN_POINTER(startId)) && startId >= gFirstIconId) startId++; @@ -243,7 +249,7 @@ void BKE_previewimg_freefunc(void *link) if (prv->gputexture[i]) GPU_texture_free(prv->gputexture[i]); } - + MEM_freeN(prv); } } @@ -509,11 +515,11 @@ void BKE_icon_changed(const int icon_id) BLI_assert(BLI_thread_is_main()); Icon *icon = NULL; - + if (!icon_id || G.background) return; icon = BLI_ghash_lookup(gIcons, SET_INT_IN_POINTER(icon_id)); - + if (icon) { /* We *only* expect ID-tied icons here, not non-ID icon/preview! */ BLI_assert(icon->id_type != 0); @@ -640,7 +646,7 @@ Icon *BKE_icon_get(const int icon_id) Icon *icon = NULL; icon = BLI_ghash_lookup(gIcons, SET_INT_IN_POINTER(icon_id)); - + if (!icon) { printf("%s: Internal error, no icon for icon ID: %d\n", __func__, icon_id); return NULL; @@ -699,7 +705,7 @@ bool BKE_icon_delete(const int icon_id) Icon *icon = BLI_ghash_popkey(gIcons, SET_INT_IN_POINTER(icon_id), NULL); if (icon) { - icon_free_data(icon); + icon_free_data(icon_id, icon); icon_free(icon); return true; } @@ -722,7 +728,7 @@ bool BKE_icon_delete_unmanaged(const int icon_id) return false; } else { - icon_free_data(icon); + icon_free_data(icon_id, icon); icon_free(icon); return true; } diff --git a/source/blender/blenkernel/intern/idcode.c b/source/blender/blenkernel/intern/idcode.c index 4860f5a896d..0edeaab8900 100644 --- a/source/blender/blenkernel/intern/idcode.c +++ b/source/blender/blenkernel/intern/idcode.c @@ -47,7 +47,7 @@ typedef struct { const char *name, *plural; const char *i18n_context; - + int flags; #define IDTYPE_FLAGS_ISLINKABLE (1 << 0) } IDType; @@ -101,7 +101,7 @@ static IDType idtypes[] = { /* -1 for ID_ID */ BLI_STATIC_ASSERT((ARRAY_SIZE(idtypes) - 1 == MAX_LIBARRAY), "Missing IDType"); -static IDType *idtype_from_name(const char *str) +static IDType *idtype_from_name(const char *str) { int i = ARRAY_SIZE(idtypes); @@ -120,7 +120,7 @@ static IDType *idtype_from_code(short idcode) while (i--) if (idcode == idtypes[i].code) return &idtypes[i]; - + return NULL; } diff --git a/source/blender/blenkernel/intern/idprop.c b/source/blender/blenkernel/intern/idprop.c index 0c5078e3e36..ae9236e35fe 100644 --- a/source/blender/blenkernel/intern/idprop.c +++ b/source/blender/blenkernel/intern/idprop.c @@ -86,7 +86,7 @@ IDProperty *IDP_NewIDPArray(const char *name) prop->type = IDP_IDPARRAY; prop->len = 0; BLI_strncpy(prop->name, name, MAX_IDPROP_NAME); - + return prop; } @@ -113,14 +113,14 @@ IDProperty *IDP_CopyIDPArray(const IDProperty *array, const int flag) memcpy(GETPROP(narray, i), tmp, sizeof(IDProperty)); MEM_freeN(tmp); } - + return narray; } static void IDP_FreeIDPArray(IDProperty *prop, const bool do_id_user) { int i; - + BLI_assert(prop->type == IDP_IDPARRAY); for (i = 0; i < prop->len; i++) @@ -472,7 +472,7 @@ static IDProperty *IDP_CopyID(const IDProperty *prop, const int flag) static IDProperty *IDP_CopyGroup(const IDProperty *prop, const int flag) { IDProperty *newp, *link; - + BLI_assert(prop->type == IDP_GROUP); newp = idp_generic_copy(prop, flag); newp->len = prop->len; @@ -1051,7 +1051,7 @@ IDProperty *IDP_New(const char type, const IDPropertyTemplate *val, const char * prop->type = type; BLI_strncpy(prop->name, name, MAX_IDPROP_NAME); - + return prop; } diff --git a/source/blender/blenkernel/intern/image.c b/source/blender/blenkernel/intern/image.c index c1ecabcfb5a..b5abdcae2d4 100644 --- a/source/blender/blenkernel/intern/image.c +++ b/source/blender/blenkernel/intern/image.c @@ -342,19 +342,18 @@ void BKE_image_free_buffers(Image *ima) /** Free (or release) any data used by this image (does not free the image itself). */ void BKE_image_free(Image *ima) { - int a; - /* Also frees animdata. */ BKE_image_free_buffers(ima); image_free_packedfiles(ima); - for (a = 0; a < IMA_MAX_RENDER_SLOT; a++) { - if (ima->renders[a]) { - RE_FreeRenderResult(ima->renders[a]); - ima->renders[a] = NULL; + LISTBASE_FOREACH(RenderSlot *, slot, &ima->renderslots) { + if (slot->render) { + RE_FreeRenderResult(slot->render); + slot->render = NULL; } } + BLI_freelistN(&ima->renderslots); BKE_image_free_views(ima); MEM_SAFE_FREE(ima->stereo3d_format); @@ -380,6 +379,12 @@ static void image_init(Image *ima, short source, short type) if (source == IMA_SRC_VIEWER) ima->flag |= IMA_VIEW_AS_RENDER; + if (type == IMA_TYPE_R_RESULT) { + for (int i = 0; i < 8; i++) { + BKE_image_add_renderslot(ima, NULL); + } + } + BKE_color_managed_colorspace_settings_init(&ima->colorspace_settings); ima->stereo3d_format = MEM_callocN(sizeof(Stereo3dFormat), "Image Stereo Format"); } @@ -466,14 +471,15 @@ void BKE_image_copy_data(Main *UNUSED(bmain), Image *ima_dst, const Image *ima_s /* Cleanup stuff that cannot be copied. */ ima_dst->cache = NULL; ima_dst->rr = NULL; - for (int i = 0; i < IMA_MAX_RENDER_SLOT; i++) { - ima_dst->renders[i] = NULL; + + BLI_duplicatelist(&ima_dst->renderslots, &ima_src->renderslots); + LISTBASE_FOREACH(RenderSlot *, slot, &ima_dst->renderslots) { + slot->render = NULL; } BLI_listbase_clear(&ima_dst->anims); for (int i = 0; i < TEXTARGET_COUNT; i++) { - ima_dst->bindcode[i] = 0; ima_dst->gputexture[i] = NULL; } @@ -538,16 +544,14 @@ bool BKE_image_scale(Image *image, int width, int height) return (ibuf != NULL); } -bool BKE_image_has_bindcode(Image *ima) +bool BKE_image_has_opengl_texture(Image *ima) { - bool has_bindcode = false; for (int i = 0; i < TEXTARGET_COUNT; i++) { - if (ima->bindcode[i]) { - has_bindcode = true; - break; + if (ima->gputexture[i]) { + return true; } } - return has_bindcode; + return false; } static void image_init_color_management(Image *ima) @@ -572,7 +576,7 @@ static void image_init_color_management(Image *ima) char BKE_image_alpha_mode_from_extension_ex(const char *filepath) { - if (BLI_testextensie_n(filepath, ".exr", ".cin", ".dpx", ".hdr", NULL)) { + if (BLI_path_extension_check_n(filepath, ".exr", ".cin", ".dpx", ".hdr", NULL)) { return IMA_ALPHA_PREMUL; } else { @@ -603,7 +607,7 @@ Image *BKE_image_load(Main *bmain, const char *filepath) ima = image_alloc(bmain, BLI_path_basename(filepath), IMA_SRC_FILE, IMA_TYPE_IMAGE); STRNCPY(ima->name, filepath); - if (BLI_testextensie_array(filepath, imb_ext_movie)) + if (BLI_path_extension_check_array(filepath, imb_ext_movie)) ima->source = IMA_SRC_MOVIE; image_init_color_management(ima); @@ -930,21 +934,6 @@ void BKE_image_tag_time(Image *ima) ima->lastused = PIL_check_seconds_timer_i(); } -#if 0 -static void tag_all_images_time(Main *bmain) -{ - Image *ima; - int ctime = PIL_check_seconds_timer_i(); - - ima = bmain->image.first; - while (ima) { - if (ima->bindcode || ima->repbind || ima->ibufs.first) { - ima->lastused = ctime; - } - } -} -#endif - static uintptr_t image_mem_size(Image *image) { uintptr_t size = 0; @@ -1363,63 +1352,63 @@ static bool do_add_image_extension(char *string, const char imtype, const ImageF (void)im_format; /* may be unused, depends on build options */ if (imtype == R_IMF_IMTYPE_IRIS) { - if (!BLI_testextensie(string, extension_test = ".rgb")) + if (!BLI_path_extension_check(string, extension_test = ".rgb")) extension = extension_test; } else if (imtype == R_IMF_IMTYPE_IRIZ) { - if (!BLI_testextensie(string, extension_test = ".rgb")) + if (!BLI_path_extension_check(string, extension_test = ".rgb")) extension = extension_test; } #ifdef WITH_HDR else if (imtype == R_IMF_IMTYPE_RADHDR) { - if (!BLI_testextensie(string, extension_test = ".hdr")) + if (!BLI_path_extension_check(string, extension_test = ".hdr")) extension = extension_test; } #endif else if (ELEM(imtype, R_IMF_IMTYPE_PNG, R_IMF_IMTYPE_FFMPEG, R_IMF_IMTYPE_H264, R_IMF_IMTYPE_THEORA, R_IMF_IMTYPE_XVID)) { - if (!BLI_testextensie(string, extension_test = ".png")) + if (!BLI_path_extension_check(string, extension_test = ".png")) extension = extension_test; } #ifdef WITH_DDS else if (imtype == R_IMF_IMTYPE_DDS) { - if (!BLI_testextensie(string, extension_test = ".dds")) + if (!BLI_path_extension_check(string, extension_test = ".dds")) extension = extension_test; } #endif else if (ELEM(imtype, R_IMF_IMTYPE_TARGA, R_IMF_IMTYPE_RAWTGA)) { - if (!BLI_testextensie(string, extension_test = ".tga")) + if (!BLI_path_extension_check(string, extension_test = ".tga")) extension = extension_test; } else if (imtype == R_IMF_IMTYPE_BMP) { - if (!BLI_testextensie(string, extension_test = ".bmp")) + if (!BLI_path_extension_check(string, extension_test = ".bmp")) extension = extension_test; } #ifdef WITH_TIFF else if (imtype == R_IMF_IMTYPE_TIFF) { - if (!BLI_testextensie_n(string, extension_test = ".tif", ".tiff", NULL)) { + if (!BLI_path_extension_check_n(string, extension_test = ".tif", ".tiff", NULL)) { extension = extension_test; } } #endif #ifdef WITH_OPENIMAGEIO else if (imtype == R_IMF_IMTYPE_PSD) { - if (!BLI_testextensie(string, extension_test = ".psd")) + if (!BLI_path_extension_check(string, extension_test = ".psd")) extension = extension_test; } #endif #ifdef WITH_OPENEXR else if (imtype == R_IMF_IMTYPE_OPENEXR || imtype == R_IMF_IMTYPE_MULTILAYER) { - if (!BLI_testextensie(string, extension_test = ".exr")) + if (!BLI_path_extension_check(string, extension_test = ".exr")) extension = extension_test; } #endif #ifdef WITH_CINEON else if (imtype == R_IMF_IMTYPE_CINEON) { - if (!BLI_testextensie(string, extension_test = ".cin")) + if (!BLI_path_extension_check(string, extension_test = ".cin")) extension = extension_test; } else if (imtype == R_IMF_IMTYPE_DPX) { - if (!BLI_testextensie(string, extension_test = ".dpx")) + if (!BLI_path_extension_check(string, extension_test = ".dpx")) extension = extension_test; } #endif @@ -1427,35 +1416,35 @@ static bool do_add_image_extension(char *string, const char imtype, const ImageF else if (imtype == R_IMF_IMTYPE_JP2) { if (im_format) { if (im_format->jp2_codec == R_IMF_JP2_CODEC_JP2) { - if (!BLI_testextensie(string, extension_test = ".jp2")) + if (!BLI_path_extension_check(string, extension_test = ".jp2")) extension = extension_test; } else if (im_format->jp2_codec == R_IMF_JP2_CODEC_J2K) { - if (!BLI_testextensie(string, extension_test = ".j2c")) + if (!BLI_path_extension_check(string, extension_test = ".j2c")) extension = extension_test; } else BLI_assert(!"Unsupported jp2 codec was specified in im_format->jp2_codec"); } else { - if (!BLI_testextensie(string, extension_test = ".jp2")) + if (!BLI_path_extension_check(string, extension_test = ".jp2")) extension = extension_test; } } #endif else { // R_IMF_IMTYPE_AVIRAW, R_IMF_IMTYPE_AVIJPEG, R_IMF_IMTYPE_JPEG90 etc - if (!(BLI_testextensie_n(string, extension_test = ".jpg", ".jpeg", NULL))) + if (!(BLI_path_extension_check_n(string, extension_test = ".jpg", ".jpeg", NULL))) extension = extension_test; } if (extension) { /* prefer this in many cases to avoid .png.tga, but in certain cases it breaks */ /* remove any other known image extension */ - if (BLI_testextensie_array(string, imb_ext_image)) { - return BLI_replace_extension(string, FILE_MAX, extension); + if (BLI_path_extension_check_array(string, imb_ext_image)) { + return BLI_path_extension_replace(string, FILE_MAX, extension); } else { - return BLI_ensure_extension(string, FILE_MAX, extension); + return BLI_path_extension_ensure(string, FILE_MAX, extension); } } @@ -3015,7 +3004,7 @@ RenderResult *BKE_image_acquire_renderresult(Scene *scene, Image *ima) if (ima->render_slot == ima->last_render_slot) rr = RE_AcquireResultRead(RE_GetSceneRender(scene)); else - rr = ima->renders[ima->render_slot]; + rr = BKE_image_get_renderslot(ima, ima->render_slot)->render; /* set proper views */ image_init_multilayer_multiview(ima, rr); @@ -3039,7 +3028,7 @@ bool BKE_image_is_openexr(struct Image *ima) { #ifdef WITH_OPENEXR if (ELEM(ima->source, IMA_SRC_FILE, IMA_SRC_SEQUENCE)) { - return BLI_testextensie(ima->name, ".exr"); + return BLI_path_extension_check(ima->name, ".exr"); } #else UNUSED_VARS(ima); @@ -3049,27 +3038,39 @@ bool BKE_image_is_openexr(struct Image *ima) void BKE_image_backup_render(Scene *scene, Image *ima, bool free_current_slot) { - /* called right before rendering, ima->renders contains render + /* called right before rendering, ima->renderslots contains render * result pointers for everything but the current render */ Render *re = RE_GetSceneRender(scene); - int slot = ima->render_slot, last = ima->last_render_slot; - if (slot != last) { - ima->renders[last] = NULL; - RE_SwapResult(re, &ima->renders[last]); + /* Ensure we always have a valid render slot. */ + if (!ima->renderslots.first) { + BKE_image_add_renderslot(ima, NULL); + ima->render_slot = 0; + ima->last_render_slot = 0; + } + else if (ima->render_slot >= BLI_listbase_count(&ima->renderslots)) { + ima->render_slot = 0; + ima->last_render_slot = 0; + } + + RenderSlot *last_slot = BKE_image_get_renderslot(ima, ima->last_render_slot); + RenderSlot *cur_slot = BKE_image_get_renderslot(ima, ima->render_slot); - if (ima->renders[slot]) { + if (last_slot && ima->render_slot != ima->last_render_slot) { + last_slot->render = NULL; + RE_SwapResult(re, &last_slot->render); + + if (cur_slot->render) { if (free_current_slot) { - RE_FreeRenderResult(ima->renders[slot]); - ima->renders[slot] = NULL; + BKE_image_clear_renderslot(ima, NULL, ima->render_slot); } else { - RE_SwapResult(re, &ima->renders[slot]); + RE_SwapResult(re, &cur_slot->render); } } } - ima->last_render_slot = slot; + ima->last_render_slot = ima->render_slot; } /**************************** multiview load openexr *********************************/ @@ -3687,11 +3688,12 @@ static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser, void **r_loc if (BKE_image_is_stereo(ima) && (iuser->flag & IMA_SHOW_STEREO)) actview = iuser->multiview_eye; + RenderSlot *slot; if (from_render) { RE_AcquireResultImage(re, &rres, actview); } - else if (ima->renders[ima->render_slot]) { - rres = *(ima->renders[ima->render_slot]); + else if ((slot = BKE_image_get_renderslot(ima, ima->render_slot))->render) { + rres = *(slot->render); rres.have_combined = ((RenderView *)rres.views.first)->rectf != NULL; } else @@ -4721,3 +4723,97 @@ static void image_update_views_format(Image *ima, ImageUser *iuser) } } } + +/**************************** Render Slots ***************************/ + +RenderSlot *BKE_image_add_renderslot(Image *ima, const char *name) +{ + RenderSlot *slot = MEM_callocN(sizeof(RenderSlot), "Image new Render Slot"); + if (name && name[0]) { + BLI_strncpy(slot->name, name, sizeof(slot->name)); + } + else { + int n = BLI_listbase_count(&ima->renderslots) + 1; + BLI_snprintf(slot->name, sizeof(slot->name), "Slot %d", n); + } + BLI_addtail(&ima->renderslots, slot); + return slot; +} + +bool BKE_image_remove_renderslot(Image *ima, ImageUser *iuser, int index) +{ + int num_slots = BLI_listbase_count(&ima->renderslots); + if (index >= num_slots || num_slots == 1) { + return false; + } + + RenderSlot *remove_slot = BLI_findlink(&ima->renderslots, index); + RenderSlot *current_slot = BLI_findlink(&ima->renderslots, ima->render_slot); + RenderSlot *current_last_slot = BLI_findlink(&ima->renderslots, ima->last_render_slot); + + RenderSlot *next_slot; + if (current_slot == remove_slot) { + next_slot = BLI_findlink(&ima->renderslots, (index == num_slots - 1) ? index - 1 : index + 1); + } + else { + next_slot = current_slot; + } + + /* If the slot to be removed is the slot with the last render, make another slot the last render slot. */ + if (remove_slot == current_last_slot) { + /* Choose the currently selected slot unless that one is being removed, in that case take the next one. */ + RenderSlot *next_last_slot; + if (current_slot == remove_slot) + next_last_slot = next_slot; + else + next_last_slot = current_slot; + + if (!iuser) return false; + Render *re = RE_GetSceneRender(iuser->scene); + if (!re) return false; + RE_SwapResult(re, ¤t_last_slot->render); + RE_SwapResult(re, &next_last_slot->render); + current_last_slot = next_last_slot; + } + + current_slot = next_slot; + + BLI_remlink(&ima->renderslots, remove_slot); + + ima->render_slot = BLI_findindex(&ima->renderslots, current_slot); + ima->last_render_slot = BLI_findindex(&ima->renderslots, current_last_slot); + + if (remove_slot->render) { + RE_FreeRenderResult(remove_slot->render); + } + MEM_freeN(remove_slot); + + return true; +} + +bool BKE_image_clear_renderslot(Image *ima, ImageUser *iuser, int index) +{ + if (index == ima->last_render_slot) { + if (!iuser) return false; + if (G.is_rendering) return false; + Render *re = RE_GetSceneRender(iuser->scene); + if (!re) return false; + RE_ClearResult(re); + return true; + } + else { + RenderSlot *slot = BLI_findlink(&ima->renderslots, index); + if (!slot) return false; + if (slot->render) { + RE_FreeRenderResult(slot->render); + slot->render = NULL; + } + return true; + } +} + +RenderSlot *BKE_image_get_renderslot(Image *ima, int index) +{ + /* Can be NULL for images without render slots. */ + return BLI_findlink(&ima->renderslots, index); +} diff --git a/source/blender/blenkernel/intern/ipo.c b/source/blender/blenkernel/intern/ipo.c index 82178096b46..eeb09931211 100644 --- a/source/blender/blenkernel/intern/ipo.c +++ b/source/blender/blenkernel/intern/ipo.c @@ -37,7 +37,7 @@ * * -- Joshua Leung, Jan 2009 */ - + #include <math.h> #include <stdio.h> #include <string.h> @@ -92,18 +92,18 @@ void BKE_ipo_free(Ipo *ipo) { IpoCurve *icu, *icn; int n = 0; - + for (icu = ipo->curve.first; icu; icu = icn) { icn = icu->next; n++; - + if (icu->bezt) MEM_freeN(icu->bezt); if (icu->bp) MEM_freeN(icu->bp); if (icu->driver) MEM_freeN(icu->driver); - + BLI_freelinkN(&ipo->curve, icu); } - + if (G.debug & G_DEBUG) printf("Freed %d (Unconverted) Ipo-Curves from IPO '%s'\n", n, ipo->id.name + 2); } @@ -162,7 +162,7 @@ static AdrBit2Path *adrcode_bitmaps_to_paths(int blocktype, int adrcode, int *to RET_ABP(ob_layer_bits); } // XXX TODO: add other types... - + /* Normal curve */ return NULL; } @@ -176,7 +176,7 @@ static const char *ob_adrcodes_to_paths(int adrcode, int *array_index) { /* set array index like this in-case nothing sets it correctly */ *array_index = 0; - + /* result depends on adrcode */ switch (adrcode) { case OB_LOC_X: @@ -191,7 +191,7 @@ static const char *ob_adrcodes_to_paths(int adrcode, int *array_index) *array_index = 1; return "delta_location"; case OB_DLOC_Z: *array_index = 2; return "delta_location"; - + case OB_ROT_X: *array_index = 0; return "rotation_euler"; case OB_ROT_Y: @@ -204,7 +204,7 @@ static const char *ob_adrcodes_to_paths(int adrcode, int *array_index) *array_index = 1; return "delta_rotation_euler"; case OB_DROT_Z: *array_index = 2; return "delta_rotation_euler"; - + case OB_SIZE_X: *array_index = 0; return "scale"; case OB_SIZE_Y: @@ -246,18 +246,18 @@ static const char *ob_adrcodes_to_paths(int adrcode, int *array_index) break; #endif } - + return NULL; } -/* PoseChannel types +/* PoseChannel types * NOTE: pchan name comes from 'actname' added earlier... */ static const char *pchan_adrcodes_to_paths(int adrcode, int *array_index) { /* set array index like this in-case nothing sets it correctly */ *array_index = 0; - + /* result depends on adrcode */ switch (adrcode) { case AC_QUAT_W: @@ -268,21 +268,21 @@ static const char *pchan_adrcodes_to_paths(int adrcode, int *array_index) *array_index = 2; return "rotation_quaternion"; case AC_QUAT_Z: *array_index = 3; return "rotation_quaternion"; - + case AC_EUL_X: *array_index = 0; return "rotation_euler"; case AC_EUL_Y: *array_index = 1; return "rotation_euler"; case AC_EUL_Z: *array_index = 2; return "rotation_euler"; - + case AC_LOC_X: *array_index = 0; return "location"; case AC_LOC_Y: *array_index = 1; return "location"; case AC_LOC_Z: *array_index = 2; return "location"; - + case AC_SIZE_X: *array_index = 0; return "scale"; case AC_SIZE_Y: @@ -290,7 +290,7 @@ static const char *pchan_adrcodes_to_paths(int adrcode, int *array_index) case AC_SIZE_Z: *array_index = 2; return "scale"; } - + /* for debugging only */ printf("ERROR: unmatched PoseChannel setting (code %d)\n", adrcode); return NULL; @@ -301,7 +301,7 @@ static const char *constraint_adrcodes_to_paths(int adrcode, int *array_index) { /* set array index like this in-case nothing sets it correctly */ *array_index = 0; - + /* result depends on adrcode */ switch (adrcode) { case CO_ENFORCE: @@ -309,18 +309,18 @@ static const char *constraint_adrcodes_to_paths(int adrcode, int *array_index) case CO_HEADTAIL: // XXX this needs to be wrapped in RNA.. probably then this path will be invalid return "data.head_tail"; } - + return NULL; } -/* ShapeKey types +/* ShapeKey types * NOTE: as we don't have access to the keyblock where the data comes from (for now), * we'll just use numerical indices for now... */ static char *shapekey_adrcodes_to_paths(ID *id, int adrcode, int *UNUSED(array_index)) { static char buf[128]; - + /* block will be attached to ID_KE block... */ if (adrcode == 0) { /* adrcode=0 was the misnamed "speed" curve (now "evaluation time") */ @@ -330,7 +330,7 @@ static char *shapekey_adrcodes_to_paths(ID *id, int adrcode, int *UNUSED(array_i /* Find the name of the ShapeKey (i.e. KeyBlock) to look for */ Key *key = (Key *)id; KeyBlock *kb = BKE_keyblock_from_key(key, adrcode); - + /* setting that we alter is the "value" (i.e. keyblock.curval) */ if (kb) { /* Use the keyblock name, escaped, so that path lookups for this will work */ @@ -349,7 +349,7 @@ static const char *mtex_adrcodes_to_paths(int adrcode, int *UNUSED(array_index)) { const char *base = NULL, *prop = NULL; static char buf[128]; - + /* base part of path */ if (adrcode & MA_MAP1) base = "textures[0]"; else if (adrcode & MA_MAP2) base = "textures[1]"; @@ -369,7 +369,7 @@ static const char *mtex_adrcodes_to_paths(int adrcode, int *UNUSED(array_index)) else if (adrcode & MA_MAP16) base = "textures[15]"; else if (adrcode & MA_MAP17) base = "textures[16]"; else if (adrcode & MA_MAP18) base = "textures[17]"; - + /* property identifier for path */ adrcode = (adrcode & (MA_MAP1 - 1)); switch (adrcode) { @@ -404,7 +404,7 @@ static const char *mtex_adrcodes_to_paths(int adrcode, int *UNUSED(array_index)) case MAP_DISP: prop = "warp_factor"; break; } - + /* only build and return path if there's a property */ if (prop) { BLI_snprintf(buf, 128, "%s.%s", base, prop); @@ -419,26 +419,26 @@ static const char *texture_adrcodes_to_paths(int adrcode, int *array_index) { /* set array index like this in-case nothing sets it correctly */ *array_index = 0; - + /* result depends on adrcode */ switch (adrcode) { case TE_NSIZE: return "noise_size"; case TE_TURB: return "turbulence"; - + case TE_NDEPTH: // XXX texture RNA undefined //poin= &(tex->noisedepth); *type= IPO_SHORT; break; break; case TE_NTYPE: // XXX texture RNA undefined //poin= &(tex->noisetype); *type= IPO_SHORT; break; break; - + case TE_N_BAS1: return "noise_basis"; case TE_N_BAS2: return "noise_basis"; // XXX this is not yet defined in RNA... - + /* voronoi */ case TE_VNW1: *array_index = 0; return "feature_weights"; @@ -454,15 +454,15 @@ static const char *texture_adrcodes_to_paths(int adrcode, int *array_index) return "distance_metric"; case TE_VN_COLT: return "color_type"; - + /* distorted noise / voronoi */ case TE_ISCA: return "noise_intensity"; - + /* distorted noise */ case TE_DISTA: return "distortion_amount"; - + /* musgrave */ case TE_MG_TYP: // XXX texture RNA undefined // poin= &(tex->stype); *type= IPO_SHORT; break; @@ -477,20 +477,20 @@ static const char *texture_adrcodes_to_paths(int adrcode, int *array_index) return "offset"; case TE_MG_GAIN: return "gain"; - + case TE_COL_R: *array_index = 0; return "rgb_factor"; case TE_COL_G: *array_index = 1; return "rgb_factor"; case TE_COL_B: *array_index = 2; return "rgb_factor"; - + case TE_BRIGHT: return "brightness"; case TE_CONTRA: return "constrast"; } - + return NULL; } @@ -499,7 +499,7 @@ static const char *material_adrcodes_to_paths(int adrcode, int *array_index) { /* set array index like this in-case nothing sets it correctly */ *array_index = 0; - + /* result depends on adrcode */ switch (adrcode) { case MA_COL_R: @@ -508,73 +508,73 @@ static const char *material_adrcodes_to_paths(int adrcode, int *array_index) *array_index = 1; return "diffuse_color"; case MA_COL_B: *array_index = 2; return "diffuse_color"; - + case MA_SPEC_R: *array_index = 0; return "specular_color"; case MA_SPEC_G: *array_index = 1; return "specular_color"; case MA_SPEC_B: *array_index = 2; return "specular_color"; - + case MA_MIR_R: *array_index = 0; return "mirror_color"; case MA_MIR_G: *array_index = 1; return "mirror_color"; case MA_MIR_B: *array_index = 2; return "mirror_color"; - + case MA_ALPHA: return "alpha"; - + case MA_REF: return "diffuse_intensity"; - + case MA_EMIT: return "emit"; - + case MA_AMB: return "ambient"; - + case MA_SPEC: return "specular_intensity"; - + case MA_HARD: return "specular_hardness"; - + case MA_SPTR: return "specular_opacity"; - + case MA_IOR: return "ior"; - + case MA_HASIZE: return "halo.size"; - + case MA_TRANSLU: return "translucency"; - + case MA_RAYM: return "raytrace_mirror.reflect"; - + case MA_FRESMIR: return "raytrace_mirror.fresnel"; - + case MA_FRESMIRI: return "raytrace_mirror.fresnel_factor"; - + case MA_FRESTRA: return "raytrace_transparency.fresnel"; - + case MA_FRESTRAI: return "raytrace_transparency.fresnel_factor"; - + case MA_ADD: return "halo.add"; - + default: /* for now, we assume that the others were MTex channels */ return mtex_adrcodes_to_paths(adrcode, array_index); } - + return NULL; } @@ -583,7 +583,7 @@ static const char *camera_adrcodes_to_paths(int adrcode, int *array_index) { /* set array index like this in-case nothing sets it correctly */ *array_index = 0; - + /* result depends on adrcode */ switch (adrcode) { case CAM_LENS: @@ -591,29 +591,29 @@ static const char *camera_adrcodes_to_paths(int adrcode, int *array_index) if (ca->type == CAM_ORTHO) return "ortho_scale"; else - return "lens"; + return "lens"; #else // XXX lazy hack for now... return "lens"; #endif // XXX this cannot be resolved easily - + case CAM_STA: return "clip_start"; case CAM_END: return "clip_end"; - + #if 0 // XXX these are not defined in RNA case CAM_YF_APERT: poin = &(ca->YF_aperture); break; case CAM_YF_FDIST: poin = &(ca->YF_dofdist); break; #endif // XXX these are not defined in RNA - + case CAM_SHIFT_X: return "shift_x"; case CAM_SHIFT_Y: return "shift_y"; } - + /* unrecognised adrcode, or not-yet-handled ones! */ return NULL; } @@ -623,39 +623,39 @@ static const char *lamp_adrcodes_to_paths(int adrcode, int *array_index) { /* set array index like this in-case nothing sets it correctly */ *array_index = 0; - + /* result depends on adrcode */ switch (adrcode) { case LA_ENERGY: return "energy"; - + case LA_COL_R: *array_index = 0; return "color"; case LA_COL_G: *array_index = 1; return "color"; case LA_COL_B: *array_index = 2; return "color"; - + case LA_DIST: return "distance"; - + case LA_SPOTSI: return "spot_size"; case LA_SPOTBL: return "spot_blend"; - + case LA_QUAD1: return "linear_attenuation"; case LA_QUAD2: return "quadratic_attenuation"; - + case LA_HALOINT: return "halo_intensity"; - + default: /* for now, we assume that the others were MTex channels */ return mtex_adrcodes_to_paths(adrcode, array_index); } - + /* unrecognised adrcode, or not-yet-handled ones! */ return NULL; } @@ -665,7 +665,7 @@ static const char *sound_adrcodes_to_paths(int adrcode, int *array_index) { /* set array index like this in-case nothing sets it correctly */ *array_index = 0; - + /* result depends on adrcode */ switch (adrcode) { case SND_VOLUME: @@ -680,7 +680,7 @@ static const char *sound_adrcodes_to_paths(int adrcode, int *array_index) case SND_ATTEN: return "attenuation"; } - + /* unrecognised adrcode, or not-yet-handled ones! */ return NULL; } @@ -690,7 +690,7 @@ static const char *world_adrcodes_to_paths(int adrcode, int *array_index) { /* set array index like this in-case nothing sets it correctly */ *array_index = 0; - + /* result depends on adrcode */ switch (adrcode) { case WO_HOR_R: @@ -705,10 +705,10 @@ static const char *world_adrcodes_to_paths(int adrcode, int *array_index) *array_index = 1; return "zenith_color"; case WO_ZEN_B: *array_index = 2; return "zenith_color"; - + case WO_EXPOS: return "exposure"; - + case WO_MISI: return "mist.intensity"; case WO_MISTDI: @@ -717,11 +717,11 @@ static const char *world_adrcodes_to_paths(int adrcode, int *array_index) return "mist.start"; case WO_MISTHI: return "mist.height"; - + default: /* for now, we assume that the others were MTex channels */ return mtex_adrcodes_to_paths(adrcode, array_index); } - + return NULL; } @@ -730,7 +730,7 @@ static const char *particle_adrcodes_to_paths(int adrcode, int *array_index) { /* set array index like this in-case nothing sets it correctly */ *array_index = 0; - + /* result depends on adrcode */ switch (adrcode) { case PART_CLUMP: @@ -761,7 +761,7 @@ static const char *particle_adrcodes_to_paths(int adrcode, int *array_index) return "settings.kink_shape"; case PART_BB_TILT: return "settings.billboard_tilt"; - + /* PartDeflect needs to be sorted out properly in rna_object_force; * If anyone else works on this, but is unfamiliar, these particular * settings reference the particles of the system themselves @@ -811,64 +811,64 @@ static char *get_rna_access(ID *id, int blocktype, int adrcode, char actname[], char *rpath = NULL; char buf[512]; int dummy_index = 0; - + /* hack: if constname is set, we can only be dealing with an Constraint curve */ if (constname) blocktype = ID_CO; - + /* get property name based on blocktype */ switch (blocktype) { case ID_OB: /* object */ propname = ob_adrcodes_to_paths(adrcode, &dummy_index); break; - + case ID_PO: /* pose channel */ propname = pchan_adrcodes_to_paths(adrcode, &dummy_index); break; - + case ID_KE: /* shapekeys */ propname = shapekey_adrcodes_to_paths(id, adrcode, &dummy_index); break; - + case ID_CO: /* constraint */ propname = constraint_adrcodes_to_paths(adrcode, &dummy_index); break; - + case ID_TE: /* texture */ propname = texture_adrcodes_to_paths(adrcode, &dummy_index); break; - + case ID_MA: /* material */ propname = material_adrcodes_to_paths(adrcode, &dummy_index); break; - + case ID_CA: /* camera */ propname = camera_adrcodes_to_paths(adrcode, &dummy_index); break; - + case ID_LA: /* lamp */ propname = lamp_adrcodes_to_paths(adrcode, &dummy_index); break; - + case ID_SO: /* sound */ propname = sound_adrcodes_to_paths(adrcode, &dummy_index); break; - + case ID_WO: /* world */ propname = world_adrcodes_to_paths(adrcode, &dummy_index); break; - + case ID_PA: /* particle */ propname = particle_adrcodes_to_paths(adrcode, &dummy_index); break; - + case ID_CU: /* curve */ - /* this used to be a 'dummy' curve which got evaluated on the fly... + /* this used to be a 'dummy' curve which got evaluated on the fly... * now we've got real var for this! */ propname = "eval_time"; break; - + /* XXX problematic blocktypes */ case ID_SEQ: /* sequencer strip */ //SEQ_FAC1: @@ -885,28 +885,28 @@ static char *get_rna_access(ID *id, int blocktype, int adrcode, char actname[], } // poin= &(seq->facf0); // XXX this doesn't seem to be included anywhere in sequencer RNA... break; - + /* special hacks */ case -1: /* special case for rotdiff drivers... we don't need a property for this... */ break; - + /* TODO... add other blocktypes... */ default: printf("IPO2ANIMATO WARNING: No path for blocktype %d, adrcode %d yet\n", blocktype, adrcode); break; } - - /* check if any property found + + /* check if any property found * - blocktype < 0 is special case for a specific type of driver, where we don't need a property name... */ if ((propname == NULL) && (blocktype > 0)) { /* nothing was found, so exit */ - if (array_index) + if (array_index) *array_index = 0; - + BLI_dynstr_free(path); - + return NULL; } else { @@ -948,24 +948,24 @@ static char *get_rna_access(ID *id, int blocktype, int adrcode, char actname[], } BLI_dynstr_append(path, buf); - + /* need to add dot before property if there was anything precceding this */ if (buf[0]) BLI_dynstr_append(path, "."); - + /* now write name of property */ BLI_dynstr_append(path, propname); - + /* if there was no array index pointer provided, add it to the path */ if (array_index == NULL) { BLI_snprintf(buf, sizeof(buf), "[\"%d\"]", dummy_index); BLI_dynstr_append(path, buf); } - + /* convert to normal MEM_malloc'd string */ rpath = BLI_dynstr_get_cstring(path); BLI_dynstr_free(path); - + /* return path... */ return rpath; } @@ -983,21 +983,21 @@ static short adrcode_to_dtar_transchan(short adrcode) return DTAR_TRANSCHAN_LOCY; case OB_LOC_Z: return DTAR_TRANSCHAN_LOCZ; - + case OB_ROT_X: return DTAR_TRANSCHAN_ROTX; case OB_ROT_Y: return DTAR_TRANSCHAN_ROTY; case OB_ROT_Z: return DTAR_TRANSCHAN_ROTZ; - + case OB_SIZE_X: return DTAR_TRANSCHAN_SCALEX; case OB_SIZE_Y: return DTAR_TRANSCHAN_SCALEX; case OB_SIZE_Z: return DTAR_TRANSCHAN_SCALEX; - + default: return 0; } @@ -1007,10 +1007,10 @@ static short adrcode_to_dtar_transchan(short adrcode) static ChannelDriver *idriver_to_cdriver(IpoDriver *idriver) { ChannelDriver *cdriver; - + /* allocate memory for new driver */ cdriver = MEM_callocN(sizeof(ChannelDriver), "ChannelDriver"); - + /* if 'pydriver', just copy data across */ if (idriver->type == IPO_DRIVER_TYPE_PYTHON) { /* PyDriver only requires the expression to be copied */ @@ -1022,24 +1022,24 @@ static ChannelDriver *idriver_to_cdriver(IpoDriver *idriver) else { DriverVar *dvar = NULL; DriverTarget *dtar = NULL; - + /* this should be ok for all types here... */ cdriver->type = DRIVER_TYPE_AVERAGE; - + /* what to store depends on the 'blocktype' - object or posechannel */ if (idriver->blocktype == ID_AR) { /* PoseChannel */ if (idriver->adrcode == OB_ROT_DIFF) { /* Rotational Difference requires a special type of variable */ dvar = driver_add_new_variable(cdriver); driver_change_variable_type(dvar, DVAR_TYPE_ROT_DIFF); - + /* first bone target */ dtar = &dvar->targets[0]; dtar->id = (ID *)idriver->ob; dtar->idtype = ID_OB; if (idriver->name[0]) BLI_strncpy(dtar->pchan_name, idriver->name, sizeof(dtar->pchan_name)); - + /* second bone target (name was stored in same var as the first one) */ dtar = &dvar->targets[1]; dtar->id = (ID *)idriver->ob; @@ -1051,7 +1051,7 @@ static ChannelDriver *idriver_to_cdriver(IpoDriver *idriver) /* only a single variable, of type 'transform channel' */ dvar = driver_add_new_variable(cdriver); driver_change_variable_type(dvar, DVAR_TYPE_TRANSFORM_CHAN); - + /* only requires a single target */ dtar = &dvar->targets[0]; dtar->id = (ID *)idriver->ob; @@ -1066,7 +1066,7 @@ static ChannelDriver *idriver_to_cdriver(IpoDriver *idriver) /* only a single variable, of type 'transform channel' */ dvar = driver_add_new_variable(cdriver); driver_change_variable_type(dvar, DVAR_TYPE_TRANSFORM_CHAN); - + /* only requires single target */ dtar = &dvar->targets[0]; dtar->id = (ID *)idriver->ob; @@ -1074,12 +1074,12 @@ static ChannelDriver *idriver_to_cdriver(IpoDriver *idriver) dtar->transChan = adrcode_to_dtar_transchan(idriver->adrcode); } } - + /* return the new one */ return cdriver; } -/* Add F-Curve to the correct list +/* Add F-Curve to the correct list * - grpname is needed to be used as group name where relevant, and is usually derived from actname */ static void fcurve_add_to_list(ListBase *groups, ListBase *list, FCurve *fcu, char *grpname, int muteipo) @@ -1091,7 +1091,7 @@ static void fcurve_add_to_list(ListBase *groups, ListBase *list, FCurve *fcu, ch */ bAction tmp_act; bActionGroup *agrp = NULL; - + /* init the temp action */ memset(&tmp_act, 0, sizeof(bAction)); // XXX only enable this line if we get errors tmp_act.groups.first = groups->first; @@ -1099,7 +1099,7 @@ static void fcurve_add_to_list(ListBase *groups, ListBase *list, FCurve *fcu, ch tmp_act.curves.first = list->first; tmp_act.curves.last = list->last; /* ... xxx, the other vars don't need to be filled in */ - + /* get the group to use */ agrp = BKE_action_group_find_name(&tmp_act, grpname); /* no matching group, so add one */ @@ -1116,14 +1116,14 @@ static void fcurve_add_to_list(ListBase *groups, ListBase *list, FCurve *fcu, ch BLI_uniquename(&tmp_act.groups, agrp, DATA_("Group"), '.', offsetof(bActionGroup, name), sizeof(agrp->name)); } - + /* add F-Curve to group */ /* WARNING: this func should only need to look at the stuff we initialized, if not, things may crash */ action_groups_add_channel(&tmp_act, agrp, fcu); - + if (agrp->flag & AGRP_MUTED) /* flush down */ fcu->flag |= FCURVE_MUTED; - + /* set the output lists based on the ones in the temp action */ groups->first = tmp_act.groups.first; groups->last = tmp_act.groups.last; @@ -1136,7 +1136,7 @@ static void fcurve_add_to_list(ListBase *groups, ListBase *list, FCurve *fcu, ch } } -/* Convert IPO-Curve to F-Curve (including Driver data), and free any of the old data that +/* Convert IPO-Curve to F-Curve (including Driver data), and free any of the old data that * is not relevant, BUT do not free the IPO-Curve itself... * actname: name of Action-Channel (if applicable) that IPO-Curve's IPO-block belonged to * constname: name of Constraint-Channel (if applicable) that IPO-Curve's IPO-block belonged to @@ -1147,21 +1147,21 @@ static void icu_to_fcurves(ID *id, ListBase *groups, ListBase *list, IpoCurve *i AdrBit2Path *abp; FCurve *fcu; int totbits; - + /* allocate memory for a new F-Curve */ fcu = MEM_callocN(sizeof(FCurve), "FCurve"); - + /* convert driver */ if (icu->driver) fcu->driver = idriver_to_cdriver(icu->driver); - + /* copy flags */ if (icu->flag & IPO_VISIBLE) fcu->flag |= FCURVE_VISIBLE; if (icu->flag & IPO_SELECT) fcu->flag |= FCURVE_SELECTED; if (icu->flag & IPO_ACTIVE) fcu->flag |= FCURVE_ACTIVE; if (icu->flag & IPO_MUTE) fcu->flag |= FCURVE_MUTED; if (icu->flag & IPO_PROTECT) fcu->flag |= FCURVE_PROTECTED; - + /* set extrapolation */ switch (icu->extrap) { case IPO_HORIZ: /* constant extrapolation */ @@ -1174,12 +1174,12 @@ static void icu_to_fcurves(ID *id, ListBase *groups, ListBase *list, IpoCurve *i case IPO_CYCL: /* cyclic extrapolation */ case IPO_CYCLX: /* cyclic extrapolation + offset */ { - /* Add a new FModifier (Cyclic) instead of setting extend value + /* Add a new FModifier (Cyclic) instead of setting extend value * as that's the new equivalent of that option. */ FModifier *fcm = add_fmodifier(&fcu->modifiers, FMODIFIER_TYPE_CYCLES, fcu); FMod_Cycles *data = (FMod_Cycles *)fcm->data; - + /* if 'offset' one is in use, set appropriate settings */ if (icu->extrap == IPO_CYCLX) data->before_mode = data->after_mode = FCM_EXTRAPOLATE_CYCLIC_OFFSET; @@ -1188,20 +1188,20 @@ static void icu_to_fcurves(ID *id, ListBase *groups, ListBase *list, IpoCurve *i break; } } - + /* -------- */ - + /* get adrcode <-> bitflags mapping to handle nasty bitflag curves? */ abp = adrcode_bitmaps_to_paths(icu->blocktype, icu->adrcode, &totbits); if (abp && totbits) { FCurve *fcurve; int b; - + if (G.debug & G_DEBUG) printf("\tconvert bitflag ipocurve, totbits = %d\n", totbits); - + /* add the 'only int values' flag */ fcu->flag |= (FCURVE_INT_VALUES | FCURVE_DISCRETE_VALUES); - + /* for each bit we have to remap + check for: * 1) we need to make copy the existing F-Curve data (fcu -> fcurve), * except for the last one which will use the original @@ -1210,46 +1210,46 @@ static void icu_to_fcurves(ID *id, ListBase *groups, ListBase *list, IpoCurve *i */ for (b = 0; b < totbits; b++, abp++) { unsigned int i = 0; - + /* make a copy of existing base-data if not the last curve */ if (b < (totbits - 1)) fcurve = copy_fcurve(fcu); else fcurve = fcu; - + /* set path */ fcurve->rna_path = BLI_strdup(abp->path); fcurve->array_index = abp->array_index; - - /* convert keyframes + + /* convert keyframes * - beztriples and bpoints are mutually exclusive, so we won't have both at the same time * - beztriples are more likely to be encountered as they are keyframes (the other type wasn't used yet) */ fcurve->totvert = icu->totvert; - + if (icu->bezt) { BezTriple *dst, *src; - + /* allocate new array for keyframes/beztriples */ fcurve->bezt = MEM_callocN(sizeof(BezTriple) * fcurve->totvert, "BezTriples"); - + /* loop through copying all BezTriples individually, as we need to modify a few things */ for (dst = fcurve->bezt, src = icu->bezt, i = 0; i < fcurve->totvert; i++, dst++, src++) { /* firstly, copy BezTriple data */ *dst = *src; - + /* interpolation can only be constant... */ dst->ipo = BEZT_IPO_CONST; - + /* 'hide' flag is now used for keytype - only 'keyframes' existed before */ dst->hide = BEZT_KEYTYPE_KEYFRAME; - + /* auto-handles - per curve to per handle */ if (icu->flag & IPO_AUTO_HORIZ) { if (dst->h1 == HD_AUTO) dst->h1 = HD_AUTO_ANIM; if (dst->h2 == HD_AUTO) dst->h2 = HD_AUTO_ANIM; } - + /* correct values, by checking if the flag of interest is set */ if ( ((int)(dst->vec[1][1])) & (abp->bit) ) dst->vec[0][1] = dst->vec[1][1] = dst->vec[2][1] = 1.0f; @@ -1262,80 +1262,80 @@ static void icu_to_fcurves(ID *id, ListBase *groups, ListBase *list, IpoCurve *i //BPoint *bp; //FPoint *fpt; } - + /* add new F-Curve to list */ fcurve_add_to_list(groups, list, fcurve, actname, muteipo); } } else { unsigned int i = 0; - + /* get rna-path * - we will need to set the 'disabled' flag if no path is able to be made (for now) */ fcu->rna_path = get_rna_access(id, icu->blocktype, icu->adrcode, actname, constname, seq, &fcu->array_index); if (fcu->rna_path == NULL) fcu->flag |= FCURVE_DISABLED; - - /* convert keyframes + + /* convert keyframes * - beztriples and bpoints are mutually exclusive, so we won't have both at the same time * - beztriples are more likely to be encountered as they are keyframes (the other type wasn't used yet) */ fcu->totvert = icu->totvert; - + if (icu->bezt) { BezTriple *dst, *src; - + /* allocate new array for keyframes/beztriples */ fcu->bezt = MEM_callocN(sizeof(BezTriple) * fcu->totvert, "BezTriples"); - + /* loop through copying all BezTriples individually, as we need to modify a few things */ for (dst = fcu->bezt, src = icu->bezt, i = 0; i < fcu->totvert; i++, dst++, src++) { /* firstly, copy BezTriple data */ *dst = *src; - + /* now copy interpolation from curve (if not already set) */ if (icu->ipo != IPO_MIXED) dst->ipo = icu->ipo; - + /* 'hide' flag is now used for keytype - only 'keyframes' existed before */ dst->hide = BEZT_KEYTYPE_KEYFRAME; - + /* auto-handles - per curve to per handle */ if (icu->flag & IPO_AUTO_HORIZ) { if (dst->h1 == HD_AUTO) dst->h1 = HD_AUTO_ANIM; if (dst->h2 == HD_AUTO) dst->h2 = HD_AUTO_ANIM; } - - /* correct values for euler rotation curves - * - they were degrees/10 + + /* correct values for euler rotation curves + * - they were degrees/10 * - we need radians for RNA to do the right thing */ if ( ((icu->blocktype == ID_OB) && ELEM(icu->adrcode, OB_ROT_X, OB_ROT_Y, OB_ROT_Z)) || ((icu->blocktype == ID_PO) && ELEM(icu->adrcode, AC_EUL_X, AC_EUL_Y, AC_EUL_Z)) ) { const float fac = (float)M_PI / 18.0f; //10.0f * M_PI/180.0f; - + dst->vec[0][1] *= fac; dst->vec[1][1] *= fac; dst->vec[2][1] *= fac; } - - /* correct values for path speed curves + + /* correct values for path speed curves * - their values were 0-1 * - we now need as 'frames' */ - if ( (id) && (icu->blocktype == GS(id->name)) && + if ( (id) && (icu->blocktype == GS(id->name)) && (fcu->rna_path && STREQ(fcu->rna_path, "eval_time")) ) { Curve *cu = (Curve *)id; - + dst->vec[0][1] *= cu->pathlen; dst->vec[1][1] *= cu->pathlen; dst->vec[2][1] *= cu->pathlen; } - - /* correct times for rotation drivers + + /* correct times for rotation drivers * - need to go from degrees to radians... * - there's only really 1 target to worry about * - were also degrees/10 @@ -1343,27 +1343,27 @@ static void icu_to_fcurves(ID *id, ListBase *groups, ListBase *list, IpoCurve *i if (fcu->driver && fcu->driver->variables.first) { DriverVar *dvar = fcu->driver->variables.first; DriverTarget *dtar = &dvar->targets[0]; - + if (ELEM(dtar->transChan, DTAR_TRANSCHAN_ROTX, DTAR_TRANSCHAN_ROTY, DTAR_TRANSCHAN_ROTZ)) { const float fac = (float)M_PI / 18.0f; - + dst->vec[0][0] *= fac; dst->vec[1][0] *= fac; dst->vec[2][0] *= fac; } } - + /* correct values for sequencer curves, that were not locked to frame */ if (seq && (seq->flag & SEQ_IPO_FRAME_LOCKED) == 0) { const float mul = (seq->enddisp - seq->startdisp) / 100.0f; const float offset = seq->startdisp; - + dst->vec[0][0] *= mul; dst->vec[0][0] += offset; - + dst->vec[1][0] *= mul; dst->vec[1][0] += offset; - + dst->vec[2][0] *= mul; dst->vec[2][0] += offset; } @@ -1374,7 +1374,7 @@ static void icu_to_fcurves(ID *id, ListBase *groups, ListBase *list, IpoCurve *i //BPoint *bp; //FPoint *fpt; } - + /* add new F-Curve to list */ fcurve_add_to_list(groups, list, fcu, actname, muteipo); } @@ -1389,16 +1389,16 @@ static void icu_to_fcurves(ID *id, ListBase *groups, ListBase *list, IpoCurve *i static void ipo_to_animato(ID *id, Ipo *ipo, char actname[], char constname[], Sequence *seq, ListBase *animgroups, ListBase *anim, ListBase *drivers) { IpoCurve *icu; - + /* sanity check */ if (ELEM(NULL, ipo, anim, drivers)) return; - + if (G.debug & G_DEBUG) printf("ipo_to_animato\n"); - - /* validate actname and constname + + /* validate actname and constname * - clear actname if it was one of the generic <builtin> ones (i.e. 'Object', or 'Shapes') - * - actname can then be used to assign F-Curves in Action to Action Groups + * - actname can then be used to assign F-Curves in Action to Action Groups * (i.e. thus keeping the benefits that used to be provided by Action Channels for grouping * F-Curves for bones). This may be added later... for now let's just dump without them... */ @@ -1408,10 +1408,10 @@ static void ipo_to_animato(ID *id, Ipo *ipo, char actname[], char constname[], S else if ((ipo->blocktype == ID_OB) && STREQ(actname, "Shape")) actname = NULL; } - + /* loop over IPO-Curves, freeing as we progress */ for (icu = ipo->curve.first; icu; icu = icu->next) { - /* Since an IPO-Curve may end up being made into many F-Curves (i.e. bitflag curves), + /* Since an IPO-Curve may end up being made into many F-Curves (i.e. bitflag curves), * we figure out the best place to put the channel, then tell the curve-converter to just dump there */ if (icu->driver) { @@ -1427,23 +1427,23 @@ static void ipo_to_animato(ID *id, Ipo *ipo, char actname[], char constname[], S else icu_to_fcurves(id, animgroups, anim, icu, actname, constname, seq, ipo->muteipo); } - + /* if this IPO block doesn't have any users after this one, free... */ id_us_min(&ipo->id); if (ID_REAL_USERS(ipo) <= 0) { IpoCurve *icn; - + for (icu = ipo->curve.first; icu; icu = icn) { icn = icu->next; - + /* free driver */ if (icu->driver) MEM_freeN(icu->driver); - + /* free old data of curve now that it's no longer needed for converting any more curves */ if (icu->bezt) MEM_freeN(icu->bezt); if (icu->bp) MEM_freeN(icu->bezt); - + /* free this IPO-Curve */ BLI_freelinkN(&ipo->curve, icu); } @@ -1459,44 +1459,44 @@ static void action_to_animato(ID *id, bAction *act, ListBase *groups, ListBase * { bActionChannel *achan, *achann; bConstraintChannel *conchan, *conchann; - + /* only continue if there are Action Channels (indicating unconverted data) */ if (BLI_listbase_is_empty(&act->chanbase)) return; - + /* get rid of all Action Groups */ // XXX this is risky if there's some old + some new data in the Action... - if (act->groups.first) + if (act->groups.first) BLI_freelistN(&act->groups); - + /* loop through Action-Channels, converting data, freeing as we go */ for (achan = act->chanbase.first; achan; achan = achann) { /* get pointer to next Action Channel */ achann = achan->next; - + /* convert Action Channel's IPO data */ if (achan->ipo) { ipo_to_animato(id, achan->ipo, achan->name, NULL, NULL, groups, curves, drivers); id_us_min(&achan->ipo->id); achan->ipo = NULL; } - + /* convert constraint channel IPO-data */ for (conchan = achan->constraintChannels.first; conchan; conchan = conchann) { /* get pointer to next Constraint Channel */ conchann = conchan->next; - + /* convert Constraint Channel's IPO data */ if (conchan->ipo) { ipo_to_animato(id, conchan->ipo, achan->name, conchan->name, NULL, groups, curves, drivers); id_us_min(&conchan->ipo->id); conchan->ipo = NULL; } - + /* free Constraint Channel */ BLI_freelinkN(&achan->constraintChannels, conchan); } - + /* free Action Channel */ BLI_freelinkN(&act->chanbase, achan); } @@ -1509,12 +1509,12 @@ static void action_to_animato(ID *id, bAction *act, ListBase *groups, ListBase * * This assumes that AnimData has been added already. Separation of drivers * from animation data is accomplished here too... */ -static void ipo_to_animdata(ID *id, Ipo *ipo, char actname[], char constname[], Sequence *seq) +static void ipo_to_animdata(Main *bmain, ID *id, Ipo *ipo, char actname[], char constname[], Sequence *seq) { AnimData *adt = BKE_animdata_from_id(id); ListBase anim = {NULL, NULL}; ListBase drivers = {NULL, NULL}; - + /* sanity check */ if (ELEM(NULL, id, ipo)) return; @@ -1522,36 +1522,36 @@ static void ipo_to_animdata(ID *id, Ipo *ipo, char actname[], char constname[], printf("ERROR ipo_to_animdata(): adt invalid\n"); return; } - + if (G.debug & G_DEBUG) { printf("ipo to animdata - ID:%s, IPO:%s, actname:%s constname:%s seqname:%s curves:%d\n", id->name + 2, ipo->id.name + 2, (actname) ? actname : "<None>", (constname) ? constname : "<None>", (seq) ? (seq->name + 2) : "<None>", BLI_listbase_count(&ipo->curve)); } - + /* Convert curves to animato system (separated into separate lists of F-Curves for animation and drivers), * and the try to put these lists in the right places, but do not free the lists here */ - // XXX there shouldn't be any need for the groups, so don't supply pointer for that now... + // XXX there shouldn't be any need for the groups, so don't supply pointer for that now... ipo_to_animato(id, ipo, actname, constname, seq, NULL, &anim, &drivers); - + /* deal with animation first */ if (anim.first) { if (G.debug & G_DEBUG) printf("\thas anim\n"); /* try to get action */ if (adt->action == NULL) { char nameBuf[MAX_ID_NAME]; - + BLI_snprintf(nameBuf, sizeof(nameBuf), "CDA:%s", ipo->id.name + 2); - - adt->action = BKE_action_add(G.main, nameBuf); + + adt->action = BKE_action_add(bmain, nameBuf); if (G.debug & G_DEBUG) printf("\t\tadded new action - '%s'\n", nameBuf); } - + /* add F-Curves to action */ BLI_movelisttolist(&adt->action->curves, &anim); } - + /* deal with drivers */ if (drivers.first) { if (G.debug & G_DEBUG) printf("\thas drivers\n"); @@ -1566,18 +1566,18 @@ static void ipo_to_animdata(ID *id, Ipo *ipo, char actname[], char constname[], static void action_to_animdata(ID *id, bAction *act) { AnimData *adt = BKE_animdata_from_id(id); - + /* only continue if there are Action Channels (indicating unconverted data) */ if (ELEM(NULL, adt, act->chanbase.first)) return; - + /* check if we need to set this Action as the AnimData's action */ if (adt->action == NULL) { /* set this Action as AnimData's Action */ if (G.debug & G_DEBUG) printf("act_to_adt - set adt action to act\n"); adt->action = act; } - + /* convert Action data */ action_to_animato(id, act, &adt->action->groups, &adt->action->curves, &adt->drivers); } @@ -1595,25 +1595,25 @@ static void nlastrips_to_animdata(ID *id, ListBase *strips) NlaTrack *nlt = NULL; NlaStrip *strip; bActionStrip *as, *asn; - + /* for each one of the original strips, convert to a new strip and free the old... */ for (as = strips->first; as; as = asn) { asn = as->next; - + /* this old strip is only worth something if it had an action... */ if (as->act) { /* convert Action data (if not yet converted), storing the results in the same Action */ action_to_animato(id, as->act, &as->act->groups, &as->act->curves, &adt->drivers); - + /* create a new-style NLA-strip which references this Action, then copy over relevant settings */ { - /* init a new strip, and assign the action to it - * - no need to muck around with the user-counts, since this is just + /* init a new strip, and assign the action to it + * - no need to muck around with the user-counts, since this is just * passing over the ref to the new owner, not creating an additional ref */ strip = MEM_callocN(sizeof(NlaStrip), "NlaStrip"); strip->act = as->act; - + /* endpoints */ strip->start = as->start; strip->end = as->end; @@ -1642,25 +1642,25 @@ static void nlastrips_to_animdata(ID *id, ListBase *strips) if ((as->flag & ACTSTRIP_HOLDLASTFRAME) == 0) strip->extendmode = NLASTRIP_EXTEND_NOTHING; } - + /* try to add this strip to the current NLA-Track (i.e. the 'last' one on the stack atm) */ if (BKE_nlatrack_add_strip(nlt, strip) == 0) { - /* trying to add to the current failed (no space), + /* trying to add to the current failed (no space), * so add a new track to the stack, and add to that... */ nlt = BKE_nlatrack_add(adt, NULL); BKE_nlatrack_add_strip(nlt, strip); } - + /* ensure that strip has a name */ BKE_nlastrip_validate_name(adt, strip); } - + /* modifiers */ // FIXME: for now, we just free them... if (as->modifiers.first) BLI_freelistN(&as->modifiers); - + /* free the old strip */ BLI_freelinkN(strips, as); } @@ -1679,147 +1679,147 @@ static void nlastrips_to_animdata(ID *id, ListBase *strips) * Data that has been converted should be freed immediately, which means that it is immediately * clear which datablocks have yet to be converted, and also prevent freeing errors when we exit. */ -// XXX currently done after all file reading... -void do_versions_ipos_to_animato(Main *main) +// XXX currently done after all file reading... +void do_versions_ipos_to_animato(Main *bmain) { ListBase drivers = {NULL, NULL}; ID *id; - - if (main == NULL) { + + if (bmain == NULL) { printf("Argh! Main is NULL in do_versions_ipos_to_animato()\n"); return; } - + /* only convert if version is right */ - if (main->versionfile >= 250) { - printf("WARNING: Animation data too new to convert (Version %d)\n", main->versionfile); + if (bmain->versionfile >= 250) { + printf("WARNING: Animation data too new to convert (Version %d)\n", bmain->versionfile); return; } else if (G.debug & G_DEBUG) printf("INFO: Converting to Animato...\n"); - + /* ----------- Animation Attached to Data -------------- */ - + /* objects */ - for (id = main->object.first; id; id = id->next) { + for (id = bmain->object.first; id; id = id->next) { Object *ob = (Object *)id; bPoseChannel *pchan; bConstraint *con; bConstraintChannel *conchan, *conchann; - + if (G.debug & G_DEBUG) printf("\tconverting ob %s\n", id->name + 2); - + /* check if object has any animation data */ if (ob->nlastrips.first) { /* Add AnimData block */ BKE_animdata_add_id(id); - + /* IPO first to take into any non-NLA'd Object Animation */ if (ob->ipo) { - ipo_to_animdata(id, ob->ipo, NULL, NULL, NULL); - + ipo_to_animdata(bmain, id, ob->ipo, NULL, NULL, NULL); + id_us_min(&ob->ipo->id); ob->ipo = NULL; } - - /* Action is skipped since it'll be used by some strip in the NLA anyway, + + /* Action is skipped since it'll be used by some strip in the NLA anyway, * causing errors with evaluation in the new evaluation pipeline */ if (ob->action) { id_us_min(&ob->action->id); ob->action = NULL; } - + /* finally NLA */ nlastrips_to_animdata(id, &ob->nlastrips); } else if ((ob->ipo) || (ob->action)) { /* Add AnimData block */ AnimData *adt = BKE_animdata_add_id(id); - + /* Action first - so that Action name get conserved */ if (ob->action) { action_to_animdata(id, ob->action); - + /* only decrease usercount if this Action isn't now being used by AnimData */ if (ob->action != adt->action) { id_us_min(&ob->action->id); ob->action = NULL; } } - + /* IPO second... */ if (ob->ipo) { - ipo_to_animdata(id, ob->ipo, NULL, NULL, NULL); + ipo_to_animdata(bmain, id, ob->ipo, NULL, NULL, NULL); id_us_min(&ob->ipo->id); ob->ipo = NULL; } } - + /* check PoseChannels for constraints with local data */ if (ob->pose) { /* Verify if there's AnimData block */ BKE_animdata_add_id(id); - + for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) { for (con = pchan->constraints.first; con; con = con->next) { - /* if constraint has own IPO, convert add these to Object - * (NOTE: they're most likely to be drivers too) + /* if constraint has own IPO, convert add these to Object + * (NOTE: they're most likely to be drivers too) */ if (con->ipo) { - /* although this was the constraint's local IPO, we still need to provide pchan + con + /* although this was the constraint's local IPO, we still need to provide pchan + con * so that drivers can be added properly... */ - ipo_to_animdata(id, con->ipo, pchan->name, con->name, NULL); + ipo_to_animdata(bmain, id, con->ipo, pchan->name, con->name, NULL); id_us_min(&con->ipo->id); con->ipo = NULL; } } } } - + /* check constraints for local IPO's */ for (con = ob->constraints.first; con; con = con->next) { - /* if constraint has own IPO, convert add these to Object - * (NOTE: they're most likely to be drivers too) + /* if constraint has own IPO, convert add these to Object + * (NOTE: they're most likely to be drivers too) */ if (con->ipo) { /* Verify if there's AnimData block, just in case */ BKE_animdata_add_id(id); - - /* although this was the constraint's local IPO, we still need to provide con + + /* although this was the constraint's local IPO, we still need to provide con * so that drivers can be added properly... */ - ipo_to_animdata(id, con->ipo, NULL, con->name, NULL); + ipo_to_animdata(bmain, id, con->ipo, NULL, con->name, NULL); id_us_min(&con->ipo->id); con->ipo = NULL; } - + /* check for Action Constraint */ // XXX do we really want to do this here? } - + /* check constraint channels - we need to remove them anyway... */ if (ob->constraintChannels.first) { /* Verify if there's AnimData block */ BKE_animdata_add_id(id); - + for (conchan = ob->constraintChannels.first; conchan; conchan = conchann) { /* get pointer to next Constraint Channel */ conchann = conchan->next; - + /* convert Constraint Channel's IPO data */ if (conchan->ipo) { - ipo_to_animdata(id, conchan->ipo, NULL, conchan->name, NULL); + ipo_to_animdata(bmain, id, conchan->ipo, NULL, conchan->name, NULL); id_us_min(&conchan->ipo->id); conchan->ipo = NULL; } - + /* free Constraint Channel */ BLI_freelinkN(&ob->constraintChannels, conchan); } } - + /* object's action will always be object-rooted */ { AnimData *adt = BKE_animdata_from_id(id); @@ -1827,100 +1827,100 @@ void do_versions_ipos_to_animato(Main *main) adt->action->idroot = ID_OB; } } - + /* shapekeys */ - for (id = main->key.first; id; id = id->next) { + for (id = bmain->key.first; id; id = id->next) { Key *key = (Key *)id; - + if (G.debug & G_DEBUG) printf("\tconverting key %s\n", id->name + 2); - - /* we're only interested in the IPO + + /* we're only interested in the IPO * NOTE: for later, it might be good to port these over to Object instead, as many of these * are likely to be drivers, but it's hard to trace that from here, so move this to Ob loop? */ if (key->ipo) { /* Add AnimData block */ AnimData *adt = BKE_animdata_add_id(id); - + /* Convert Shapekey data... */ - ipo_to_animdata(id, key->ipo, NULL, NULL, NULL); - + ipo_to_animdata(bmain, id, key->ipo, NULL, NULL, NULL); + if (adt->action) adt->action->idroot = key->ipo->blocktype; - + id_us_min(&key->ipo->id); key->ipo = NULL; } } - + /* materials */ - for (id = main->mat.first; id; id = id->next) { + for (id = bmain->mat.first; id; id = id->next) { Material *ma = (Material *)id; - + if (G.debug & G_DEBUG) printf("\tconverting material %s\n", id->name + 2); - + /* we're only interested in the IPO */ if (ma->ipo) { /* Add AnimData block */ AnimData *adt = BKE_animdata_add_id(id); - + /* Convert Material data... */ - ipo_to_animdata(id, ma->ipo, NULL, NULL, NULL); - + ipo_to_animdata(bmain, id, ma->ipo, NULL, NULL, NULL); + if (adt->action) adt->action->idroot = ma->ipo->blocktype; - + id_us_min(&ma->ipo->id); ma->ipo = NULL; } } - + /* worlds */ - for (id = main->world.first; id; id = id->next) { + for (id = bmain->world.first; id; id = id->next) { World *wo = (World *)id; - + if (G.debug & G_DEBUG) printf("\tconverting world %s\n", id->name + 2); - + /* we're only interested in the IPO */ if (wo->ipo) { /* Add AnimData block */ AnimData *adt = BKE_animdata_add_id(id); - + /* Convert World data... */ - ipo_to_animdata(id, wo->ipo, NULL, NULL, NULL); - + ipo_to_animdata(bmain, id, wo->ipo, NULL, NULL, NULL); + if (adt->action) adt->action->idroot = wo->ipo->blocktype; - + id_us_min(&wo->ipo->id); wo->ipo = NULL; } } - + /* sequence strips */ - for (id = main->scene.first; id; id = id->next) { + for (id = bmain->scene.first; id; id = id->next) { Scene *scene = (Scene *)id; Editing *ed = scene->ed; if (ed && ed->seqbasep) { Sequence *seq; - + AnimData *adt = BKE_animdata_add_id(id); - + SEQ_BEGIN(ed, seq) { IpoCurve *icu = (seq->ipo) ? seq->ipo->curve.first : NULL; short adrcode = SEQ_FAC1; - + if (G.debug & G_DEBUG) printf("\tconverting sequence strip %s\n", seq->name + 2); - + if (ELEM(NULL, seq->ipo, icu)) { seq->flag |= SEQ_USE_EFFECT_DEFAULT_FADE; continue; } - + /* patch adrcode, so that we can map - * to different DNA variables later + * to different DNA variables later * (semi-hack (tm) ) */ switch (seq->type) { @@ -1936,13 +1936,13 @@ void do_versions_ipos_to_animato(Main *main) break; } icu->adrcode = adrcode; - + /* convert IPO */ - ipo_to_animdata((ID *)scene, seq->ipo, NULL, NULL, seq); - + ipo_to_animdata(bmain, (ID *)scene, seq->ipo, NULL, NULL, seq); + if (adt->action) adt->action->idroot = ID_SCE; /* scene-rooted */ - + id_us_min(&seq->ipo->id); seq->ipo = NULL; } @@ -1952,142 +1952,142 @@ void do_versions_ipos_to_animato(Main *main) /* textures */ - for (id = main->tex.first; id; id = id->next) { + for (id = bmain->tex.first; id; id = id->next) { Tex *te = (Tex *)id; - + if (G.debug & G_DEBUG) printf("\tconverting texture %s\n", id->name + 2); - + /* we're only interested in the IPO */ if (te->ipo) { /* Add AnimData block */ AnimData *adt = BKE_animdata_add_id(id); - + /* Convert Texture data... */ - ipo_to_animdata(id, te->ipo, NULL, NULL, NULL); - + ipo_to_animdata(bmain, id, te->ipo, NULL, NULL, NULL); + if (adt->action) adt->action->idroot = te->ipo->blocktype; - + id_us_min(&te->ipo->id); te->ipo = NULL; } } - + /* cameras */ - for (id = main->camera.first; id; id = id->next) { + for (id = bmain->camera.first; id; id = id->next) { Camera *ca = (Camera *)id; - + if (G.debug & G_DEBUG) printf("\tconverting camera %s\n", id->name + 2); - + /* we're only interested in the IPO */ if (ca->ipo) { /* Add AnimData block */ AnimData *adt = BKE_animdata_add_id(id); - + /* Convert Camera data... */ - ipo_to_animdata(id, ca->ipo, NULL, NULL, NULL); - + ipo_to_animdata(bmain, id, ca->ipo, NULL, NULL, NULL); + if (adt->action) adt->action->idroot = ca->ipo->blocktype; - + id_us_min(&ca->ipo->id); ca->ipo = NULL; } } - + /* lamps */ - for (id = main->lamp.first; id; id = id->next) { + for (id = bmain->lamp.first; id; id = id->next) { Lamp *la = (Lamp *)id; - + if (G.debug & G_DEBUG) printf("\tconverting lamp %s\n", id->name + 2); - + /* we're only interested in the IPO */ if (la->ipo) { /* Add AnimData block */ AnimData *adt = BKE_animdata_add_id(id); - + /* Convert Lamp data... */ - ipo_to_animdata(id, la->ipo, NULL, NULL, NULL); - + ipo_to_animdata(bmain, id, la->ipo, NULL, NULL, NULL); + if (adt->action) adt->action->idroot = la->ipo->blocktype; - + id_us_min(&la->ipo->id); la->ipo = NULL; } } - + /* curves */ - for (id = main->curve.first; id; id = id->next) { + for (id = bmain->curve.first; id; id = id->next) { Curve *cu = (Curve *)id; - + if (G.debug & G_DEBUG) printf("\tconverting curve %s\n", id->name + 2); - + /* we're only interested in the IPO */ if (cu->ipo) { /* Add AnimData block */ AnimData *adt = BKE_animdata_add_id(id); - + /* Convert Curve data... */ - ipo_to_animdata(id, cu->ipo, NULL, NULL, NULL); - + ipo_to_animdata(bmain, id, cu->ipo, NULL, NULL, NULL); + if (adt->action) adt->action->idroot = cu->ipo->blocktype; - + id_us_min(&cu->ipo->id); cu->ipo = NULL; } } - + /* --------- Unconverted Animation Data ------------------ */ - /* For Animation data which may not be directly connected (i.e. not linked) to any other + /* For Animation data which may not be directly connected (i.e. not linked) to any other * data, we need to perform a separate pass to make sure that they are converted to standalone * Actions which may then be able to be reused. This does mean that we will be going over data that's * already been converted, but there are no problems with that. * - * The most common case for this will be Action Constraints, or IPO's with Fake-Users. - * We collect all drivers that were found into a temporary collection, and free them in one go, as they're + * The most common case for this will be Action Constraints, or IPO's with Fake-Users. + * We collect all drivers that were found into a temporary collection, and free them in one go, as they're * impossible to resolve. */ - + /* actions */ - for (id = main->action.first; id; id = id->next) { + for (id = bmain->action.first; id; id = id->next) { bAction *act = (bAction *)id; - + if (G.debug & G_DEBUG) printf("\tconverting action %s\n", id->name + 2); - + /* if old action, it will be object-only... */ if (act->chanbase.first) act->idroot = ID_OB; - + /* be careful! some of the actions we encounter will be converted ones... */ action_to_animato(NULL, act, &act->groups, &act->curves, &drivers); } - + /* ipo's */ - for (id = main->ipo.first; id; id = id->next) { + for (id = bmain->ipo.first; id; id = id->next) { Ipo *ipo = (Ipo *)id; - + if (G.debug & G_DEBUG) printf("\tconverting ipo %s\n", id->name + 2); - + /* most likely this IPO has already been processed, so check if any curves left to convert */ if (ipo->curve.first) { bAction *new_act; - + /* add a new action for this, and convert all data into that action */ - new_act = BKE_action_add(main, id->name + 2); + new_act = BKE_action_add(bmain, id->name + 2); ipo_to_animato(NULL, ipo, NULL, NULL, NULL, NULL, &new_act->curves, &drivers); new_act->idroot = ipo->blocktype; } - + /* clear fake-users, and set user-count to zero to make sure it is cleared on file-save */ ipo->id.us = 0; ipo->id.flag &= ~LIB_FAKEUSER; } - + /* free unused drivers from actions + ipos */ free_fcurves(&drivers); - + if (G.debug & G_DEBUG) printf("INFO: Animato convert done\n"); } diff --git a/source/blender/blenkernel/intern/key.c b/source/blender/blenkernel/intern/key.c index fd42556067e..4689575655e 100644 --- a/source/blender/blenkernel/intern/key.c +++ b/source/blender/blenkernel/intern/key.c @@ -102,18 +102,18 @@ void BKE_key_free_nolib(Key *key) } } -Key *BKE_key_add(ID *id) /* common function */ +Key *BKE_key_add(Main *bmain, ID *id) /* common function */ { Key *key; char *el; - - key = BKE_libblock_alloc(G.main, ID_KE, "Key", 0); - + + key = BKE_libblock_alloc(bmain, ID_KE, "Key", 0); + key->type = KEY_NORMAL; key->from = id; key->uidgen = 1; - + /* XXX the code here uses some defines which will soon be deprecated... */ switch (GS(id->name)) { case ID_ME: @@ -150,7 +150,7 @@ Key *BKE_key_add(ID *id) /* common function */ default: break; } - + return key; } @@ -192,24 +192,24 @@ Key *BKE_key_copy_nolib(Key *key) { Key *keyn; KeyBlock *kbn, *kb; - + keyn = MEM_dupallocN(key); keyn->adt = NULL; BLI_duplicatelist(&keyn->block, &key->block); - + kb = key->block.first; kbn = keyn->block.first; while (kbn) { - + if (kbn->data) kbn->data = MEM_dupallocN(kbn->data); if (kb == key->refkey) keyn->refkey = kbn; - + kbn = kbn->next; kb = kb->next; } - + return keyn; } @@ -223,7 +223,7 @@ void BKE_key_sort(Key *key) KeyBlock *kb; KeyBlock *kb2; - /* locate the key which is out of position */ + /* locate the key which is out of position */ for (kb = key->block.first; kb; kb = kb->next) if ((kb->next) && (kb->pos > kb->next->pos)) break; @@ -232,7 +232,7 @@ void BKE_key_sort(Key *key) if (kb) { kb = kb->next; /* next key is the out-of-order one */ BLI_remlink(&key->block, kb); - + /* find the right location and insert before */ for (kb2 = key->block.first; kb2; kb2 = kb2->next) { if (kb2->pos > kb->pos) { @@ -251,7 +251,7 @@ void BKE_key_sort(Key *key) void key_curve_position_weights(float t, float data[4], int type) { float t2, t3, fc; - + if (type == KEY_LINEAR) { data[0] = 0.0f; data[1] = -t + 1.0f; @@ -293,7 +293,7 @@ void key_curve_position_weights(float t, float data[4], int type) void key_curve_tangent_weights(float t, float data[4], int type) { float t2, fc; - + if (type == KEY_LINEAR) { data[0] = 0.0f; data[1] = -1.0f; @@ -332,7 +332,7 @@ void key_curve_tangent_weights(float t, float data[4], int type) void key_curve_normal_weights(float t, float data[4], int type) { float fc; - + if (type == KEY_LINEAR) { data[0] = 0.0f; data[1] = 0.0f; @@ -415,7 +415,7 @@ static int setkeys(float fac, ListBase *lb, KeyBlock *k[], float t[4], int cycl) t[3] = k[3]->pos; k1 = k[3]; } - + while (t[2] < fac) { /* find correct location */ if (k1->next == NULL) { if (cycl) { @@ -441,7 +441,7 @@ static int setkeys(float fac, ListBase *lb, KeyBlock *k[], float t[4], int cycl) if (ofs > 2.1f + lastpos) break; } - + bsplinetype = 0; if (k[1]->type == KEY_BSPLINE || k[2]->type == KEY_BSPLINE) bsplinetype = 1; @@ -499,7 +499,7 @@ static void flerp(int tot, float *in, float *f0, float *f1, float *f2, float *f3 static void rel_flerp(int tot, float *in, float *ref, float *out, float fac) { int a; - + for (a = 0; a < tot; a++) { in[a] -= fac * (ref[a] - out[a]); } @@ -588,7 +588,7 @@ static void cp_key(const int start, int end, const int tot, char *poin, Key *key return; if (end > tot) end = tot; - + if (tot != kb->totelem) { ktot = 0.0; flagflo = 1; @@ -605,9 +605,9 @@ static void cp_key(const int start, int end, const int tot, char *poin, Key *key /* this exception is needed curves with multiple splines */ if (start != 0) { - + poin += poinsize * start; - + if (flagflo) { ktot += start * kd; a = (int)floor(ktot); @@ -620,13 +620,13 @@ static void cp_key(const int start, int end, const int tot, char *poin, Key *key k1 += start * key->elemsize; } } - + if (mode == KEY_MODE_BEZTRIPLE) { elemstr[0] = 1; elemstr[1] = IPO_BEZTRIPLE; elemstr[2] = 0; } - + /* just do it here, not above! */ elemsize = key->elemsize; if (mode == KEY_MODE_BEZTRIPLE) elemsize *= 3; @@ -668,7 +668,7 @@ static void cp_key(const int start, int end, const int tot, char *poin, Key *key poin += *ofsp; cp += 2; ofsp++; } - + /* are we going to be nasty? */ if (flagflo) { ktot += kd; @@ -682,7 +682,7 @@ static void cp_key(const int start, int end, const int tot, char *poin, Key *key k1 += elemsize; kref += elemsize; } - + if (mode == KEY_MODE_BEZTRIPLE) { a += 2; } @@ -748,13 +748,13 @@ void BKE_key_evaluate_relative(const int start, int end, const int tot, char *ba /* step 1 init */ cp_key(start, end, tot, basispoin, key, actkb, key->refkey, NULL, mode); - + /* step 2: do it */ - + for (kb = key->block.first, keyblock_index = 0; kb; kb = kb->next, keyblock_index++) { if (kb != key->refkey) { float icuval = kb->curval; - + /* only with value, and no difference allowed */ if (!(kb->flag & KEYBLOCK_MUTE) && icuval != 0.0f && kb->totelem == tot) { KeyBlock *refb; @@ -764,7 +764,7 @@ void BKE_key_evaluate_relative(const int start, int end, const int tot, char *ba /* reference now can be any block */ refb = BLI_findlink(&key->block, kb->relative); if (refb == NULL) continue; - + poin = basispoin; from = key_block_get_data(key, actkb, kb, &freefrom); reffrom = key_block_get_data(key, actkb, refb, &freereffrom); @@ -772,18 +772,18 @@ void BKE_key_evaluate_relative(const int start, int end, const int tot, char *ba poin += start * poinsize; reffrom += key->elemsize * start; // key elemsize yes! from += key->elemsize * start; - + for (b = start; b < end; b++) { - + weight = weights ? (*weights * icuval) : icuval; - + cp = key->elemstr; if (mode == KEY_MODE_BEZTRIPLE) cp = elemstr; - + ofsp = ofs; - + while (cp[0]) { /* (cp[0] == amount) */ - + switch (cp[1]) { case IPO_FLOAT: rel_flerp(3, (float *)poin, (float *)reffrom, (float *)from, weight); @@ -803,14 +803,14 @@ void BKE_key_evaluate_relative(const int start, int end, const int tot, char *ba } poin += *ofsp; - + cp += 2; ofsp++; } - + reffrom += elemsize; from += elemsize; - + if (mode == KEY_MODE_BEZTRIPLE) b += 2; if (weights) weights++; } @@ -837,7 +837,7 @@ static void do_key(const int start, int end, const int tot, char *poin, Key *key if (!key_pointer_size(key, mode, &poinsize, &ofs[0])) return; - + if (end > tot) end = tot; k1 = key_block_get_data(key, actkb, k[0], &freek1); @@ -891,7 +891,7 @@ static void do_key(const int start, int end, const int tot, char *poin, Key *key if (start != 0) { poin += poinsize * start; - + if (flagdo & 1) { if (flagflo & 1) { k1tot += start * k1d; @@ -957,10 +957,10 @@ static void do_key(const int start, int end, const int tot, char *poin, Key *key if (mode == KEY_MODE_BEZTRIPLE) elemsize *= 3; for (a = start; a < end; a++) { - + cp = key->elemstr; if (mode == KEY_MODE_BEZTRIPLE) cp = elemstr; - + ofsp = ofs; while (cp[0]) { /* (cp[0] == amount) */ @@ -984,7 +984,7 @@ static void do_key(const int start, int end, const int tot, char *poin, Key *key BLI_assert(!"invalid 'cp[1]'"); return; } - + poin += *ofsp; cp += 2; ofsp++; @@ -1038,7 +1038,7 @@ static void do_key(const int start, int end, const int tot, char *poin, Key *key k4 += elemsize; } } - + if (mode == KEY_MODE_BEZTRIPLE) a += 2; } @@ -1055,10 +1055,10 @@ static float *get_weights_array(Object *ob, char *vgroup, WeightsArrayCache *cac BMIter iter; BMVert *eve; int totvert = 0, defgrp_index = 0; - + /* no vgroup string set? */ if (vgroup[0] == 0) return NULL; - + /* gather dvert and totvert */ if (ob->type == OB_MESH) { Mesh *me = ob->data; @@ -1073,9 +1073,9 @@ static float *get_weights_array(Object *ob, char *vgroup, WeightsArrayCache *cac dvert = lt->dvert; totvert = lt->pntsu * lt->pntsv * lt->pntsw; } - + if (dvert == NULL) return NULL; - + /* find the group (weak loop-in-loop) */ defgrp_index = defgroup_name_index(ob, vgroup); if (defgrp_index != -1) { @@ -1197,7 +1197,7 @@ static void do_cu_key(Curve *cu, Key *key, KeyBlock *actkb, KeyBlock **k, float { Nurb *nu; int a, step; - + for (a = 0, nu = cu->nurb.first; nu; nu = nu->next, a += step) { if (nu->bp) { step = nu->pntsu * nu->pntsv; @@ -1217,7 +1217,7 @@ static void do_rel_cu_key(Curve *cu, Key *key, KeyBlock *actkb, char *out, const { Nurb *nu; int a, step; - + for (a = 0, nu = cu->nurb.first; nu; nu = nu->next, a += step) { if (nu->bp) { step = nu->pntsu * nu->pntsv; @@ -1263,7 +1263,7 @@ static void do_latt_key(Object *ob, Key *key, char *out, const int tot) KeyBlock *k[4], *actkb = BKE_keyblock_from_object(ob); float t[4]; int flag; - + if (key->type == KEY_RELATIVE) { float **per_keyblock_weights; per_keyblock_weights = BKE_keyblock_get_per_block_weights(ob, key, NULL); @@ -1272,7 +1272,7 @@ static void do_latt_key(Object *ob, Key *key, char *out, const int tot) } else { const float ctime_scaled = key->ctime / 100.0f; - + flag = setkeys(ctime_scaled, &key->block, k, t, 0); if (flag == 0) { @@ -1331,7 +1331,7 @@ float *BKE_key_evaluate_object_ex( /* if nothing to interpolate, cancel */ if (tot == 0 || size == 0) return NULL; - + /* allocate array */ if (arr == NULL) { out = MEM_callocN(size, "BKE_key_evaluate_object out"); @@ -1346,11 +1346,11 @@ float *BKE_key_evaluate_object_ex( /* prevent python from screwing this up? anyhoo, the from pointer could be dropped */ key->from = (ID *)ob->data; - + if (ob->shapeflag & OB_SHAPE_LOCK) { /* shape locked, copy the locked shape instead of blending */ KeyBlock *kb = BLI_findlink(&key->block, ob->shapenr - 1); - + if (kb && (kb->flag & KEYBLOCK_MUTE)) kb = key->refkey; @@ -1358,7 +1358,7 @@ float *BKE_key_evaluate_object_ex( kb = key->block.first; ob->shapenr = 1; } - + if (OB_TYPE_SUPPORT_VGROUP(ob->type)) { float *weights = get_weights_array(ob, kb->vgroup, NULL); @@ -1370,13 +1370,13 @@ float *BKE_key_evaluate_object_ex( cp_cu_key(ob->data, key, actkb, kb, 0, tot, out, tot); } else { - + if (ob->type == OB_MESH) do_mesh_key(ob, key, out, tot); else if (ob->type == OB_LATTICE) do_latt_key(ob, key, out, tot); else if (ob->type == OB_CURVE) do_curve_key(ob, key, out, tot); else if (ob->type == OB_SURF) do_curve_key(ob, key, out, tot); } - + if (r_totelem) { *r_totelem = tot; } @@ -1451,14 +1451,14 @@ KeyBlock *BKE_keyblock_add(Key *key, const char *name) KeyBlock *kb; float curpos = -0.1; int tot; - + kb = key->block.last; if (kb) curpos = kb->pos; - + kb = MEM_callocN(sizeof(KeyBlock), "Keyblock"); BLI_addtail(&key->block, kb); kb->type = KEY_CARDINAL; - + tot = BLI_listbase_count(&key->block); if (name) { BLI_strncpy(kb->name, name, sizeof(kb->name)); @@ -1476,7 +1476,7 @@ KeyBlock *BKE_keyblock_add(Key *key, const char *name) key->totkey++; if (key->totkey == 1) key->refkey = kb; - + kb->slidermin = 0.0f; kb->slidermax = 1.0f; @@ -1523,10 +1523,10 @@ KeyBlock *BKE_keyblock_add_ctime(Key *key, const char *name, const bool do_force } /* only the active keyblock */ -KeyBlock *BKE_keyblock_from_object(Object *ob) +KeyBlock *BKE_keyblock_from_object(Object *ob) { Key *key = BKE_key_from_object(ob); - + if (key) { KeyBlock *kb = BLI_findlink(&key->block, ob->shapenr - 1); return kb; @@ -1538,7 +1538,7 @@ KeyBlock *BKE_keyblock_from_object(Object *ob) KeyBlock *BKE_keyblock_from_object_reference(Object *ob) { Key *key = BKE_key_from_object(ob); - + if (key) return key->refkey; @@ -1550,18 +1550,18 @@ KeyBlock *BKE_keyblock_from_key(Key *key, int index) { KeyBlock *kb; int i; - + if (key) { kb = key->block.first; - + for (i = 1; i < key->totkey; i++) { kb = kb->next; - + if (index == i) return kb; } } - + return NULL; } @@ -1585,23 +1585,23 @@ void BKE_keyblock_copy_settings(KeyBlock *kb_dst, const KeyBlock *kb_src) kb_dst->slidermax = kb_src->slidermax; } -/* Get RNA-Path for 'value' setting of the given ShapeKey +/* Get RNA-Path for 'value' setting of the given ShapeKey * NOTE: the user needs to free the returned string once they're finish with it */ char *BKE_keyblock_curval_rnapath_get(Key *key, KeyBlock *kb) { PointerRNA ptr; PropertyRNA *prop; - + /* sanity checks */ if (ELEM(NULL, key, kb)) return NULL; - + /* create the RNA pointer */ RNA_pointer_create(&key->id, &RNA_ShapeKey, kb, &ptr); /* get pointer to the property too */ prop = RNA_struct_find_property(&ptr, "value"); - + /* return the path */ return RNA_path_from_ID_to_property(&ptr, prop); } @@ -1689,7 +1689,7 @@ void BKE_keyblock_update_from_curve(Curve *UNUSED(cu), KeyBlock *kb, ListBase *n } } else { - + ; for (a = nu->pntsu * nu->pntsv, bp = nu->bp; a; a--, fp += 4, bp++) { copy_v3_v3(fp, bp->vec); diff --git a/source/blender/blenkernel/intern/lamp.c b/source/blender/blenkernel/intern/lamp.c index 158d2954100..0e81e6570e2 100644 --- a/source/blender/blenkernel/intern/lamp.c +++ b/source/blender/blenkernel/intern/lamp.c @@ -89,7 +89,7 @@ void BKE_lamp_init(Lamp *la) la->contact_spread = 0.2f; la->contact_thickness = 0.5f; la->spec_fac = 1.0f; - + curvemapping_initialize(la->curfalloff); } @@ -152,7 +152,7 @@ Lamp *BKE_lamp_localize(Lamp *la) if (la->nodetree) lan->nodetree = ntreeLocalize(la->nodetree); - + lan->preview = NULL; return lan; @@ -175,7 +175,7 @@ void BKE_lamp_free(Lamp *la) MEM_freeN(la->nodetree); la->nodetree = NULL; } - + BKE_previewimg_free(&la->preview); BKE_icon_id_delete(&la->id); la->id.icon_id = 0; diff --git a/source/blender/blenkernel/intern/lattice.c b/source/blender/blenkernel/intern/lattice.c index b5b62de57ec..a885495f2bf 100644 --- a/source/blender/blenkernel/intern/lattice.c +++ b/source/blender/blenkernel/intern/lattice.c @@ -152,13 +152,13 @@ void BKE_lattice_resize(Lattice *lt, int uNew, int vNew, int wNew, Object *ltOb) int i, u, v, w; float fu, fv, fw, uc, vc, wc, du = 0.0, dv = 0.0, dw = 0.0; float *co, (*vertexCos)[3] = NULL; - + /* vertex weight groups are just freed all for now */ if (lt->dvert) { BKE_defvert_array_free(lt->dvert, lt->pntsu * lt->pntsv * lt->pntsw); lt->dvert = NULL; } - + while (uNew * vNew * wNew > 32000) { if (uNew >= vNew && uNew >= wNew) uNew--; else if (vNew >= uNew && vNew >= wNew) vNew--; @@ -203,7 +203,7 @@ void BKE_lattice_resize(Lattice *lt, int uNew, int vNew, int wNew, Object *ltOb) } } } - + if (ltOb) { float mat[4][4]; int typeu = lt->typeu, typev = lt->typev, typew = lt->typew; @@ -240,9 +240,9 @@ void BKE_lattice_resize(Lattice *lt, int uNew, int vNew, int wNew, Object *ltOb) lt->actbp = LT_ACTBP_NONE; MEM_freeN(lt->def); lt->def = MEM_callocN(lt->pntsu * lt->pntsv * lt->pntsw * sizeof(BPoint), "lattice bp"); - + bp = lt->def; - + for (i = 0; i < lt->pntsu * lt->pntsv * lt->pntsw; i++, bp++) { copy_v3_v3(bp->vec, vertexCos[i]); } @@ -255,9 +255,9 @@ void BKE_lattice_init(Lattice *lt) BLI_assert(MEMCMP_STRUCT_OFS_IS_ZERO(lt, id)); lt->flag = LT_GRID; - + lt->typeu = lt->typev = lt->typew = KEY_BSPLINE; - + lt->def = MEM_callocN(sizeof(BPoint), "lattvert"); /* temporary */ BKE_lattice_resize(lt, 2, 2, 2, NULL); /* creates a uniform lattice */ lt->actbp = LT_ACTBP_NONE; @@ -360,14 +360,14 @@ LatticeDeformData *init_latt_deform(Object *oblatt, Object *ob) if (lt->editlatt) lt = lt->editlatt->latt; bp = lt->def; - + fp = latticedata = MEM_mallocN(sizeof(float) * 3 * lt->pntsu * lt->pntsv * lt->pntsw, "latticedata"); - + /* for example with a particle system: (ob == NULL) */ if (ob == NULL) { /* in deformspace, calc matrix */ invert_m4_m4(latmat, oblatt->obmat); - + /* back: put in deform array */ invert_m4_m4(imat, latmat); } @@ -375,11 +375,11 @@ LatticeDeformData *init_latt_deform(Object *oblatt, Object *ob) /* in deformspace, calc matrix */ invert_m4_m4(imat, oblatt->obmat); mul_m4_m4m4(latmat, imat, ob->obmat); - + /* back: put in deform array */ invert_m4_m4(imat, latmat); } - + for (w = 0, fw = lt->fw; w < lt->pntsw; w++, fw += lt->dw) { for (v = 0, fv = lt->fv; v < lt->pntsv; v++, fv += lt->dv) { for (u = 0, fu = lt->fu; u < lt->pntsu; u++, bp++, co += 3, fp += 3, fu += lt->du) { @@ -556,7 +556,7 @@ static bool where_on_path_deform(Object *ob, float ctime, float vec[4], float di BevList *bl; float ctime1; int cycl = 0; - + /* test for cyclic */ bl = ob->curve_cache->bev.first; if (!bl->nr) return false; @@ -568,14 +568,14 @@ static bool where_on_path_deform(Object *ob, float ctime, float vec[4], float di else { ctime1 = ctime; } - + /* vec needs 4 items */ if (where_on_path(ob, ctime1, vec, dir, quat, radius, NULL)) { - + if (cycl == 0) { Path *path = ob->curve_cache->path; float dvec[3]; - + if (ctime < 0.0f) { sub_v3_v3v3(dvec, path->data[1].vec, path->data[0].vec); mul_v3_fl(dvec, ctime * (float)path->len); @@ -641,7 +641,7 @@ static bool calc_curve_deform(Object *par, float co[3], } } } - + if (where_on_path_deform(par, fac, loc, dir, new_quat, &radius)) { /* returns OK */ float quat[4], cent[3]; @@ -687,7 +687,7 @@ static bool calc_curve_deform(Object *par, float co[3], /* scale if enabled */ if (cu->flag & CU_PATH_RADIUS) mul_v3_fl(cent, radius); - + /* local rotation */ normalize_qt(quat); mul_qt_v3(quat, cent); @@ -731,7 +731,7 @@ void curve_deform_verts( cd.dmin[0] = cd.dmin[1] = cd.dmin[2] = -1.0f; cd.dmax[0] = cd.dmax[1] = cd.dmax[2] = 0.0f; } - + /* Check whether to use vertex groups (only possible if target is a Mesh or Lattice). * We want either a Mesh/Lattice with no derived data, or derived data with deformverts. */ @@ -804,12 +804,12 @@ void curve_deform_verts( else { /* set mesh min max bounds */ INIT_MINMAX(cd.dmin, cd.dmax); - + for (a = 0; a < numVerts; a++) { mul_m4_v3(cd.curvespace, vertexCos[a]); minmax_v3v3_v3(cd.dmin, cd.dmax, vertexCos[a]); } - + for (a = 0; a < numVerts; a++) { /* already in 'cd.curvespace', prev for loop */ calc_curve_deform(cuOb, vertexCos[a], defaxis, &cd, NULL); @@ -827,7 +827,7 @@ void curve_deform_vector(Object *cuOb, Object *target, { CurveDeform cd; float quat[4]; - + if (cuOb->type != OB_CURVE) { unit_m3(mat); return; @@ -835,21 +835,21 @@ void curve_deform_vector(Object *cuOb, Object *target, init_curve_deform(cuOb, target, &cd); cd.no_rot_axis = no_rot_axis; /* option to only rotate for XY, for example */ - + copy_v3_v3(cd.dmin, orco); copy_v3_v3(cd.dmax, orco); mul_m4_v3(cd.curvespace, vec); - + if (calc_curve_deform(cuOb, vec, target->trackflag, &cd, quat)) { float qmat[3][3]; - + quat_to_mat3(qmat, quat); mul_m3_m3m3(mat, qmat, cd.objectspace3); } else unit_m3(mat); - + mul_m4_v3(cd.objectspace, vec); } @@ -937,11 +937,11 @@ void outside_lattice(Lattice *lt) if (lt->pntsu > 1) du = 1.0f / ((float)lt->pntsu - 1); if (lt->pntsv > 1) dv = 1.0f / ((float)lt->pntsv - 1); if (lt->pntsw > 1) dw = 1.0f / ((float)lt->pntsw - 1); - + for (w = 0; w < lt->pntsw; w++) { - + for (v = 0; v < lt->pntsv; v++) { - + for (u = 0; u < lt->pntsu; u++, bp++) { if (u == 0 || v == 0 || w == 0 || u == lt->pntsu - 1 || v == lt->pntsv - 1 || w == lt->pntsw - 1) { /* pass */ @@ -949,41 +949,41 @@ void outside_lattice(Lattice *lt) else { bp->hide = 1; bp->f1 &= ~SELECT; - + /* u extrema */ bp1 = latt_bp(lt, 0, v, w); bp2 = latt_bp(lt, lt->pntsu - 1, v, w); - + fac1 = du * u; bp->vec[0] = (1.0f - fac1) * bp1->vec[0] + fac1 * bp2->vec[0]; bp->vec[1] = (1.0f - fac1) * bp1->vec[1] + fac1 * bp2->vec[1]; bp->vec[2] = (1.0f - fac1) * bp1->vec[2] + fac1 * bp2->vec[2]; - + /* v extrema */ bp1 = latt_bp(lt, u, 0, w); bp2 = latt_bp(lt, u, lt->pntsv - 1, w); - + fac1 = dv * v; bp->vec[0] += (1.0f - fac1) * bp1->vec[0] + fac1 * bp2->vec[0]; bp->vec[1] += (1.0f - fac1) * bp1->vec[1] + fac1 * bp2->vec[1]; bp->vec[2] += (1.0f - fac1) * bp1->vec[2] + fac1 * bp2->vec[2]; - + /* w extrema */ bp1 = latt_bp(lt, u, v, 0); bp2 = latt_bp(lt, u, v, lt->pntsw - 1); - + fac1 = dw * w; bp->vec[0] += (1.0f - fac1) * bp1->vec[0] + fac1 * bp2->vec[0]; bp->vec[1] += (1.0f - fac1) * bp1->vec[1] + fac1 * bp2->vec[1]; bp->vec[2] += (1.0f - fac1) * bp1->vec[2] + fac1 * bp2->vec[2]; - + mul_v3_fl(bp->vec, 1.0f / 3.0f); - + } } - + } - + } } else { @@ -1004,9 +1004,9 @@ float (*BKE_lattice_vertexcos_get(struct Object *ob, int *r_numVerts))[3] if (lt->editlatt) lt = lt->editlatt->latt; numVerts = *r_numVerts = lt->pntsu * lt->pntsv * lt->pntsw; - + vertexCos = MEM_mallocN(sizeof(*vertexCos) * numVerts, "lt_vcos"); - + for (i = 0; i < numVerts; i++) { copy_v3_v3(vertexCos[i], lt->def[i].vec); } @@ -1046,7 +1046,7 @@ void BKE_lattice_modifiers_calc(struct Depsgraph *depsgraph, Scene *scene, Objec const ModifierTypeInfo *mti = modifierType_getInfo(md->type); md->scene = scene; - + if (!(mti->flags & eModifierTypeFlag_AcceptsLattice)) continue; if (!(md->mode & eModifierMode_Realtime)) continue; if (editmode && !(md->mode & eModifierMode_Editmode)) continue; @@ -1072,7 +1072,7 @@ void BKE_lattice_modifiers_calc(struct Depsgraph *depsgraph, Scene *scene, Objec dl->parts = 1; dl->nr = numVerts; dl->verts = (float *) vertexCos; - + BLI_addtail(&ob->curve_cache->disp, dl); } } @@ -1154,7 +1154,7 @@ void BKE_lattice_minmax_dl(Object *ob, Lattice *lt, float min[3], float max[3]) } else { int i, numVerts; - + if (lt->editlatt) lt = lt->editlatt->latt; numVerts = lt->pntsu * lt->pntsv * lt->pntsw; diff --git a/source/blender/blenkernel/intern/layer.c b/source/blender/blenkernel/intern/layer.c index c7bb24cdcee..db9ce76b30c 100644 --- a/source/blender/blenkernel/intern/layer.c +++ b/source/blender/blenkernel/intern/layer.c @@ -439,7 +439,9 @@ static LayerCollection *collection_from_index(ListBase *lb, const int number, in } (*i)++; + } + for (LayerCollection *lc = lb->first; lc; lc = lc->next) { LayerCollection *lc_nested = collection_from_index(&lc->layer_collections, number, i); if (lc_nested) { return lc_nested; @@ -537,7 +539,9 @@ static int index_from_collection(ListBase *lb, const LayerCollection *lc, int *i } (*i)++; + } + for (LayerCollection *lcol = lb->first; lcol; lcol = lcol->next) { int i_nested = index_from_collection(&lcol->layer_collections, lc, i); if (i_nested != -1) { return i_nested; @@ -567,7 +571,7 @@ int BKE_layer_collection_findindex(ViewLayer *view_layer, const LayerCollection * in at least one layer collection. That list is also synchronized here, and * stores state like selection. */ -static void layer_collection_sync( +static int layer_collection_sync( ViewLayer *view_layer, const ListBase *lb_scene, ListBase *lb_layer, ListBase *new_object_bases, int parent_exclude, int parent_restrict) @@ -594,6 +598,7 @@ static void layer_collection_sync( /* Add layer collections for any new scene collections, and ensure order is the same. */ ListBase new_lb_layer = {NULL, NULL}; + int runtime_flag = 0; for (const CollectionChild *child = lb_scene->first; child; child = child->next) { Collection *collection = child->collection; @@ -615,15 +620,19 @@ static void layer_collection_sync( } /* Sync child collections. */ - layer_collection_sync( + int child_runtime_flag = layer_collection_sync( view_layer, &collection->children, &lc->layer_collections, new_object_bases, lc->flag, child_restrict); /* Layer collection exclude is not inherited. */ if (lc->flag & LAYER_COLLECTION_EXCLUDE) { + lc->runtime_flag = 0; continue; } + else { + lc->runtime_flag = child_runtime_flag; + } /* Sync objects, except if collection was excluded. */ for (CollectionObject *cob = collection->gobject.first; cob; cob = cob->next) { @@ -645,22 +654,50 @@ static void layer_collection_sync( BLI_ghash_insert(view_layer->object_bases_hash, base->object, base); } - if ((child_restrict & COLLECTION_RESTRICT_VIEW) == 0) { + int object_restrict = base->object->restrictflag; + + if (((child_restrict & COLLECTION_RESTRICT_VIEW) == 0) && + ((object_restrict & OB_RESTRICT_VIEW) == 0)) + { base->flag |= BASE_VISIBLED | BASE_VISIBLE_VIEWPORT; - if ((child_restrict & COLLECTION_RESTRICT_SELECT) == 0) { + if (((child_restrict & COLLECTION_RESTRICT_SELECT) == 0) && + ((object_restrict & OB_RESTRICT_SELECT) == 0)) + { base->flag |= BASE_SELECTABLED; } } - if ((child_restrict & COLLECTION_RESTRICT_RENDER) == 0) { + + if (((child_restrict & COLLECTION_RESTRICT_RENDER) == 0) && + ((object_restrict & OB_RESTRICT_RENDER) == 0)) + + { base->flag |= BASE_VISIBLE_RENDER; } + + /* Update runtime flags used for display and tools. */ + if (base->flag & BASE_VISIBLED) { + lc->runtime_flag |= LAYER_COLLECTION_HAS_ENABLED_OBJECTS; + } + + if (base->flag & BASE_HIDE) { + view_layer->runtime_flag |= VIEW_LAYER_HAS_HIDE; + } + else if (base->flag & BASE_VISIBLED) { + lc->runtime_flag |= LAYER_COLLECTION_HAS_VISIBLE_OBJECTS; + } + + lc->runtime_flag |= LAYER_COLLECTION_HAS_OBJECTS; } + + runtime_flag |= lc->runtime_flag; } /* Replace layer collection list with new one. */ *lb_layer = new_lb_layer; BLI_assert(BLI_listbase_count(lb_scene) == BLI_listbase_count(lb_layer)); + + return runtime_flag; } /** @@ -688,6 +725,8 @@ void BKE_layer_collection_sync(const Scene *scene, ViewLayer *view_layer) base->flag &= ~(BASE_VISIBLED | BASE_SELECTABLED | BASE_VISIBLE_VIEWPORT | BASE_VISIBLE_RENDER); } + view_layer->runtime_flag = 0; + /* Generate new layer connections and object bases when collections changed. */ CollectionChild child = {NULL, NULL, scene->master_collection}; const ListBase collections = {&child, &child}; @@ -759,6 +798,7 @@ void BKE_main_collection_sync_remap(const Main *bmain) for (Collection *collection = bmain->collection.first; collection; collection = collection->id.next) { BKE_collection_object_cache_free(collection); + DEG_id_tag_update_ex((Main *)bmain, &collection->id, DEG_TAG_COPY_ON_WRITE); } BKE_main_collection_sync(bmain); @@ -808,6 +848,107 @@ bool BKE_layer_collection_objects_select(ViewLayer *view_layer, LayerCollection return changed; } +bool BKE_layer_collection_has_selected_objects(ViewLayer *view_layer, LayerCollection *lc) +{ + if (lc->collection->flag & COLLECTION_RESTRICT_SELECT) { + return false; + } + + if (!(lc->flag & LAYER_COLLECTION_EXCLUDE)) { + for (CollectionObject *cob = lc->collection->gobject.first; cob; cob = cob->next) { + Base *base = BKE_view_layer_base_find(view_layer, cob->ob); + + if (base && (base->flag & BASE_SELECTED)) { + return true; + } + } + } + + for (LayerCollection *iter = lc->layer_collections.first; iter; iter = iter->next) { + if (BKE_layer_collection_has_selected_objects(view_layer, iter)) { + return true; + } + } + + return false; +} + +/* ---------------------------------------------------------------------- */ + +/* Test base visibility when BASE_VISIBLED has not been set yet. */ +static bool base_is_visible(Base *base, eEvaluationMode mode) +{ + if (mode == DAG_EVAL_VIEWPORT) { + return ((base->flag & BASE_VISIBLE_VIEWPORT) != 0) && + ((base->flag & BASE_HIDE) == 0); + } + else { + return ((base->flag & BASE_VISIBLE_RENDER) != 0); + } +} + +/* Update after toggling visibility of an object base. */ +void BKE_base_set_visible(Scene *scene, ViewLayer *view_layer, Base *base, bool extend) +{ + if (!extend) { + /* Make only one base visible. */ + for (Base *other = view_layer->object_bases.first; other; other = other->next) { + other->flag |= BASE_HIDE; + } + + base->flag &= ~BASE_HIDE; + } + else { + /* Toggle visibility of one base. */ + base->flag ^= BASE_HIDE; + } + + BKE_layer_collection_sync(scene, view_layer); +} + +void BKE_layer_collection_set_visible(Scene *scene, ViewLayer *view_layer, LayerCollection *lc, bool extend) +{ + if (!extend) { + /* Make only objects from one collection visible. */ + for (Base *base = view_layer->object_bases.first; base; base = base->next) { + base->flag |= BASE_HIDE; + } + + FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(lc->collection, ob) + { + Base *base = BLI_ghash_lookup(view_layer->object_bases_hash, ob); + + if (base) { + base->flag &= ~BASE_HIDE; + } + } + FOREACH_COLLECTION_OBJECT_RECURSIVE_END; + + BKE_layer_collection_activate(view_layer, lc); + } + else { + /* Toggle visibility of objects from collection. */ + bool hide = (lc->runtime_flag & LAYER_COLLECTION_HAS_VISIBLE_OBJECTS) != 0; + + FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(lc->collection, ob) + { + Base *base = BLI_ghash_lookup(view_layer->object_bases_hash, ob); + + if (base) { + if (hide) { + base->flag |= BASE_HIDE; + } + else { + base->flag &= ~BASE_HIDE; + } + } + } + FOREACH_COLLECTION_OBJECT_RECURSIVE_END; + } + + BKE_layer_collection_sync(scene, view_layer); +} + /* ---------------------------------------------------------------------- */ static LayerCollection *find_layer_collection_by_scene_collection(LayerCollection *lc, const Collection *collection) @@ -1234,21 +1375,8 @@ void BKE_layer_eval_view_layer( { DEG_debug_print_eval(depsgraph, __func__, view_layer->name, view_layer); - /* Set visibility based on depsgraph mode. */ + /* Visibility based on depsgraph mode. */ const eEvaluationMode mode = DEG_get_mode(depsgraph); - const int base_flag = (mode == DAG_EVAL_VIEWPORT) ? BASE_VISIBLE_VIEWPORT : BASE_VISIBLE_RENDER; - - for (Base *base = view_layer->object_bases.first; base != NULL; base = base->next) { - if (base->flag & base_flag) { - base->flag |= BASE_VISIBLED; - } - else { - base->flag &= ~BASE_VISIBLED; - } - } - - /* TODO(sergey): Is it always required? */ - view_layer->flag |= VIEW_LAYER_ENGINE_DIRTY; /* Create array of bases, for fast index-based lookup. */ const int num_object_bases = BLI_listbase_count(&view_layer->object_bases); @@ -1257,15 +1385,26 @@ void BKE_layer_eval_view_layer( num_object_bases, sizeof(Base *), "view_layer->object_bases_array"); int base_index = 0; for (Base *base = view_layer->object_bases.first; base; base = base->next) { - /* if base is not selectabled, clear select. */ + /* Set visibility. */ + if (base_is_visible(base, mode)) { + base->flag |= BASE_VISIBLED; + } + else { + base->flag &= ~(BASE_VISIBLED | BASE_SELECTABLED); + } + + /* If base is not selectabled, clear select. */ if ((base->flag & BASE_SELECTABLED) == 0) { base->flag &= ~BASE_SELECTED; } - /* Store base in the array. */ + view_layer->object_bases_array[base_index++] = base; } + + + /* Flush back base flag to the original view layer for editing. */ + ViewLayer *view_layer_orig = DEG_get_input_view_layer(depsgraph); if (view_layer == DEG_get_evaluated_view_layer(depsgraph)) { - ViewLayer *view_layer_orig = DEG_get_input_view_layer(depsgraph); Base *base_orig = view_layer_orig->object_bases.first; const Base *base_eval = view_layer->object_bases.first; while (base_orig != NULL) { @@ -1274,6 +1413,14 @@ void BKE_layer_eval_view_layer( base_eval = base_eval->next; } } + + /* Hidden objects can't be active. */ + if (view_layer->basact && !(view_layer->basact->flag & BASE_VISIBLED)) { + view_layer->basact = NULL; + } + if (view_layer_orig->basact && !(view_layer_orig->basact->flag & BASE_VISIBLED)) { + view_layer_orig->basact = NULL; + } } void BKE_layer_eval_view_layer_indexed( diff --git a/source/blender/blenkernel/intern/library.c b/source/blender/blenkernel/intern/library.c index a885f22b739..c45903aa1fa 100644 --- a/source/blender/blenkernel/intern/library.c +++ b/source/blender/blenkernel/intern/library.c @@ -142,7 +142,7 @@ # include "PIL_time_utildefines.h" #endif -/* GS reads the memory pointed at in a specific ordering. +/* GS reads the memory pointed at in a specific ordering. * only use this definition, makes little and big endian systems * work fine, in conjunction with MAKE_ID */ @@ -768,13 +768,14 @@ bool id_single_user(bContext *C, ID *id, PointerRNA *ptr, PropertyRNA *prop) { ID *newid = NULL; PointerRNA idptr; - + if (id) { /* if property isn't editable, we're going to have an extra block hanging around until we save */ if (RNA_property_editable(ptr, prop)) { - if (id_copy(CTX_data_main(C), id, &newid, false) && newid) { + Main *bmain = CTX_data_main(C); + if (id_copy(bmain, id, &newid, false) && newid) { /* copy animation actions too */ - BKE_animdata_copy_id_action(id, false); + BKE_animdata_copy_id_action(bmain, id, false); /* us is 1 by convention, but RNA_property_pointer_set * will also increment it, so set it to zero */ newid->us = 0; @@ -783,12 +784,12 @@ bool id_single_user(bContext *C, ID *id, PointerRNA *ptr, PropertyRNA *prop) RNA_id_pointer_create(newid, &idptr); RNA_property_pointer_set(ptr, prop, idptr); RNA_property_update(C, ptr, prop); - + return true; } } } - + return false; } @@ -1078,9 +1079,9 @@ int set_listbasepointers(Main *main, ListBase **lb) lb[INDEX_ID_TE] = &(main->tex); lb[INDEX_ID_MA] = &(main->mat); lb[INDEX_ID_VF] = &(main->vfont); - + /* Important!: When adding a new object type, - * the specific data should be inserted here + * the specific data should be inserted here */ lb[INDEX_ID_AR] = &(main->armature); @@ -1113,7 +1114,7 @@ int set_listbasepointers(Main *main, ListBase **lb) lb[INDEX_ID_WS] = &(main->workspaces); /* before wm, so it's freed after it! */ lb[INDEX_ID_WM] = &(main->wm); lb[INDEX_ID_MSK] = &(main->mask); - + lb[INDEX_ID_NULL] = NULL; return (MAX_LIBARRAY - 1); @@ -1408,7 +1409,7 @@ void *BKE_id_new_nomain(const short type, const char *name) static void id_copy_animdata(Main *bmain, ID *id, const bool do_action) { AnimData *adt = BKE_animdata_from_id(id); - + if (adt) { IdAdtTemplate *iat = (IdAdtTemplate *)id; iat->adt = BKE_animdata_copy(bmain, iat->adt, do_action, true); /* could be set to false, need to investigate */ @@ -1527,7 +1528,7 @@ void BKE_main_free(Main *mainvar) while (a--) { ListBase *lb = lbarray[a]; ID *id; - + while ( (id = lb->first) ) { #if 1 BKE_libblock_free_ex(mainvar, id, false, false); @@ -1766,11 +1767,11 @@ ID *BKE_libblock_find_name(struct Main *bmain, const short type, const char *nam void id_sort_by_name(ListBase *lb, ID *id) { ID *idtest; - + /* insert alphabetically */ if (lb->first != lb->last) { BLI_remlink(lb, id); - + idtest = lb->first; while (idtest) { if (BLI_strcasecmp(idtest->name, id->name) > 0 || (idtest->lib && !id->lib)) { @@ -1784,7 +1785,7 @@ void id_sort_by_name(ListBase *lb, ID *id) BLI_addtail(lb, id); } } - + } /** @@ -1794,9 +1795,9 @@ void id_sort_by_name(ListBase *lb, ID *id) static ID *is_dupid(ListBase *lb, ID *id, const char *name) { ID *idtest = NULL; - + for (idtest = lb->first; idtest; idtest = idtest->next) { - /* if idtest is not a lib */ + /* if idtest is not a lib */ if (id != idtest && !ID_IS_LINKED(idtest)) { /* do not test alphabetic! */ /* optimized */ @@ -1805,7 +1806,7 @@ static ID *is_dupid(ListBase *lb, ID *id, const char *name) } } } - + return idtest; } @@ -1894,8 +1895,8 @@ static bool check_for_dupid(ListBase *lb, ID *id, char *name) * or 1 greater than the largest used number if all those low ones are taken. * We can't be bothered to look for the lowest unused number beyond (MAX_IN_USE - 1). */ - /* If the original name has no numeric suffix, - * rather than just chopping and adding numbers, + /* If the original name has no numeric suffix, + * rather than just chopping and adding numbers, * shave off the end chars until we have a unique name. * Check the null terminators match as well so we don't get Cube.000 -> Cube.00 */ if (nr == 0 && name[left_len] == '\0') { @@ -1906,7 +1907,7 @@ static bool check_for_dupid(ListBase *lb, ID *id, char *name) len = left_len - 1; idtest = is_dupid(lb, id, name); - + while (idtest && len > 1) { name[len--] = '\0'; idtest = is_dupid(lb, id, name); @@ -1914,7 +1915,7 @@ static bool check_for_dupid(ListBase *lb, ID *id, char *name) if (idtest == NULL) return true; /* otherwise just continue and use a number suffix */ } - + if (nr > 999 && left_len > (MAX_ID_NAME - 8)) { /* this would overflow name buffer */ left[MAX_ID_NAME - 8] = 0; @@ -1977,7 +1978,7 @@ bool new_id(ListBase *lb, ID *id, const char *tname) #endif id_sort_by_name(lb, id); - + return result; } @@ -2492,7 +2493,7 @@ void BLI_libblock_ensure_unique_name(Main *bmain, const char *name) lb = which_libbase(bmain, GS(name)); if (lb == NULL) return; - + /* search for id */ idtest = BLI_findstring(lb, name + 2, offsetof(ID, name) + 2); diff --git a/source/blender/blenkernel/intern/library_query.c b/source/blender/blenkernel/intern/library_query.c index 37b5b62b06e..f23d8720a65 100644 --- a/source/blender/blenkernel/intern/library_query.c +++ b/source/blender/blenkernel/intern/library_query.c @@ -352,10 +352,6 @@ void BKE_library_foreach_ID_link(Main *bmain, ID *id, LibraryIDLinkCallback call #define CALLBACK_INVOKE(check_id_super, cb_flag) \ FOREACH_CALLBACK_INVOKE(&data, check_id_super, cb_flag) - if (id->override_static != NULL) { - CALLBACK_INVOKE_ID(id->override_static->reference, IDWALK_CB_USER | IDWALK_CB_STATIC_OVERRIDE_REFERENCE); - } - for (; id != NULL; id = (flag & IDWALK_RECURSE) ? BLI_LINKSTACK_POP(data.ids_todo) : NULL) { data.self_id = id; data.cb_flag = ID_IS_LINKED(id) ? IDWALK_CB_INDIRECT_USAGE : 0; @@ -372,6 +368,11 @@ void BKE_library_foreach_ID_link(Main *bmain, ID *id, LibraryIDLinkCallback call continue; } + if (id->override_static != NULL) { + CALLBACK_INVOKE_ID(id->override_static->reference, IDWALK_CB_USER | IDWALK_CB_STATIC_OVERRIDE_REFERENCE); + CALLBACK_INVOKE_ID(id->override_static->storage, IDWALK_CB_USER | IDWALK_CB_STATIC_OVERRIDE_REFERENCE); + } + library_foreach_idproperty_ID_link(&data, id->properties, IDWALK_CB_USER); AnimData *adt = BKE_animdata_from_id(id); diff --git a/source/blender/blenkernel/intern/library_remap.c b/source/blender/blenkernel/intern/library_remap.c index e3c10175feb..f34a2ff7f84 100644 --- a/source/blender/blenkernel/intern/library_remap.c +++ b/source/blender/blenkernel/intern/library_remap.c @@ -195,8 +195,10 @@ static int foreach_libblock_remap_callback(void *user_data, ID *id_self, ID **id const bool skip_never_null = (id_remap_data->flag & ID_REMAP_SKIP_NEVER_NULL_USAGE) != 0; #ifdef DEBUG_PRINT - printf("In %s: Remapping %s (%p) to %s (%p) (is_indirect: %d, skip_indirect: %d)\n", - id->name, old_id->name, old_id, new_id ? new_id->name : "<NONE>", new_id, is_indirect, skip_indirect); + printf("In %s (lib %p): Remapping %s (%p) to %s (%p) " + "(is_indirect: %d, skip_indirect: %d, is_reference: %d, skip_reference: %d)\n", + id->name, id->lib, old_id->name, old_id, new_id ? new_id->name : "<NONE>", new_id, + is_indirect, skip_indirect, is_reference, skip_reference); #endif if ((id_remap_data->flag & ID_REMAP_FLAG_NEVER_NULL_USAGE) && (cb_flag & IDWALK_CB_NEVER_NULL)) { @@ -239,7 +241,7 @@ static int foreach_libblock_remap_callback(void *user_data, ID *id_self, ID **id else { if (!is_never_null) { *id_p = new_id; - DEG_id_tag_update_ex(id_remap_data->bmain, id_self, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME); + DEG_id_tag_update_ex(id_remap_data->bmain, id_self, DEG_TAG_TRANSFORM | DEG_TAG_TIME | DEG_TAG_GEOMETRY); } if (cb_flag & IDWALK_CB_USER) { id_us_min(old_id); @@ -1015,7 +1017,7 @@ void BKE_libblock_free(Main *bmain, void *idv) void BKE_libblock_free_us(Main *bmain, void *idv) /* test users */ { ID *id = idv; - + id_us_min(id); /* XXX This is a temp (2.77) hack so that we keep same behavior as in 2.76 regarding collections when deleting an object. @@ -1031,7 +1033,7 @@ void BKE_libblock_free_us(Main *bmain, void *idv) /* test users */ if (id->us == 0) { BKE_libblock_unlink(bmain, id, false, false); - + BKE_libblock_free(bmain, id); } } diff --git a/source/blender/blenkernel/intern/material.c b/source/blender/blenkernel/intern/material.c index 1ea2f170922..21b2ab6b454 100644 --- a/source/blender/blenkernel/intern/material.c +++ b/source/blender/blenkernel/intern/material.c @@ -49,8 +49,8 @@ #include "DNA_object_types.h" #include "DNA_scene_types.h" -#include "BLI_math.h" -#include "BLI_listbase.h" +#include "BLI_math.h" +#include "BLI_listbase.h" #include "BLI_utildefines.h" #include "BLI_string.h" #include "BLI_array_utils.h" @@ -90,10 +90,10 @@ void init_def_material(void) void BKE_material_free(Material *ma) { BKE_animdata_free((ID *)ma, false); - + /* Free gpu material before the ntree */ GPU_material_free(&ma->gpumaterial); - + /* is no lib link block, but material extension */ if (ma->nodetree) { ntreeFreeTree(ma->nodetree); @@ -117,7 +117,7 @@ void BKE_material_init(Material *ma) ma->spec = 0.5; ma->roughness = 0.25f; - + ma->pr_lamp = 3; /* two lamps, is bits */ ma->pr_type = MA_SPHERE; @@ -131,9 +131,9 @@ Material *BKE_material_add(Main *bmain, const char *name) Material *ma; ma = BKE_libblock_alloc(bmain, ID_MA, name, 0); - + BKE_material_init(ma); - + return ma; } @@ -218,7 +218,7 @@ Material ***give_matarar(Object *ob) Mesh *me; Curve *cu; MetaBall *mb; - + if (ob->type == OB_MESH) { me = ob->data; return &(me->mat); @@ -239,7 +239,7 @@ short *give_totcolp(Object *ob) Mesh *me; Curve *cu; MetaBall *mb; - + if (ob->type == OB_MESH) { me = ob->data; return &(me->totcol); @@ -413,7 +413,7 @@ Material *BKE_material_pop_id(Main *bmain, ID *id, int index_i, bool update_data DEG_relations_tag_update(bmain); } } - + return ret; } @@ -447,7 +447,7 @@ Material *give_current_material(Object *ob, short act) const short *totcolp; if (ob == NULL) return NULL; - + /* if object cannot have material, (totcolp == NULL) */ totcolp = give_totcolp(ob); if (totcolp == NULL || ob->totcol == 0) return NULL; @@ -473,12 +473,12 @@ Material *give_current_material(Object *ob, short act) if (act > ob->totcol) act = ob->totcol; matarar = give_matarar(ob); - + if (matarar && *matarar) ma = (*matarar)[act - 1]; else ma = NULL; - + } - + return ma; } @@ -621,18 +621,18 @@ void assign_material(Main *bmain, Object *ob, Material *ma, short act, int assig if (act > MAXMAT) return; if (act < 1) act = 1; - + /* prevent crashing when using accidentally */ BLI_assert(!ID_IS_LINKED(ob)); if (ID_IS_LINKED(ob)) return; - + /* test arraylens */ - + totcolp = give_totcolp(ob); matarar = give_matarar(ob); - + if (totcolp == NULL || matarar == NULL) return; - + if (act > *totcolp) { matar = MEM_callocN(sizeof(void *) * act, "matarray1"); @@ -676,7 +676,7 @@ void assign_material(Main *bmain, Object *ob, Material *ma, short act, int assig break; } } - + /* do it */ ob->matbits[act - 1] = bit; @@ -811,14 +811,14 @@ short BKE_object_material_slot_find_index(Object *ob, Material *ma) { Material ***matarar; short a, *totcolp; - + if (ma == NULL) return 0; - + totcolp = give_totcolp(ob); matarar = give_matarar(ob); - + if (totcolp == NULL || matarar == NULL) return 0; - + for (a = 0; a < *totcolp; a++) if ((*matarar)[a] == ma) break; @@ -831,7 +831,7 @@ bool BKE_object_material_slot_add(Main *bmain, Object *ob) { if (ob == NULL) return false; if (ob->totcol >= MAXMAT) return false; - + assign_material(bmain, ob, NULL, ob->totcol + 1, BKE_MAT_ASSIGN_USERPREF); ob->actcol = ob->totcol; return true; @@ -844,7 +844,7 @@ bool BKE_object_material_slot_remove(Main *bmain, Object *ob) Material *mao, ***matarar; short *totcolp; short a, actcol; - + if (ob == NULL || ob->totcol == 0) { return false; } @@ -858,10 +858,10 @@ bool BKE_object_material_slot_remove(Main *bmain, Object *ob) /* take a mesh/curve/mball as starting point, remove 1 index, * AND with all objects that share the ob->data - * + * * after that check indices in mesh/curve/mball!!! */ - + totcolp = give_totcolp(ob); matarar = give_matarar(ob); @@ -873,21 +873,21 @@ bool BKE_object_material_slot_remove(Main *bmain, Object *ob) if (ob->actcol > ob->totcol) { ob->actcol = ob->totcol; } - + /* we delete the actcol */ mao = (*matarar)[ob->actcol - 1]; if (mao) id_us_min(&mao->id); - + for (a = ob->actcol; a < ob->totcol; a++) (*matarar)[a - 1] = (*matarar)[a]; (*totcolp)--; - + if (*totcolp == 0) { MEM_freeN(*matarar); *matarar = NULL; } - + actcol = ob->actcol; for (Object *obt = bmain->object.first; obt; obt = obt->id.next) { @@ -900,14 +900,14 @@ bool BKE_object_material_slot_remove(Main *bmain, Object *ob) mao = obt->mat[actcol - 1]; if (mao) id_us_min(&mao->id); - + for (a = actcol; a < obt->totcol; a++) { obt->mat[a - 1] = obt->mat[a]; obt->matbits[a - 1] = obt->matbits[a]; } obt->totcol--; if (obt->actcol > obt->totcol) obt->actcol = obt->totcol; - + if (obt->totcol == 0) { MEM_freeN(obt->mat); MEM_freeN(obt->matbits); @@ -932,7 +932,7 @@ static bNode *nodetree_uv_node_recursive(bNode *node) { bNode *inode; bNodeSocket *sock; - + for (sock = node->inputs.first; sock; sock = sock->next) { if (sock->link) { inode = sock->link->fromnode; @@ -944,7 +944,7 @@ static bNode *nodetree_uv_node_recursive(bNode *node) } } } - + return NULL; } @@ -967,7 +967,7 @@ void BKE_texpaint_slot_refresh_cache(Scene *scene, Material *ma) ma->paint_clone_slot = 0; return; } - + bNode *node, *active_node; if (!(ma->nodetree)) { @@ -995,10 +995,10 @@ void BKE_texpaint_slot_refresh_cache(Scene *scene, Material *ma) if (active_node == node) ma->paint_active_slot = index; ma->texpaintslot[index].ima = (Image *)node->id; - + /* for new renderer, we need to traverse the treeback in search of a UV node */ bNode *uvnode = nodetree_uv_node_recursive(node); - + if (uvnode) { NodeShaderUVMap *storage = (NodeShaderUVMap *)uvnode->storage; ma->texpaintslot[index].uvname = storage->uv_map; @@ -1014,8 +1014,8 @@ void BKE_texpaint_slot_refresh_cache(Scene *scene, Material *ma) } ma->tot_slots = count; - - + + if (ma->paint_active_slot >= count) { ma->paint_active_slot = count - 1; } @@ -1042,7 +1042,7 @@ void BKE_texpaint_slots_refresh_object(Scene *scene, struct Object *ob) void ramp_blend(int type, float r_col[3], const float fac, const float col[3]) { float tmp, facm = 1.0f - fac; - + switch (type) { case MA_RAMP_BLEND: r_col[0] = facm * (r_col[0]) + fac * col[0]; diff --git a/source/blender/blenkernel/intern/mball.c b/source/blender/blenkernel/intern/mball.c index 3afaf2d569e..2ff69c5ee6d 100644 --- a/source/blender/blenkernel/intern/mball.c +++ b/source/blender/blenkernel/intern/mball.c @@ -89,7 +89,7 @@ void BKE_mball_init(MetaBall *mb) mb->size[0] = mb->size[1] = mb->size[2] = 1.0; mb->texflag = MB_AUTOSPACE; - + mb->wiresize = 0.4f; mb->rendersize = 0.2f; mb->thresh = 0.6f; @@ -201,7 +201,7 @@ void BKE_mball_texspace_calc(Object *ob) if (ob->bb == NULL) ob->bb = MEM_callocN(sizeof(BoundBox), "mb boundbox"); bb = ob->bb; - + /* Weird one, this. */ /* INIT_MINMAX(min, max); */ (min)[0] = (min)[1] = (min)[2] = 1.0e30f; diff --git a/source/blender/blenkernel/intern/mesh.c b/source/blender/blenkernel/intern/mesh.c index b325d8d02d9..f502d7e394f 100644 --- a/source/blender/blenkernel/intern/mesh.c +++ b/source/blender/blenkernel/intern/mesh.c @@ -107,7 +107,7 @@ static int customdata_compare(CustomData *c1, CustomData *c2, Mesh *m1, Mesh *m2 const float thresh_sq = thresh * thresh; CustomDataLayer *l1, *l2; int i, i1 = 0, i2 = 0, tot, j; - + for (i = 0; i < c1->totlayer; i++) { if (ELEM(c1->layers[i].type, CD_MVERT, CD_MEDGE, CD_MPOLY, CD_MLOOPUV, CD_MLOOPCOL, CD_MDEFORMVERT)) @@ -126,7 +126,7 @@ static int customdata_compare(CustomData *c1, CustomData *c2, Mesh *m1, Mesh *m2 if (i1 != i2) return MESHCMP_CDLAYERS_MISMATCH; - + l1 = c1->layers; l2 = c2->layers; tot = i1; i1 = 0; i2 = 0; @@ -144,52 +144,52 @@ static int customdata_compare(CustomData *c1, CustomData *c2, Mesh *m1, Mesh *m2 i2++; l2++; } - + if (l1->type == CD_MVERT) { MVert *v1 = l1->data; MVert *v2 = l2->data; int vtot = m1->totvert; - + for (j = 0; j < vtot; j++, v1++, v2++) { if (len_squared_v3v3(v1->co, v2->co) > thresh_sq) return MESHCMP_VERTCOMISMATCH; /* I don't care about normals, let's just do coodinates */ } } - + /*we're order-agnostic for edges here*/ if (l1->type == CD_MEDGE) { MEdge *e1 = l1->data; MEdge *e2 = l2->data; int etot = m1->totedge; EdgeHash *eh = BLI_edgehash_new_ex(__func__, etot); - + for (j = 0; j < etot; j++, e1++) { BLI_edgehash_insert(eh, e1->v1, e1->v2, e1); } - + for (j = 0; j < etot; j++, e2++) { if (!BLI_edgehash_lookup(eh, e2->v1, e2->v2)) return MESHCMP_EDGEUNKNOWN; } BLI_edgehash_free(eh, NULL); } - + if (l1->type == CD_MPOLY) { MPoly *p1 = l1->data; MPoly *p2 = l2->data; int ptot = m1->totpoly; - + for (j = 0; j < ptot; j++, p1++, p2++) { MLoop *lp1, *lp2; int k; - + if (p1->totloop != p2->totloop) return MESHCMP_POLYMISMATCH; - + lp1 = m1->mloop + p1->loopstart; lp2 = m2->mloop + p2->loopstart; - + for (k = 0; k < p1->totloop; k++, lp1++, lp2++) { if (lp1->v != lp2->v) return MESHCMP_POLYVERTMISMATCH; @@ -200,7 +200,7 @@ static int customdata_compare(CustomData *c1, CustomData *c2, Mesh *m1, Mesh *m2 MLoop *lp1 = l1->data; MLoop *lp2 = l2->data; int ltot = m1->totloop; - + for (j = 0; j < ltot; j++, lp1++, lp2++) { if (lp1->v != lp2->v) return MESHCMP_LOOPMISMATCH; @@ -210,22 +210,22 @@ static int customdata_compare(CustomData *c1, CustomData *c2, Mesh *m1, Mesh *m2 MLoopUV *lp1 = l1->data; MLoopUV *lp2 = l2->data; int ltot = m1->totloop; - + for (j = 0; j < ltot; j++, lp1++, lp2++) { if (len_squared_v2v2(lp1->uv, lp2->uv) > thresh_sq) return MESHCMP_LOOPUVMISMATCH; } } - + if (l1->type == CD_MLOOPCOL) { MLoopCol *lp1 = l1->data; MLoopCol *lp2 = l2->data; int ltot = m1->totloop; - + for (j = 0; j < ltot; j++, lp1++, lp2++) { - if (ABS(lp1->r - lp2->r) > thresh || - ABS(lp1->g - lp2->g) > thresh || - ABS(lp1->b - lp2->b) > thresh || + if (ABS(lp1->r - lp2->r) > thresh || + ABS(lp1->g - lp2->g) > thresh || + ABS(lp1->b - lp2->b) > thresh || ABS(lp1->a - lp2->a) > thresh) { return MESHCMP_LOOPCOLMISMATCH; @@ -237,14 +237,14 @@ static int customdata_compare(CustomData *c1, CustomData *c2, Mesh *m1, Mesh *m2 MDeformVert *dv1 = l1->data; MDeformVert *dv2 = l2->data; int dvtot = m1->totvert; - + for (j = 0; j < dvtot; j++, dv1++, dv2++) { int k; MDeformWeight *dw1 = dv1->dw, *dw2 = dv2->dw; - + if (dv1->totweight != dv2->totweight) return MESHCMP_DVERT_TOTGROUPMISMATCH; - + for (k = 0; k < dv1->totweight; k++, dw1++, dw2++) { if (dw1->def_nr != dw2->def_nr) return MESHCMP_DVERT_GROUPMISMATCH; @@ -254,7 +254,7 @@ static int customdata_compare(CustomData *c1, CustomData *c2, Mesh *m1, Mesh *m2 } } } - + return 0; } @@ -267,22 +267,22 @@ static int customdata_compare(CustomData *c1, CustomData *c2, Mesh *m1, Mesh *m2 const char *BKE_mesh_cmp(Mesh *me1, Mesh *me2, float thresh) { int c; - + if (!me1 || !me2) return "Requires two input meshes"; - - if (me1->totvert != me2->totvert) + + if (me1->totvert != me2->totvert) return "Number of verts don't match"; - + if (me1->totedge != me2->totedge) return "Number of edges don't match"; - + if (me1->totpoly != me2->totpoly) return "Number of faces don't match"; - + if (me1->totloop != me2->totloop) return "Number of loops don't match"; - + if ((c = customdata_compare(&me1->vdata, &me2->vdata, me1, me2, thresh))) return cmpcode_to_str(c); @@ -294,7 +294,7 @@ const char *BKE_mesh_cmp(Mesh *me1, Mesh *me2, float thresh) if ((c = customdata_compare(&me1->pdata, &me2->pdata, me1, me2, thresh))) return cmpcode_to_str(c); - + return NULL; } @@ -440,7 +440,7 @@ void BKE_mesh_update_customdata_pointers(Mesh *me, const bool do_ensure_tess_cd) me->mface = CustomData_get_layer(&me->fdata, CD_MFACE); me->mcol = CustomData_get_layer(&me->fdata, CD_MCOL); me->mtface = CustomData_get_layer(&me->fdata, CD_MTFACE); - + me->mpoly = CustomData_get_layer(&me->pdata, CD_MPOLY); me->mloop = CustomData_get_layer(&me->ldata, CD_MLOOP); @@ -728,8 +728,9 @@ BMesh *BKE_mesh_to_bmesh( Mesh *BKE_bmesh_to_mesh_nomain(BMesh *bm, const struct BMeshToMeshParams *params) { + BLI_assert(params->calc_object_remap == false); Mesh *mesh = BKE_id_new_nomain(ID_ME, NULL); - BM_mesh_bm_to_me(bm, mesh, params); + BM_mesh_bm_to_me(NULL, bm, mesh, params); return mesh; } @@ -823,13 +824,13 @@ void BKE_mesh_boundbox_calc(Mesh *me, float r_loc[3], float r_size[3]) BoundBox *bb; float min[3], max[3]; float mloc[3], msize[3]; - + if (me->bb == NULL) me->bb = MEM_callocN(sizeof(BoundBox), "boundbox"); bb = me->bb; if (!r_loc) r_loc = mloc; if (!r_size) r_size = msize; - + INIT_MINMAX(min, max); if (!BKE_mesh_minmax(me, min, max)) { min[0] = min[1] = min[2] = -1.0f; @@ -837,11 +838,11 @@ void BKE_mesh_boundbox_calc(Mesh *me, float r_loc[3], float r_size[3]) } mid_v3_v3v3(r_loc, min, max); - + r_size[0] = (max[0] - min[0]) / 2.0f; r_size[1] = (max[1] - min[1]) / 2.0f; r_size[2] = (max[2] - min[2]) / 2.0f; - + BKE_boundbox_init_from_minmax(bb, min, max); bb->flag &= ~BOUNDBOX_DIRTY; @@ -1036,7 +1037,7 @@ int test_index_face(MFace *mface, CustomData *fdata, int mfindex, int nr) Mesh *BKE_mesh_from_object(Object *ob) { - + if (ob == NULL) return NULL; if (ob->type == OB_MESH) return ob->data; else return NULL; @@ -1047,9 +1048,9 @@ void BKE_mesh_assign_object(Main *bmain, Object *ob, Mesh *me) Mesh *old = NULL; multires_force_update(ob); - + if (ob == NULL) return; - + if (ob->type == OB_MESH) { old = ob->data; if (old) @@ -1057,7 +1058,7 @@ void BKE_mesh_assign_object(Main *bmain, Object *ob, Mesh *me) ob->data = me; id_us_plus((ID *)me); } - + test_object_materials(bmain, ob, (ID *)me); test_object_modifiers(ob); @@ -1127,7 +1128,7 @@ void BKE_mesh_material_remap(Mesh *me, const unsigned int *remap, unsigned int r } -void BKE_mesh_smooth_flag_set(Object *meshOb, int enableSmooth) +void BKE_mesh_smooth_flag_set(Object *meshOb, int enableSmooth) { Mesh *me = meshOb->data; int i; @@ -1142,7 +1143,7 @@ void BKE_mesh_smooth_flag_set(Object *meshOb, int enableSmooth) mp->flag &= ~ME_SMOOTH; } } - + for (i = 0; i < me->totface; i++) { MFace *mf = &me->mface[i]; @@ -1184,7 +1185,7 @@ int poly_find_loop_from_vert( if (loopstart->v == vert) return j; } - + return -1; } @@ -1201,7 +1202,7 @@ int poly_get_adj_loops_from_vert( int corner = poly_find_loop_from_vert(poly, &mloop[poly->loopstart], vert); - + if (corner != -1) { #if 0 /* unused - this loop */ const MLoop *ml = &mloop[poly->loopstart + corner]; @@ -1237,7 +1238,7 @@ bool BKE_mesh_minmax(const Mesh *me, float r_min[3], float r_max[3]) for (mvert = me->mvert; i--; mvert++) { minmax_v3v3_v3(r_min, r_max, mvert->co); } - + return (me->totvert != 0); } @@ -1280,7 +1281,7 @@ void BKE_mesh_translate(Mesh *me, const float offset[3], const bool do_keys) for (mvert = me->mvert; i--; mvert++) { add_v3_v3(mvert->co, offset); } - + if (do_keys && me->key) { KeyBlock *kb; for (kb = me->key->block.first; kb; kb = kb->next) { diff --git a/source/blender/blenkernel/intern/mesh_evaluate.c b/source/blender/blenkernel/intern/mesh_evaluate.c index 4e1297043d0..3062cd13f5f 100644 --- a/source/blender/blenkernel/intern/mesh_evaluate.c +++ b/source/blender/blenkernel/intern/mesh_evaluate.c @@ -179,7 +179,7 @@ void BKE_mesh_calc_normals_mapping_ex( /* if (fnors != r_faceNors) MEM_freeN(fnors); */ /* NO NEED TO ALLOC YET */ fnors = pnors = NULL; - + } typedef struct MeshCalcNormalsData { @@ -192,7 +192,7 @@ typedef struct MeshCalcNormalsData { } MeshCalcNormalsData; static void mesh_calc_normals_poly_cb( - void *__restrict userdata, + void *__restrict userdata, const int pidx, const ParallelRangeTLS *__restrict UNUSED(tls)) { @@ -203,7 +203,7 @@ static void mesh_calc_normals_poly_cb( } static void mesh_calc_normals_poly_prepare_cb( - void *__restrict userdata, + void *__restrict userdata, const int pidx, const ParallelRangeTLS *__restrict UNUSED(tls)) { @@ -402,14 +402,14 @@ void BKE_mesh_calc_normals_tessface( for (i = 0; i < numVerts; i++) { MVert *mv = &mverts[i]; float *no = tnorms[i]; - + if (UNLIKELY(normalize_v3(no) == 0.0f)) { normalize_v3_v3(no, mv->co); } normal_float_to_short_v3(mv->no, no); } - + cleanup: MEM_freeN(tnorms); @@ -2325,19 +2325,19 @@ static bool mesh_calc_center_centroid_ex( const MLoopTri *lt; float totweight; int i; - + zero_v3(r_center); - + if (looptri_num == 0) return false; - + totweight = 0.0f; for (i = 0, lt = looptri; i < looptri_num; i++, lt++) { const MVert *v1 = &mverts[mloop[lt->tri[0]].v]; const MVert *v2 = &mverts[mloop[lt->tri[1]].v]; const MVert *v3 = &mverts[mloop[lt->tri[2]].v]; float area; - + area = area_tri_v3(v1->co, v2->co, v3->co); madd_v3_v3fl(r_center, v1->co, area); madd_v3_v3fl(r_center, v2->co, area); @@ -2346,9 +2346,9 @@ static bool mesh_calc_center_centroid_ex( } if (totweight == 0.0f) return false; - + mul_v3_fl(r_center, 1.0f / (3.0f * totweight)); - + return true; } @@ -2368,18 +2368,18 @@ void BKE_mesh_calc_volume( float center[3]; float totvol; int i; - + if (r_volume) *r_volume = 0.0f; if (r_center) zero_v3(r_center); - + if (looptri_num == 0) return; - + if (!mesh_calc_center_centroid_ex(mverts, mverts_num, looptri, looptri_num, mloop, center)) return; - + totvol = 0.0f; for (i = 0, lt = looptri; i < looptri_num; i++, lt++) { @@ -2387,7 +2387,7 @@ void BKE_mesh_calc_volume( const MVert *v2 = &mverts[mloop[lt->tri[1]].v]; const MVert *v3 = &mverts[mloop[lt->tri[2]].v]; float vol; - + vol = volume_tetrahedron_signed_v3(center, v1->co, v2->co, v3->co); if (r_volume) { totvol += vol; @@ -2399,7 +2399,7 @@ void BKE_mesh_calc_volume( madd_v3_v3fl(r_center, v3->co, vol); } } - + /* Note: Depending on arbitrary centroid position, * totvol can become negative even for a valid mesh. * The true value is always the positive value. diff --git a/source/blender/blenkernel/intern/mesh_iterators.c b/source/blender/blenkernel/intern/mesh_iterators.c new file mode 100644 index 00000000000..48f6b1820f8 --- /dev/null +++ b/source/blender/blenkernel/intern/mesh_iterators.c @@ -0,0 +1,154 @@ +/* + * ***** BEGIN GPL LICENSE BLOCK ***** + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * Contributor(s): Blender Foundation + * + * ***** END GPL LICENSE BLOCK ***** + */ + +/** \file blender/blenkernel/intern/mesh_iterators.c + * \ingroup bke + * + * Functions for iterating mesh features. + */ + +#include "DNA_mesh_types.h" +#include "DNA_meshdata_types.h" + +#include "BKE_customdata.h" +#include "BKE_mesh.h" +#include "BKE_mesh_iterators.h" + + +/* Copied from cdDM_foreachMappedVert */ +void BKE_mesh_foreach_mapped_vert( + Mesh *mesh, + void (*func)(void *userData, int index, const float co[3], const float no_f[3], const short no_s[3]), + void *userData, + MeshForeachFlag flag) +{ + MVert *mv = mesh->mvert; + const int *index = CustomData_get_layer(&mesh->vdata, CD_ORIGINDEX); + int i; + + if (index) { + for (i = 0; i < mesh->totvert; i++, mv++) { + const short *no = (flag & MESH_FOREACH_USE_NORMAL) ? mv->no : NULL; + const int orig = *index++; + if (orig == ORIGINDEX_NONE) continue; + func(userData, orig, mv->co, NULL, no); + } + } + else { + for (i = 0; i < mesh->totvert; i++, mv++) { + const short *no = (flag & MESH_FOREACH_USE_NORMAL) ? mv->no : NULL; + func(userData, i, mv->co, NULL, no); + } + } +} + +/* Copied from cdDM_foreachMappedEdge */ +void BKE_mesh_foreach_mapped_edge( + Mesh *mesh, + void (*func)(void *userData, int index, const float v0co[3], const float v1co[3]), + void *userData) +{ + MVert *mv = mesh->mvert; + MEdge *med = mesh->medge; + int i, orig, *index = CustomData_get_layer(&mesh->edata, CD_ORIGINDEX); + + for (i = 0; i < mesh->totedge; i++, med++) { + if (index) { + orig = *index++; + if (orig == ORIGINDEX_NONE) continue; + func(userData, orig, mv[med->v1].co, mv[med->v2].co); + } + else + func(userData, i, mv[med->v1].co, mv[med->v2].co); + } +} + +/* Copied from cdDM_foreachMappedLoop */ +void BKE_mesh_foreach_mapped_loop( + Mesh *mesh, + void (*func)(void *userData, int vertex_index, int face_index, const float co[3], const float no[3]), + void *userData, + MeshForeachFlag flag) +{ + /* We can't use dm->getLoopDataLayout(dm) here, we want to always access dm->loopData, EditDerivedBMesh would + * return loop data from bmesh itself. */ + const float (*lnors)[3] = (flag & MESH_FOREACH_USE_NORMAL) ? CustomData_get_layer(&mesh->ldata, CD_NORMAL) : NULL; + + const MVert *mv = mesh->mvert; + const MLoop *ml = mesh->mloop; + const MPoly *mp = mesh->mpoly; + const int *v_index = CustomData_get_layer(&mesh->vdata, CD_ORIGINDEX); + const int *f_index = CustomData_get_layer(&mesh->pdata, CD_ORIGINDEX); + int p_idx, i; + + for (p_idx = 0; p_idx < mesh->totpoly; ++p_idx, ++mp) { + for (i = 0; i < mp->totloop; ++i, ++ml) { + const int v_idx = v_index ? v_index[ml->v] : ml->v; + const int f_idx = f_index ? f_index[p_idx] : p_idx; + const float *no = lnors ? *lnors++ : NULL; + if (!ELEM(ORIGINDEX_NONE, v_idx, f_idx)) { + func(userData, v_idx, f_idx, mv[ml->v].co, no); + } + } + } +} + +/* Copied from cdDM_foreachMappedFaceCenter */ +void BKE_mesh_foreach_mapped_face_center( + Mesh *mesh, + void (*func)(void *userData, int index, const float cent[3], const float no[3]), + void *userData, + MeshForeachFlag flag) +{ + MVert *mvert = mesh->mvert; + MPoly *mp; + MLoop *ml; + int i, orig, *index; + + index = CustomData_get_layer(&mesh->pdata, CD_ORIGINDEX); + mp = mesh->mpoly; + for (i = 0; i < mesh->totpoly; i++, mp++) { + float cent[3]; + float *no, _no[3]; + + if (index) { + orig = *index++; + if (orig == ORIGINDEX_NONE) continue; + } + else { + orig = i; + } + + ml = &mesh->mloop[mp->loopstart]; + BKE_mesh_calc_poly_center(mp, ml, mvert, cent); + + if (flag & MESH_FOREACH_USE_NORMAL) { + BKE_mesh_calc_poly_normal(mp, ml, mvert, (no = _no)); + } + else { + no = NULL; + } + + func(userData, orig, cent, no); + } + +} diff --git a/source/blender/blenkernel/intern/modifier.c b/source/blender/blenkernel/intern/modifier.c index 0b904caf375..835b78e2a78 100644 --- a/source/blender/blenkernel/intern/modifier.c +++ b/source/blender/blenkernel/intern/modifier.c @@ -130,7 +130,7 @@ ModifierData *modifier_new(int type) { const ModifierTypeInfo *mti = modifierType_getInfo(type); ModifierData *md = MEM_callocN(mti->structSize, mti->structName); - + /* note, this name must be made unique later */ BLI_strncpy(md->name, DATA_(mti->name), sizeof(md->name)); @@ -489,7 +489,7 @@ bool modifier_isEnabled(struct Scene *scene, ModifierData *md, int required_mode if (scene != NULL && mti->isDisabled && mti->isDisabled(md, required_mode == eModifierMode_Render)) return false; if (md->mode & eModifierMode_DisableTemporary) return false; if ((required_mode & eModifierMode_Editmode) && !(mti->flags & eModifierTypeFlag_SupportsEditmode)) return false; - + return true; } @@ -505,7 +505,7 @@ CDMaskLink *modifiers_calcDataMasks(struct Scene *scene, Object *ob, ModifierDat const ModifierTypeInfo *mti = modifierType_getInfo(md->type); curr = MEM_callocN(sizeof(CDMaskLink), "CDMaskLink"); - + if (modifier_isEnabled(scene, md, required_mode)) { if (mti->requiredDataMask) curr->mask = mti->requiredDataMask(ob, md); @@ -614,7 +614,7 @@ Object *modifiers_isDeformedByArmature(Object *ob) VirtualModifierData virtualModifierData; ModifierData *md = modifiers_getVirtualModifierList(ob, &virtualModifierData); ArmatureModifierData *amd = NULL; - + /* return the first selected armature, this lets us use multiple armatures */ for (; md; md = md->next) { if (md->type == eModifierType_Armature) { @@ -623,10 +623,10 @@ Object *modifiers_isDeformedByArmature(Object *ob) return amd->object; } } - + if (amd) /* if were still here then return the last armature */ return amd->object; - + return NULL; } @@ -659,7 +659,7 @@ Object *modifiers_isDeformedByLattice(Object *ob) VirtualModifierData virtualModifierData; ModifierData *md = modifiers_getVirtualModifierList(ob, &virtualModifierData); LatticeModifierData *lmd = NULL; - + /* return the first selected lattice, this lets us use multiple lattices */ for (; md; md = md->next) { if (md->type == eModifierType_Lattice) { @@ -668,10 +668,10 @@ Object *modifiers_isDeformedByLattice(Object *ob) return lmd->object; } } - + if (lmd) /* if were still here then return the last lattice */ return lmd->object; - + return NULL; } @@ -683,7 +683,7 @@ Object *modifiers_isDeformedByCurve(Object *ob) VirtualModifierData virtualModifierData; ModifierData *md = modifiers_getVirtualModifierList(ob, &virtualModifierData); CurveModifierData *cmd = NULL; - + /* return the first selected curve, this lets us use multiple curves */ for (; md; md = md->next) { if (md->type == eModifierType_Curve) { @@ -692,10 +692,10 @@ Object *modifiers_isDeformedByCurve(Object *ob) return cmd->object; } } - + if (cmd) /* if were still here then return the last curve */ return cmd->object; - + return NULL; } diff --git a/source/blender/blenkernel/intern/movieclip.c b/source/blender/blenkernel/intern/movieclip.c index fc236cc2ad0..98586a5c2f5 100644 --- a/source/blender/blenkernel/intern/movieclip.c +++ b/source/blender/blenkernel/intern/movieclip.c @@ -171,7 +171,7 @@ static void get_sequence_fname(const MovieClip *clip, BLI_strncpy(name, clip->name, sizeof(clip->name)); } - BLI_path_abs(name, ID_BLEND_PATH(G.main, &clip->id)); + BLI_path_abs(name, ID_BLEND_PATH_FROM_GLOBAL(&clip->id)); } /* supposed to work with sequences only */ @@ -261,7 +261,7 @@ static void movieclip_open_anim_file(MovieClip *clip) if (!clip->anim) { BLI_strncpy(str, clip->name, FILE_MAX); - BLI_path_abs(str, ID_BLEND_PATH(G.main, &clip->id)); + BLI_path_abs(str, ID_BLEND_PATH_FROM_GLOBAL(&clip->id)); /* FIXME: make several stream accessible in image editor, too */ clip->anim = openanim(str, IB_rect, 0, clip->colorspace_settings.name); @@ -1300,7 +1300,7 @@ void BKE_movieclip_reload(Main *bmain, MovieClip *clip) */ { Scene *scene; - for (scene = G.main->scene.first; scene; scene = scene->id.next) { + for (scene = bmain->scene.first; scene; scene = scene->id.next) { if (scene->nodetree) { nodeUpdateID(scene->nodetree, &clip->id); } @@ -1568,7 +1568,7 @@ void BKE_movieclip_filename_for_frame(MovieClip *clip, MovieClipUser *user, char } else { BLI_strncpy(name, clip->name, FILE_MAX); - BLI_path_abs(name, ID_BLEND_PATH(G.main, &clip->id)); + BLI_path_abs(name, ID_BLEND_PATH_FROM_GLOBAL(&clip->id)); } } diff --git a/source/blender/blenkernel/intern/multires.c b/source/blender/blenkernel/intern/multires.c index 39a472241bc..5bd4a1a0475 100644 --- a/source/blender/blenkernel/intern/multires.c +++ b/source/blender/blenkernel/intern/multires.c @@ -190,7 +190,7 @@ static BLI_bitmap *multires_mdisps_downsample_hidden(BLI_bitmap *old_hidden, for (x = 0; x < new_gridsize; x++) { old_value = BLI_BITMAP_TEST(old_hidden, factor * y * old_gridsize + x * factor); - + BLI_BITMAP_SET(new_hidden, y * new_gridsize + x, old_value); } } @@ -205,7 +205,7 @@ static void multires_output_hidden_to_ccgdm(CCGDerivedMesh *ccgdm, BLI_bitmap **grid_hidden = ccgdm->gridHidden; int *gridOffset; int i, j; - + gridOffset = ccgdm->dm.getGridOffset(&ccgdm->dm); for (i = 0; i < me->totpoly; i++) { @@ -213,7 +213,7 @@ static void multires_output_hidden_to_ccgdm(CCGDerivedMesh *ccgdm, int g = gridOffset[i] + j; const MDisps *md = &mdisps[g]; BLI_bitmap *gh = md->hidden; - + if (gh) { grid_hidden[g] = multires_mdisps_downsample_hidden(gh, md->level, level); @@ -227,7 +227,7 @@ static void multires_output_hidden_to_ccgdm(CCGDerivedMesh *ccgdm, static void multires_mdisps_subdivide_hidden(MDisps *md, int new_level) { BLI_bitmap *subd; - + BLI_assert(md->hidden); /* nothing to do if already subdivided enough */ @@ -238,7 +238,7 @@ static void multires_mdisps_subdivide_hidden(MDisps *md, int new_level) md->level, new_level, NULL); - + /* swap in the subdivided data */ MEM_freeN(md->hidden); md->hidden = subd; @@ -251,7 +251,7 @@ static MDisps *multires_mdisps_initialize_hidden(Mesh *me, int level) int gridsize = BKE_ccg_gridsize(level); int gridarea = SQUARE(gridsize); int i, j; - + for (i = 0; i < me->totpoly; i++) { bool hide = false; @@ -475,7 +475,7 @@ static int get_levels_from_disps(Object *ob) for (j = 0; j < me->mpoly[i].totloop; j++, md++) { if (md->totdisp == 0) continue; - + while (1) { int side = (1 << (totlvl - 1)) + 1; int lvl_totdisp = side * side; @@ -485,9 +485,9 @@ static int get_levels_from_disps(Object *ob) totlvl--; else totlvl++; - + } - + break; } } @@ -538,7 +538,7 @@ static void multires_reallocate_mdisps(int totloop, MDisps *mdisps, int lvl) if (mdisps[i].disps) MEM_freeN(mdisps[i].disps); - + if (mdisps[i].level && mdisps[i].hidden) multires_mdisps_subdivide_hidden(&mdisps[i], lvl); @@ -736,7 +736,7 @@ static DerivedMesh *subsurf_dm_create_local(Object *ob, DerivedMesh *dm, int lvl if (alloc_paint_mask) flags |= SUBSURF_ALLOC_PAINT_MASK; - + return subsurf_make_derived_from_derived(dm, &smd, NULL, flags); } @@ -802,7 +802,7 @@ void multiresModifier_base_apply(MultiresModifierData *mmd, Object *ob) /* find center */ for (j = 0; j < pmap[i].count; j++) { const MPoly *p = &me->mpoly[pmap[i].indices[j]]; - + /* this double counts, not sure if that's bad or good */ for (k = 0; k < p->totloop; ++k) { int vndx = me->mloop[p->loopstart + k].v; @@ -828,18 +828,18 @@ void multiresModifier_base_apply(MultiresModifierData *mmd, Object *ob) fake_poly.loopstart = 0; fake_loops = MEM_malloc_arrayN(p->totloop, sizeof(MLoop), "fake_loops"); fake_co = MEM_malloc_arrayN(p->totloop, 3 * sizeof(float), "fake_co"); - + for (k = 0; k < p->totloop; ++k) { int vndx = me->mloop[p->loopstart + k].v; - + fake_loops[k].v = k; - + if (vndx == i) copy_v3_v3(fake_co[k], center); else copy_v3_v3(fake_co[k], origco[vndx]); } - + BKE_mesh_calc_poly_normal_coords(&fake_poly, fake_loops, (const float(*)[3])fake_co, no); MEM_freeN(fake_loops); @@ -854,7 +854,7 @@ void multiresModifier_base_apply(MultiresModifierData *mmd, Object *ob) copy_v3_v3(push, avg_no); mul_v3_fl(push, dist); add_v3_v3(me->mvert[i].co, push); - + } MEM_freeN(origco); @@ -943,7 +943,7 @@ static void multires_subdivide(MultiresModifierData *mmd, Object *ob, int totlvl ccgSubSurf_updateLevels(ss, lvl, NULL, 0); /* reallocate displacements */ - multires_reallocate_mdisps(me->totloop, mdisps, totlvl); + multires_reallocate_mdisps(me->totloop, mdisps, totlvl); /* compute displacements */ multiresModifier_disp_run(highdm, me, NULL, CALC_DISPLACEMENTS, subGridData, totlvl); @@ -956,7 +956,7 @@ static void multires_subdivide(MultiresModifierData *mmd, Object *ob, int totlvl } else { /* only reallocate, nothing to upsample */ - multires_reallocate_mdisps(me->totloop, mdisps, totlvl); + multires_reallocate_mdisps(me->totloop, mdisps, totlvl); } multires_set_tot_level(ob, mmd, totlvl); @@ -1129,7 +1129,7 @@ static void multiresModifier_disp_run(DerivedMesh *dm, Mesh *me, DerivedMesh *dm int *gridOffset; int i, gridSize, dGridSize, dSkip; int totloop, totpoly; - + /* this happens in the dm made by bmesh_mdisps_space_set */ if (dm2 && CustomData_has_layer(&dm2->loopData, CD_MDISPS)) { mpoly = CustomData_get_layer(&dm2->polyData, CD_MPOLY); @@ -1141,7 +1141,7 @@ static void multiresModifier_disp_run(DerivedMesh *dm, Mesh *me, DerivedMesh *dm totloop = me->totloop; totpoly = me->totpoly; } - + if (!mdisps) { if (op == CALC_DISPLACEMENTS) mdisps = CustomData_add_layer(&me->ldata, CD_MDISPS, CD_DEFAULT, NULL, me->totloop); @@ -1215,7 +1215,7 @@ void multires_modifier_update_mdisps(struct DerivedMesh *dm) if (mdisps) { int lvl = ccgdm->multires.lvl; int totlvl = ccgdm->multires.totlvl; - + if (lvl < totlvl) { DerivedMesh *lowdm, *cddm, *highdm; CCGElem **highGridData, **lowGridData, **subGridData, **gridData, *diffGrid; @@ -1312,7 +1312,7 @@ void multires_modifier_update_hidden(DerivedMesh *dm) if (mdisps) { int i; - + for (i = 0; i < me->totloop; i++) { MDisps *md = &mdisps[i]; BLI_bitmap *gh = grid_hidden[i]; @@ -1326,131 +1326,11 @@ void multires_modifier_update_hidden(DerivedMesh *dm) md->hidden); if (md->hidden) MEM_freeN(md->hidden); - - md->hidden = gh; - } - } - } -} - -void multires_set_space(DerivedMesh *dm, Object *ob, int from, int to) -{ - DerivedMesh *ccgdm = NULL, *subsurf = NULL; - CCGElem **gridData, **subGridData = NULL; - CCGKey key; - MPoly *mpoly = CustomData_get_layer(&dm->polyData, CD_MPOLY); - MDisps *mdisps; - MultiresModifierData *mmd = get_multires_modifier(NULL, ob, 1); - int *gridOffset, totlvl; - int i, k, numGrids, gridSize, dGridSize, dSkip; - - if (!mmd) - return; - - mdisps = CustomData_get_layer(&dm->loopData, CD_MDISPS); - - if (!mdisps) { - goto cleanup; - } - - totlvl = mmd->totlvl; - ccgdm = multires_dm_create_local(ob, dm, totlvl, totlvl, mmd->simple, false); - - subsurf = subsurf_dm_create_local(ob, dm, totlvl, - mmd->simple, mmd->flags & eMultiresModifierFlag_ControlEdges, mmd->flags & eMultiresModifierFlag_PlainUv, 0); - numGrids = subsurf->getNumGrids(subsurf); - gridSize = subsurf->getGridSize(subsurf); - gridData = subsurf->getGridData(subsurf); - subsurf->getGridKey(subsurf, &key); - - subGridData = MEM_calloc_arrayN(numGrids, sizeof(CCGElem *), "subGridData*"); - - for (i = 0; i < numGrids; i++) { - subGridData[i] = MEM_calloc_arrayN(key.elem_size, gridSize * gridSize, "subGridData"); - memcpy(subGridData[i], gridData[i], key.elem_size * gridSize * gridSize); - } - - /* numGrids = ccgdm->dm->getNumGrids((DerivedMesh *)ccgdm); */ /*UNUSED*/ - gridSize = ccgdm->getGridSize((DerivedMesh *)ccgdm); - gridData = ccgdm->getGridData((DerivedMesh *)ccgdm); - gridOffset = ccgdm->getGridOffset((DerivedMesh *)ccgdm); - - dGridSize = multires_side_tot[totlvl]; - dSkip = (dGridSize - 1) / (gridSize - 1); - - k = 0; /*current loop/mdisp index within the mloop array*/ - - /* TODO: Use BLI_task parallel range for that one too? */ - for (i = 0; i < dm->numPolyData; ++i) { - const int numVerts = mpoly[i].totloop; - int S, x, y, gIndex = gridOffset[i]; - - for (S = 0; S < numVerts; ++S, ++gIndex, ++k) { - MDisps *mdisp = &mdisps[mpoly[i].loopstart + S]; - /* CCGElem *grid = gridData[gIndex]; */ /* UNUSED */ - CCGElem *subgrid = subGridData[gIndex]; - float (*dispgrid)[3] = NULL; - - /* when adding new faces in edit mode, need to allocate disps */ - if (!mdisp->disps) { - mdisp->totdisp = gridSize * gridSize; - mdisp->level = totlvl; - mdisp->disps = MEM_calloc_arrayN(mdisp->totdisp, 3 * sizeof(float), "disp in multires_set_space"); - } - - dispgrid = mdisp->disps; - - for (y = 0; y < gridSize; y++) { - for (x = 0; x < gridSize; x++) { - float *data = dispgrid[dGridSize * y * dSkip + x * dSkip]; - float *co = CCG_grid_elem_co(&key, subgrid, x, y); - float mat[3][3], dco[3]; - - /* construct tangent space matrix */ - grid_tangent_matrix(mat, &key, x, y, subgrid); - - /* convert to absolute coordinates in space */ - if (from == MULTIRES_SPACE_TANGENT) { - mul_v3_m3v3(dco, mat, data); - add_v3_v3(dco, co); - } - else if (from == MULTIRES_SPACE_OBJECT) { - add_v3_v3v3(dco, co, data); - } - else if (from == MULTIRES_SPACE_ABSOLUTE) { - copy_v3_v3(dco, data); - } - - /*now, convert to desired displacement type*/ - if (to == MULTIRES_SPACE_TANGENT) { - invert_m3(mat); - - sub_v3_v3(dco, co); - mul_v3_m3v3(data, mat, dco); - } - else if (to == MULTIRES_SPACE_OBJECT) { - sub_v3_v3(dco, co); - mul_v3_m3v3(data, mat, dco); - } - else if (to == MULTIRES_SPACE_ABSOLUTE) { - copy_v3_v3(data, dco); - } - } + md->hidden = gh; } } } - -cleanup: - if (subsurf) { - subsurf->needsFree = 1; - subsurf->release(subsurf); - } - - if (ccgdm) { - ccgdm->needsFree = 1; - ccgdm->release(ccgdm); - } } void multires_stitch_grids(Object *ob) @@ -1545,10 +1425,10 @@ void old_mdisps_bilinear(float out[3], float (*disps)[3], const int st, float u, const int st_max = st - 1; float urat, vrat, uopp; float d[4][3], d2[2][3]; - + if (!disps || isnan(u) || isnan(v)) return; - + if (u < 0) u = 0; else if (u >= st) @@ -1565,7 +1445,7 @@ void old_mdisps_bilinear(float out[3], float (*disps)[3], const int st, float u, if (x2 >= st) x2 = st_max; if (y2 >= st) y2 = st_max; - + urat = u - x; vrat = v - y; uopp = 1 - urat; @@ -1640,7 +1520,7 @@ void multires_load_old_250(Mesh *me) for (i = 0; i < me->totface; i++) if (mdisps[i].totdisp) old_mdisps_convert(&me->mface[i], &mdisps[i]); - + CustomData_add_layer(&me->ldata, CD_MDISPS, CD_CALLOC, NULL, me->totloop); mdisps2 = CustomData_get_layer(&me->ldata, CD_MDISPS); @@ -1649,7 +1529,7 @@ void multires_load_old_250(Mesh *me) for (i = 0; i < me->totface; i++, mf++) { int nvert = mf->v4 ? 4 : 3; int totdisp = mdisps[i].totdisp / nvert; - + for (j = 0; j < nvert; j++, k++) { mdisps2[k].disps = MEM_calloc_arrayN(totdisp, 3 * sizeof(float), "multires disp in conversion"); mdisps2[k].totdisp = totdisp; @@ -1710,11 +1590,11 @@ static void create_old_vert_face_map(ListBase **map, IndexNode **mem, const Mult { int i, j; IndexNode *node = NULL; - + (*map) = MEM_calloc_arrayN(totvert, sizeof(ListBase), "vert face map"); (*mem) = MEM_calloc_arrayN(totface, 4 * sizeof(IndexNode), "vert face map mem"); node = *mem; - + /* Find the users */ for (i = 0; i < totface; ++i) { for (j = 0; j < (mface[i].v[3] ? 4 : 3); ++j, ++node) { @@ -1729,11 +1609,11 @@ static void create_old_vert_edge_map(ListBase **map, IndexNode **mem, const Mult { int i, j; IndexNode *node = NULL; - + (*map) = MEM_calloc_arrayN(totvert, sizeof(ListBase), "vert edge map"); (*mem) = MEM_calloc_arrayN(totedge, 2 * sizeof(IndexNode), "vert edge map mem"); node = *mem; - + /* Find the users */ for (i = 0; i < totedge; ++i) { for (j = 0; j < 2; ++j, ++node) { @@ -1854,7 +1734,7 @@ static void multires_mvert_to_ss(DerivedMesh *dm, MVert *mvert) vd = ccgSubSurf_getFaceCenterData(f); copy_v3_v3(CCG_elem_co(&key, vd), mvert[i].co); i++; - + for (S = 0; S < numVerts; S++) { for (x = 1; x < gridSize - 1; x++, i++) { vd = ccgSubSurf_getFaceGridEdgeData(ss, f, S, x); @@ -2085,7 +1965,7 @@ static void multires_load_old_vcols(Mesh *me) * so we can assume the active vcol layer is the correct one */ if (!(mcol = CustomData_get_layer(&me->fdata, CD_MCOL))) return; - + for (i = 0; i < me->totface; ++i) { for (j = 0; j < 4; ++j) { mcol[i * 4 + j].a = colface[i].col[j].a; @@ -2164,7 +2044,7 @@ void multires_load_old(Object *ob, Mesh *me) /* Add a multires modifier to the object */ md = ob->modifiers.first; while (md && modifierType_getInfo(md->type)->type == eModifierTypeType_OnlyDeform) - md = md->next; + md = md->next; mmd = (MultiresModifierData *)modifier_new(eModifierType_Multires); BLI_insertlinkbefore(&ob->modifiers, md, mmd); diff --git a/source/blender/blenkernel/intern/nla.c b/source/blender/blenkernel/intern/nla.c index b91887e6815..91340997532 100644 --- a/source/blender/blenkernel/intern/nla.c +++ b/source/blender/blenkernel/intern/nla.c @@ -54,9 +54,10 @@ #include "BKE_action.h" #include "BKE_fcurve.h" -#include "BKE_nla.h" #include "BKE_global.h" #include "BKE_library.h" +#include "BKE_main.h" +#include "BKE_nla.h" #ifdef WITH_AUDASPACE # include <AUD_Special.h> @@ -78,31 +79,31 @@ void BKE_nlastrip_free(ListBase *strips, NlaStrip *strip) { NlaStrip *cs, *csn; - + /* sanity checks */ if (strip == NULL) return; - + /* free child-strips */ for (cs = strip->strips.first; cs; cs = csn) { csn = cs->next; BKE_nlastrip_free(&strip->strips, cs); } - + /* remove reference to action */ if (strip->act) id_us_min(&strip->act->id); - + /* free remapping info */ //if (strip->remap) // BKE_animremap_free(); - + /* free own F-Curves */ free_fcurves(&strip->fcurves); - + /* free own F-Modifiers */ free_fmodifiers(&strip->modifiers); - + /* free the strip itself */ if (strips) BLI_freelinkN(strips, strip); @@ -116,17 +117,17 @@ void BKE_nlastrip_free(ListBase *strips, NlaStrip *strip) void BKE_nlatrack_free(ListBase *tracks, NlaTrack *nlt) { NlaStrip *strip, *stripn; - + /* sanity checks */ if (nlt == NULL) return; - + /* free strips */ for (strip = nlt->strips.first; strip; strip = stripn) { stripn = strip->next; BKE_nlastrip_free(&nlt->strips, strip); } - + /* free NLA track itself now */ if (tracks) BLI_freelinkN(tracks, nlt); @@ -140,17 +141,17 @@ void BKE_nlatrack_free(ListBase *tracks, NlaTrack *nlt) void BKE_nla_tracks_free(ListBase *tracks) { NlaTrack *nlt, *nltn; - + /* sanity checks */ if (ELEM(NULL, tracks, tracks->first)) return; - + /* free tracks one by one */ for (nlt = tracks->first; nlt; nlt = nltn) { nltn = nlt->next; BKE_nlatrack_free(tracks, nlt); } - + /* clear the list's pointers to be safe */ BLI_listbase_clear(tracks); } @@ -162,19 +163,19 @@ void BKE_nla_tracks_free(ListBase *tracks) * * \param use_same_action When true, the existing action is used (instead of being duplicated) */ -NlaStrip *BKE_nlastrip_copy(NlaStrip *strip, const bool use_same_action) +NlaStrip *BKE_nlastrip_copy(Main *bmain, NlaStrip *strip, const bool use_same_action) { NlaStrip *strip_d; NlaStrip *cs, *cs_d; - + /* sanity check */ if (strip == NULL) return NULL; - + /* make a copy */ strip_d = MEM_dupallocN(strip); strip_d->next = strip_d->prev = NULL; - + /* handle action */ if (strip_d->act) { if (use_same_action) { @@ -183,104 +184,104 @@ NlaStrip *BKE_nlastrip_copy(NlaStrip *strip, const bool use_same_action) } else { /* use a copy of the action instead (user count shouldn't have changed yet) */ - strip_d->act = BKE_action_copy(G.main, strip_d->act); + strip_d->act = BKE_action_copy(bmain, strip_d->act); } } - + /* copy F-Curves and modifiers */ copy_fcurves(&strip_d->fcurves, &strip->fcurves); copy_fmodifiers(&strip_d->modifiers, &strip->modifiers); - + /* make a copy of all the child-strips, one at a time */ BLI_listbase_clear(&strip_d->strips); - + for (cs = strip->strips.first; cs; cs = cs->next) { - cs_d = BKE_nlastrip_copy(cs, use_same_action); + cs_d = BKE_nlastrip_copy(bmain, cs, use_same_action); BLI_addtail(&strip_d->strips, cs_d); } - + /* return the strip */ return strip_d; } /* Copy NLA Track */ -NlaTrack *BKE_nlatrack_copy(NlaTrack *nlt, const bool use_same_actions) +NlaTrack *BKE_nlatrack_copy(Main *bmain, NlaTrack *nlt, const bool use_same_actions) { NlaStrip *strip, *strip_d; NlaTrack *nlt_d; - + /* sanity check */ if (nlt == NULL) return NULL; - + /* make a copy */ nlt_d = MEM_dupallocN(nlt); nlt_d->next = nlt_d->prev = NULL; - + /* make a copy of all the strips, one at a time */ BLI_listbase_clear(&nlt_d->strips); - + for (strip = nlt->strips.first; strip; strip = strip->next) { - strip_d = BKE_nlastrip_copy(strip, use_same_actions); + strip_d = BKE_nlastrip_copy(bmain, strip, use_same_actions); BLI_addtail(&nlt_d->strips, strip_d); } - + /* return the copy */ return nlt_d; } /* Copy all NLA data */ -void BKE_nla_tracks_copy(ListBase *dst, ListBase *src) +void BKE_nla_tracks_copy(Main *bmain, ListBase *dst, ListBase *src) { NlaTrack *nlt, *nlt_d; - + /* sanity checks */ if (ELEM(NULL, dst, src)) return; - + /* clear out the destination list first for precautions... */ BLI_listbase_clear(dst); - + /* copy each NLA-track, one at a time */ for (nlt = src->first; nlt; nlt = nlt->next) { /* make a copy, and add the copy to the destination list */ // XXX: we need to fix this sometime - nlt_d = BKE_nlatrack_copy(nlt, true); + nlt_d = BKE_nlatrack_copy(bmain, nlt, true); BLI_addtail(dst, nlt_d); } } /* Adding ------------------------------------------- */ -/* Add a NLA Track to the given AnimData +/* Add a NLA Track to the given AnimData * - prev: NLA-Track to add the new one after */ NlaTrack *BKE_nlatrack_add(AnimData *adt, NlaTrack *prev) { NlaTrack *nlt; - + /* sanity checks */ if (adt == NULL) return NULL; - + /* allocate new track */ nlt = MEM_callocN(sizeof(NlaTrack), "NlaTrack"); - + /* set settings requiring the track to not be part of the stack yet */ nlt->flag = NLATRACK_SELECTED; nlt->index = BLI_listbase_count(&adt->nla_tracks); - + /* add track to stack, and make it the active one */ if (prev) BLI_insertlinkafter(&adt->nla_tracks, prev, nlt); else BLI_addtail(&adt->nla_tracks, nlt); BKE_nlatrack_set_active(&adt->nla_tracks, nlt); - + /* must have unique name, but we need to seed this */ strcpy(nlt->name, "NlaTrack"); BLI_uniquename(&adt->nla_tracks, nlt, DATA_("NlaTrack"), '.', offsetof(NlaTrack, name), sizeof(nlt->name)); - + /* return the new track */ return nlt; } @@ -289,15 +290,15 @@ NlaTrack *BKE_nlatrack_add(AnimData *adt, NlaTrack *prev) NlaStrip *BKE_nlastrip_new(bAction *act) { NlaStrip *strip; - + /* sanity checks */ if (act == NULL) return NULL; - + /* allocate new strip */ strip = MEM_callocN(sizeof(NlaStrip), "NlaStrip"); - - /* generic settings + + /* generic settings * - selected flag to highlight this to the user * - (XXX) disabled Auto-Blends, as this was often causing some unwanted effects * - (XXX) synchronization of strip-length in accordance with changes to action-length @@ -305,23 +306,23 @@ NlaStrip *BKE_nlastrip_new(bAction *act) * though this decision is still subject to further review... */ strip->flag = NLASTRIP_FLAG_SELECT; - + /* assign the action reference */ strip->act = act; id_us_plus(&act->id); - - /* determine initial range + + /* determine initial range * - strip length cannot be 0... ever... */ calc_action_range(strip->act, &strip->actstart, &strip->actend, 0); - + strip->start = strip->actstart; strip->end = (IS_EQF(strip->actstart, strip->actend)) ? (strip->actstart + 1.0f) : (strip->actend); - + /* strip should be referenced as-is */ strip->scale = 1.0f; strip->repeat = 1.0f; - + /* return the new strip */ return strip; } @@ -331,28 +332,28 @@ NlaStrip *BKE_nlastack_add_strip(AnimData *adt, bAction *act) { NlaStrip *strip; NlaTrack *nlt; - + /* sanity checks */ if (ELEM(NULL, adt, act)) return NULL; - + /* create a new NLA strip */ strip = BKE_nlastrip_new(act); if (strip == NULL) return NULL; - + /* firstly try adding strip to last track, but if that fails, add to a new track */ if (BKE_nlatrack_add_strip(adt->nla_tracks.last, strip) == 0) { - /* trying to add to the last track failed (no track or no space), + /* trying to add to the last track failed (no track or no space), * so add a new track to the stack, and add to that... */ nlt = BKE_nlatrack_add(adt, NULL); BKE_nlatrack_add_strip(nlt, strip); } - + /* automatically name it too */ BKE_nlastrip_validate_name(adt, strip); - + /* returns the strip added */ return strip; } @@ -361,14 +362,14 @@ NlaStrip *BKE_nlastack_add_strip(AnimData *adt, bAction *act) NlaStrip *BKE_nla_add_soundstrip(Scene *scene, Speaker *speaker) { NlaStrip *strip = MEM_callocN(sizeof(NlaStrip), "NlaSoundStrip"); - + /* if speaker has a sound, set the strip length to the length of the sound, * otherwise default to length of 10 frames */ #ifdef WITH_AUDASPACE if (speaker->sound) { AUD_SoundInfo info = AUD_getInfo(speaker->sound->playback_handle); - + strip->end = (float)ceil((double)info.length * FPS); } else @@ -379,17 +380,17 @@ NlaStrip *BKE_nla_add_soundstrip(Scene *scene, Speaker *speaker) (void)scene; (void)speaker; } - + /* general settings */ strip->type = NLASTRIP_TYPE_SOUND; - + strip->flag = NLASTRIP_FLAG_SELECT; strip->extendmode = NLASTRIP_EXTEND_NOTHING; /* nothing to extend... */ - + /* strip should be referenced as-is */ strip->scale = 1.0f; strip->repeat = 1.0f; - + /* return this strip */ return strip; } @@ -406,19 +407,19 @@ static float nlastrip_get_frame_actionclip(NlaStrip *strip, float cframe, short { float actlength, scale; // float repeat; // UNUSED - + /* get number of repeats */ if (IS_EQF(strip->repeat, 0.0f)) strip->repeat = 1.0f; // repeat = strip->repeat; // UNUSED - + /* scaling */ if (IS_EQF(strip->scale, 0.0f)) strip->scale = 1.0f; scale = fabsf(strip->scale); /* scale must be positive - we've got a special flag for reversing */ - + /* length of referenced action */ actlength = strip->actend - strip->actstart; if (IS_EQF(actlength, 0.0f)) actlength = 1.0f; - + /* reversed = play strip backwards */ if (strip->flag & NLASTRIP_FLAG_REVERSE) { /* FIXME: this won't work right with Graph Editor? */ @@ -430,7 +431,7 @@ static float nlastrip_get_frame_actionclip(NlaStrip *strip, float cframe, short } else { /* if (mode == NLATIME_CONVERT_EVAL) */ if (IS_EQF((float)cframe, strip->end) && IS_EQF(strip->repeat, floorf(strip->repeat))) { - /* this case prevents the motion snapping back to the first frame at the end of the strip + /* this case prevents the motion snapping back to the first frame at the end of the strip * by catching the case where repeats is a whole number, which means that the end of the strip * could also be interpreted as the end of the start of a repeat */ @@ -453,7 +454,7 @@ static float nlastrip_get_frame_actionclip(NlaStrip *strip, float cframe, short } else { /* if (mode == NLATIME_CONVERT_EVAL) */ if (IS_EQF(cframe, strip->end) && IS_EQF(strip->repeat, floorf(strip->repeat))) { - /* this case prevents the motion snapping back to the first frame at the end of the strip + /* this case prevents the motion snapping back to the first frame at the end of the strip * by catching the case where repeats is a whole number, which means that the end of the strip * could also be interpreted as the end of the start of a repeat */ @@ -475,10 +476,10 @@ static float nlastrip_get_frame_actionclip(NlaStrip *strip, float cframe, short static float nlastrip_get_frame_transition(NlaStrip *strip, float cframe, short mode) { float length; - + /* length of strip */ length = strip->end - strip->start; - + /* reversed = play strip backwards */ if (strip->flag & NLASTRIP_FLAG_REVERSE) { if (mode == NLATIME_CONVERT_MAP) @@ -506,7 +507,7 @@ float nlastrip_get_frame(NlaStrip *strip, float cframe, short mode) case NLASTRIP_TYPE_META: /* meta - for now, does the same as transition (is really just an empty container) */ case NLASTRIP_TYPE_TRANSITION: /* transition */ return nlastrip_get_frame_transition(strip, cframe, mode); - + case NLASTRIP_TYPE_CLIP: /* action-clip (default) */ default: return nlastrip_get_frame_actionclip(strip, cframe, mode); @@ -523,15 +524,15 @@ float nlastrip_get_frame(NlaStrip *strip, float cframe, short mode) float BKE_nla_tweakedit_remap(AnimData *adt, float cframe, short mode) { NlaStrip *strip; - - /* sanity checks + + /* sanity checks * - obviously we've got to have some starting data * - when not in tweakmode, the active Action does not have any scaling applied :) * - when in tweakmode, if the no-mapping flag is set, do not map */ if ((adt == NULL) || (adt->flag & ADT_NLA_EDIT_ON) == 0 || (adt->flag & ADT_NLA_EDIT_NOMAP)) return cframe; - + /* if the active-strip info has been stored already, access this, otherwise look this up * and store for (very probable) future usage */ @@ -545,15 +546,15 @@ float BKE_nla_tweakedit_remap(AnimData *adt, float cframe, short mode) adt->actstrip = BKE_nlastrip_find_active(adt->act_track); } strip = adt->actstrip; - - /* sanity checks + + /* sanity checks * - in rare cases, we may not be able to find this strip for some reason (internal error) * - for now, if the user has defined a curve to control the time, this correction cannot be performed * reliably... */ if ((strip == NULL) || (strip->flag & NLASTRIP_FLAG_USR_TIME)) return cframe; - + /* perform the correction now... */ return nlastrip_get_frame(strip, cframe, mode); } @@ -568,7 +569,7 @@ float BKE_nla_tweakedit_remap(AnimData *adt, float cframe, short mode) bool BKE_nlastrips_has_space(ListBase *strips, float start, float end) { NlaStrip *strip; - + /* sanity checks */ if ((strips == NULL) || IS_EQF(start, end)) return false; @@ -576,7 +577,7 @@ bool BKE_nlastrips_has_space(ListBase *strips, float start, float end) puts("BKE_nlastrips_has_space() error... start and end arguments swapped"); SWAP(float, start, end); } - + /* loop over NLA strips checking for any overlaps with this area... */ for (strip = strips->first; strip; strip = strip->next) { /* if start frame of strip is past the target end-frame, that means that @@ -584,43 +585,43 @@ bool BKE_nlastrips_has_space(ListBase *strips, float start, float end) */ if (strip->start >= end) return true; - + /* if the end of the strip is greater than either of the boundaries, the range * must fall within the extents of the strip */ if ((strip->end > start) || (strip->end > end)) return false; } - + /* if we are still here, we haven't encountered any overlapping strips */ return true; } -/* Rearrange the strips in the track so that they are always in order +/* Rearrange the strips in the track so that they are always in order * (usually only needed after a strip has been moved) */ void BKE_nlastrips_sort_strips(ListBase *strips) { ListBase tmp = {NULL, NULL}; NlaStrip *strip, *sstrip, *stripn; - + /* sanity checks */ if (ELEM(NULL, strips, strips->first)) return; - + /* we simply perform insertion sort on this list, since it is assumed that per track, * there are only likely to be at most 5-10 strips */ for (strip = strips->first; strip; strip = stripn) { short not_added = 1; - + stripn = strip->next; - - /* remove this strip from the list, and add it to the new list, searching from the end of - * the list, assuming that the lists are in order + + /* remove this strip from the list, and add it to the new list, searching from the end of + * the list, assuming that the lists are in order */ BLI_remlink(strips, strip); - + for (sstrip = tmp.last; sstrip; sstrip = sstrip->prev) { /* check if add after */ if (sstrip->end <= strip->start) { @@ -629,33 +630,33 @@ void BKE_nlastrips_sort_strips(ListBase *strips) break; } } - + /* add before first? */ if (not_added) BLI_addhead(&tmp, strip); } - + /* reassign the start and end points of the strips */ strips->first = tmp.first; strips->last = tmp.last; } -/* Add the given NLA-Strip to the given list of strips, assuming that it +/* Add the given NLA-Strip to the given list of strips, assuming that it * isn't currently a member of another list */ bool BKE_nlastrips_add_strip(ListBase *strips, NlaStrip *strip) { NlaStrip *ns; bool not_added = true; - + /* sanity checks */ if (ELEM(NULL, strips, strip)) return false; - + /* check if any space to add */ if (BKE_nlastrips_has_space(strips, strip->start, strip->end) == 0) return false; - + /* find the right place to add the strip to the nominated track */ for (ns = strips->first; ns; ns = ns->next) { /* if current strip occurs after the new strip, add it before */ @@ -669,7 +670,7 @@ bool BKE_nlastrips_add_strip(ListBase *strips, NlaStrip *strip) /* just add to the end of the list of the strips then... */ BLI_addtail(strips, strip); } - + /* added... */ return true; } @@ -685,15 +686,15 @@ void BKE_nlastrips_make_metas(ListBase *strips, bool is_temp) { NlaStrip *mstrip = NULL; NlaStrip *strip, *stripn; - + /* sanity checks */ if (ELEM(NULL, strips, strips->first)) return; - + /* group all continuous chains of selected strips into meta-strips */ for (strip = strips->first; strip; strip = stripn) { stripn = strip->next; - + if (strip->flag & NLASTRIP_FLAG_SELECT) { /* if there is an existing meta-strip, add this strip to it, otherwise, create a new one */ if (mstrip == NULL) { @@ -701,25 +702,25 @@ void BKE_nlastrips_make_metas(ListBase *strips, bool is_temp) mstrip = MEM_callocN(sizeof(NlaStrip), "Meta-NlaStrip"); mstrip->type = NLASTRIP_TYPE_META; BLI_insertlinkbefore(strips, strip, mstrip); - + /* set flags */ mstrip->flag = NLASTRIP_FLAG_SELECT; - + /* set temp flag if appropriate (i.e. for transform-type editing) */ if (is_temp) mstrip->flag |= NLASTRIP_FLAG_TEMP_META; - + /* set default repeat/scale values to prevent warnings */ mstrip->repeat = mstrip->scale = 1.0f; - + /* make its start frame be set to the start frame of the current strip */ mstrip->start = strip->start; } - + /* remove the selected strips from the track, and add to the meta */ BLI_remlink(strips, strip); BLI_addtail(&mstrip->strips, strip); - + /* expand the meta's dimensions to include the newly added strip- i.e. its last frame */ mstrip->end = strip->end; } @@ -736,11 +737,11 @@ void BKE_nlastrips_make_metas(ListBase *strips, bool is_temp) void BKE_nlastrips_clear_metastrip(ListBase *strips, NlaStrip *strip) { NlaStrip *cs, *csn; - + /* sanity check */ if (ELEM(NULL, strips, strip)) return; - + /* move each one of the meta-strip's children before the meta-strip * in the list of strips after unlinking them from the meta-strip */ @@ -749,7 +750,7 @@ void BKE_nlastrips_clear_metastrip(ListBase *strips, NlaStrip *strip) BLI_remlink(&strip->strips, cs); BLI_insertlinkbefore(strips, strip, cs); } - + /* free the meta-strip now */ BKE_nlastrip_free(strips, strip); } @@ -761,15 +762,15 @@ void BKE_nlastrips_clear_metastrip(ListBase *strips, NlaStrip *strip) void BKE_nlastrips_clear_metas(ListBase *strips, bool only_sel, bool only_temp) { NlaStrip *strip, *stripn; - + /* sanity checks */ if (ELEM(NULL, strips, strips->first)) return; - + /* remove meta-strips fitting the criteria of the arguments */ for (strip = strips->first; strip; strip = stripn) { stripn = strip->next; - + /* check if strip is a meta-strip */ if (strip->type == NLASTRIP_TYPE_META) { /* if check if selection and 'temporary-only' considerations are met */ @@ -790,37 +791,37 @@ bool BKE_nlameta_add_strip(NlaStrip *mstrip, NlaStrip *strip) /* sanity checks */ if (ELEM(NULL, mstrip, strip)) return false; - + /* firstly, check if the meta-strip has space for this */ if (BKE_nlastrips_has_space(&mstrip->strips, strip->start, strip->end) == 0) return false; - + /* check if this would need to be added to the ends of the meta, * and subsequently, if the neighboring strips allow us enough room */ if (strip->start < mstrip->start) { - /* check if strip to the left (if it exists) ends before the - * start of the strip we're trying to add + /* check if strip to the left (if it exists) ends before the + * start of the strip we're trying to add */ if ((mstrip->prev == NULL) || (mstrip->prev->end <= strip->start)) { /* add strip to start of meta's list, and expand dimensions */ BLI_addhead(&mstrip->strips, strip); mstrip->start = strip->start; - + return true; } else /* failed... no room before */ return false; } else if (strip->end > mstrip->end) { - /* check if strip to the right (if it exists) starts before the - * end of the strip we're trying to add + /* check if strip to the right (if it exists) starts before the + * end of the strip we're trying to add */ if ((mstrip->next == NULL) || (mstrip->next->start >= strip->end)) { /* add strip to end of meta's list, and expand dimensions */ BLI_addtail(&mstrip->strips, strip); mstrip->end = strip->end; - + return true; } else /* failed... no room after */ @@ -832,7 +833,7 @@ bool BKE_nlameta_add_strip(NlaStrip *mstrip, NlaStrip *strip) } } -/* Adjust the settings of NLA-Strips contained within a Meta-Strip (recursively), +/* Adjust the settings of NLA-Strips contained within a Meta-Strip (recursively), * until the Meta-Strips children all fit within the Meta-Strip's new dimensions */ void BKE_nlameta_flush_transforms(NlaStrip *mstrip) @@ -841,8 +842,8 @@ void BKE_nlameta_flush_transforms(NlaStrip *mstrip) float oStart, oEnd, offset; float oLen, nLen; short scaleChanged = 0; - - /* sanity checks + + /* sanity checks * - strip must exist * - strip must be a meta-strip with some contents */ @@ -850,37 +851,37 @@ void BKE_nlameta_flush_transforms(NlaStrip *mstrip) return; if (mstrip->type != NLASTRIP_TYPE_META) return; - + /* get the original start/end points, and calculate the start-frame offset - * - these are simply the start/end frames of the child strips, + * - these are simply the start/end frames of the child strips, * since we assume they weren't transformed yet */ oStart = ((NlaStrip *)mstrip->strips.first)->start; oEnd = ((NlaStrip *)mstrip->strips.last)->end; offset = mstrip->start - oStart; - + /* optimization: * don't flush if nothing changed yet * TODO: maybe we need a flag to say always flush? */ if (IS_EQF(oStart, mstrip->start) && IS_EQF(oEnd, mstrip->end)) return; - + /* check if scale changed */ oLen = oEnd - oStart; nLen = mstrip->end - mstrip->start; if (IS_EQF(nLen, oLen) == 0) scaleChanged = 1; - + /* for each child-strip, calculate new start/end points based on this new info */ for (strip = mstrip->strips.first; strip; strip = strip->next) { if (scaleChanged) { float p1, p2; - + /* compute positions of endpoints relative to old extents of strip */ p1 = (strip->start - oStart) / oLen; p2 = (strip->end - oStart) / oLen; - + /* apply new strip endpoints using the proportions, then wait for second pass to flush scale properly */ strip->start = (p1 * nLen) + mstrip->start; strip->end = (p2 * nLen) + mstrip->start; @@ -891,20 +892,20 @@ void BKE_nlameta_flush_transforms(NlaStrip *mstrip) strip->end += offset; } } - + /* apply a second pass over child strips, to finish up unfinished business */ for (strip = mstrip->strips.first; strip; strip = strip->next) { /* only if scale changed, need to perform RNA updates */ if (scaleChanged) { PointerRNA ptr; - + /* use RNA updates to compute scale properly */ RNA_pointer_create(NULL, &RNA_NlaStrip, strip, &ptr); - + RNA_float_set(&ptr, "frame_start", strip->start); RNA_float_set(&ptr, "frame_end", strip->end); } - + /* finally, make sure the strip's children (if it is a meta-itself), get updated */ BKE_nlameta_flush_transforms(strip); } @@ -916,17 +917,17 @@ void BKE_nlameta_flush_transforms(NlaStrip *mstrip) NlaTrack *BKE_nlatrack_find_active(ListBase *tracks) { NlaTrack *nlt; - + /* sanity check */ if (ELEM(NULL, tracks, tracks->first)) return NULL; - + /* try to find the first active track */ for (nlt = tracks->first; nlt; nlt = nlt->next) { if (nlt->flag & NLATRACK_ACTIVE) return nlt; } - + /* none found */ return NULL; } @@ -939,11 +940,11 @@ NlaTrack *BKE_nlatrack_find_active(ListBase *tracks) NlaTrack *BKE_nlatrack_find_tweaked(AnimData *adt) { NlaTrack *nlt; - + /* sanity check */ if (adt == NULL) return NULL; - + /* Since the track itself gets disabled, we want the first disabled... */ for (nlt = adt->nla_tracks.first; nlt; nlt = nlt->next) { if (nlt->flag & (NLATRACK_ACTIVE | NLATRACK_DISABLED)) { @@ -953,13 +954,13 @@ NlaTrack *BKE_nlatrack_find_tweaked(AnimData *adt) } else if (G.debug & G_DEBUG) { printf("%s: Active strip (%p, %s) not in NLA track found (%p, %s)\n", - __func__, + __func__, adt->actstrip, (adt->actstrip) ? adt->actstrip->name : "<None>", nlt, nlt->name); } } } - + /* Not found! */ return NULL; } @@ -970,22 +971,22 @@ NlaTrack *BKE_nlatrack_find_tweaked(AnimData *adt) void BKE_nlatrack_solo_toggle(AnimData *adt, NlaTrack *nlt) { NlaTrack *nt; - + /* sanity check */ if (ELEM(NULL, adt, adt->nla_tracks.first)) return; - + /* firstly, make sure 'solo' flag for all tracks is disabled */ for (nt = adt->nla_tracks.first; nt; nt = nt->next) { if (nt != nlt) nt->flag &= ~NLATRACK_SOLO; } - + /* now, enable 'solo' for the given track if appropriate */ if (nlt) { /* toggle solo status */ nlt->flag ^= NLATRACK_SOLO; - + /* set or clear solo-status on AnimData */ if (nlt->flag & NLATRACK_SOLO) adt->flag |= ADT_NLA_SOLO_TRACK; @@ -996,21 +997,21 @@ void BKE_nlatrack_solo_toggle(AnimData *adt, NlaTrack *nlt) adt->flag &= ~ADT_NLA_SOLO_TRACK; } -/* Make the given NLA-track the active one for the given stack. If no track is provided, +/* Make the given NLA-track the active one for the given stack. If no track is provided, * this function can be used to simply deactivate all the NLA tracks in the given stack too. */ void BKE_nlatrack_set_active(ListBase *tracks, NlaTrack *nlt_a) { NlaTrack *nlt; - + /* sanity check */ if (ELEM(NULL, tracks, tracks->first)) return; - + /* deactive all the rest */ for (nlt = tracks->first; nlt; nlt = nlt->next) nlt->flag &= ~NLATRACK_ACTIVE; - + /* set the given one as the active one */ if (nlt_a) nlt_a->flag |= NLATRACK_ACTIVE; @@ -1019,24 +1020,24 @@ void BKE_nlatrack_set_active(ListBase *tracks, NlaTrack *nlt_a) /* Check if there is any space in the given track to add a strip of the given length */ bool BKE_nlatrack_has_space(NlaTrack *nlt, float start, float end) { - /* sanity checks + /* sanity checks * - track must exist * - track must be editable * - bounds cannot be equal (0-length is nasty) */ if ((nlt == NULL) || (nlt->flag & NLATRACK_PROTECTED) || IS_EQF(start, end)) return false; - + if (start > end) { puts("BKE_nlatrack_has_space() error... start and end arguments swapped"); SWAP(float, start, end); } - + /* check if there's any space left in the track for a strip of the given length */ return BKE_nlastrips_has_space(&nlt->strips, start, end); } -/* Rearrange the strips in the track so that they are always in order +/* Rearrange the strips in the track so that they are always in order * (usually only needed after a strip has been moved) */ void BKE_nlatrack_sort_strips(NlaTrack *nlt) @@ -1044,12 +1045,12 @@ void BKE_nlatrack_sort_strips(NlaTrack *nlt) /* sanity checks */ if (ELEM(NULL, nlt, nlt->strips.first)) return; - + /* sort the strips with a more generic function */ BKE_nlastrips_sort_strips(&nlt->strips); } -/* Add the given NLA-Strip to the given NLA-Track, assuming that it +/* Add the given NLA-Strip to the given NLA-Track, assuming that it * isn't currently attached to another one */ bool BKE_nlatrack_add_strip(NlaTrack *nlt, NlaStrip *strip) @@ -1057,11 +1058,11 @@ bool BKE_nlatrack_add_strip(NlaTrack *nlt, NlaStrip *strip) /* sanity checks */ if (ELEM(NULL, nlt, strip)) return false; - + /* do not allow adding strips if this track is locked */ if (nlt->flag & NLATRACK_PROTECTED) return false; - + /* try to add the strip to the track using a more generic function */ return BKE_nlastrips_add_strip(&nlt->strips, strip); } @@ -1072,25 +1073,25 @@ bool BKE_nlatrack_add_strip(NlaTrack *nlt, NlaStrip *strip) bool BKE_nlatrack_get_bounds(NlaTrack *nlt, float bounds[2]) { NlaStrip *strip; - + /* initialize bounds */ if (bounds) bounds[0] = bounds[1] = 0.0f; else return false; - + /* sanity checks */ if (ELEM(NULL, nlt, nlt->strips.first)) return false; - + /* lower bound is first strip's start frame */ strip = nlt->strips.first; bounds[0] = strip->start; - + /* upper bound is last strip's end frame */ strip = nlt->strips.last; bounds[1] = strip->end; - + /* done */ return true; } @@ -1101,17 +1102,17 @@ bool BKE_nlatrack_get_bounds(NlaTrack *nlt, float bounds[2]) NlaStrip *BKE_nlastrip_find_active(NlaTrack *nlt) { NlaStrip *strip; - + /* sanity check */ if (ELEM(NULL, nlt, nlt->strips.first)) return NULL; - + /* try to find the first active strip */ for (strip = nlt->strips.first; strip; strip = strip->next) { if (strip->flag & NLASTRIP_FLAG_ACTIVE) return strip; } - + /* none found */ return NULL; } @@ -1121,11 +1122,11 @@ void BKE_nlastrip_set_active(AnimData *adt, NlaStrip *strip) { NlaTrack *nlt; NlaStrip *nls; - + /* sanity checks */ if (adt == NULL) return; - + /* loop over tracks, deactivating*/ for (nlt = adt->nla_tracks.first; nlt; nlt = nlt->next) { for (nls = nlt->strips.first; nls; nls = nls->next) { @@ -1143,11 +1144,11 @@ bool BKE_nlastrip_within_bounds(NlaStrip *strip, float min, float max) { const float stripLen = (strip) ? strip->end - strip->start : 0.0f; const float boundsLen = fabsf(max - min); - + /* sanity checks */ if ((strip == NULL) || IS_EQF(stripLen, 0.0f) || IS_EQF(boundsLen, 0.0f)) return false; - + /* only ok if at least part of the strip is within the bounding window * - first 2 cases cover when the strip length is less than the bounding area * - second 2 cases cover when the strip length is greater than the bounding area @@ -1164,7 +1165,7 @@ bool BKE_nlastrip_within_bounds(NlaStrip *strip, float min, float max) { return false; } - + /* should be ok! */ return true; } @@ -1177,7 +1178,7 @@ static void nlastrip_fix_resize_overlaps(NlaStrip *strip) if (strip->next) { NlaStrip *nls = strip->next; float offset = 0.0f; - + if (nls->type == NLASTRIP_TYPE_TRANSITION) { /* transition strips should grow/shrink to accomodate the resized strip, * but if the strip's bounds now exceed the transition, we're forced to @@ -1197,7 +1198,7 @@ static void nlastrip_fix_resize_overlaps(NlaStrip *strip) */ nls->start = nls->end - 1.0f; offset = ceilf(strip->end - nls->start); /* XXX: review whether preventing fractionals is good here... */ - + /* apply necessary offset to ensure that the strip has enough space */ for (; nls; nls = nls->next) { nls->start += offset; @@ -1210,7 +1211,7 @@ static void nlastrip_fix_resize_overlaps(NlaStrip *strip) * otherwise it will be very hard to get rid of later */ offset = ceilf(strip->end - nls->start); - + /* apply to times of all strips in this direction */ for (; nls; nls = nls->next) { nls->start += offset; @@ -1218,13 +1219,13 @@ static void nlastrip_fix_resize_overlaps(NlaStrip *strip) } } } - + /* previous strips - same routine as before */ /* NOTE: when strip bounds are recalculated, this is not considered! */ if (strip->prev) { NlaStrip *nls = strip->prev; float offset = 0.0f; - + if (nls->type == NLASTRIP_TYPE_TRANSITION) { /* transition strips should grow/shrink to accomodate the resized strip, * but if the strip's bounds now exceed the transition, we're forced to @@ -1244,7 +1245,7 @@ static void nlastrip_fix_resize_overlaps(NlaStrip *strip) */ nls->end = nls->start + 1.0f; offset = ceilf(nls->end - strip->start); /* XXX: review whether preventing fractionals is good here... */ - + /* apply necessary offset to ensure that the strip has enough space */ for (; nls; nls = nls->next) { nls->start -= offset; @@ -1257,7 +1258,7 @@ static void nlastrip_fix_resize_overlaps(NlaStrip *strip) * otherwise it will be very hard to get rid of later */ offset = ceilf(nls->end - strip->start); - + /* apply to times of all strips in this direction */ for (; nls; nls = nls->prev) { nls->start -= offset; @@ -1273,24 +1274,24 @@ static void nlastrip_fix_resize_overlaps(NlaStrip *strip) void BKE_nlastrip_recalculate_bounds(NlaStrip *strip) { float actlen, mapping; - + /* sanity checks * - must have a strip * - can only be done for action clips */ if ((strip == NULL) || (strip->type != NLASTRIP_TYPE_CLIP)) return; - + /* calculate new length factors */ actlen = strip->actend - strip->actstart; if (IS_EQF(actlen, 0.0f)) actlen = 1.0f; - + mapping = strip->scale * strip->repeat; - + /* adjust endpoint of strip in response to this */ if (IS_EQF(mapping, 0.0f) == 0) strip->end = (actlen * mapping) + strip->start; - + /* make sure we don't overlap our neighbors */ nlastrip_fix_resize_overlaps(strip); } @@ -1301,15 +1302,15 @@ static bool nlastrip_is_first(AnimData *adt, NlaStrip *strip) { NlaTrack *nlt; NlaStrip *ns; - + /* sanity checks */ if (ELEM(NULL, adt, strip)) return false; - + /* check if strip has any strips before it */ if (strip->prev) return false; - + /* check other tracks to see if they have a strip that's earlier */ /* TODO: or should we check that the strip's track is also the first? */ for (nlt = adt->nla_tracks.first; nlt; nlt = nlt->next) { @@ -1320,7 +1321,7 @@ static bool nlastrip_is_first(AnimData *adt, NlaStrip *strip) return false; } } - + /* should be first now */ return true; } @@ -1331,17 +1332,17 @@ static bool nlastrip_is_first(AnimData *adt, NlaStrip *strip) bool BKE_nlatrack_has_animated_strips(NlaTrack *nlt) { NlaStrip *strip; - + /* sanity checks */ if (ELEM(NULL, nlt, nlt->strips.first)) return false; - + /* check each strip for F-Curves only (don't care about whether the flags are set) */ for (strip = nlt->strips.first; strip; strip = strip->next) { if (strip->fcurves.first) return true; } - + /* none found */ return false; } @@ -1350,17 +1351,17 @@ bool BKE_nlatrack_has_animated_strips(NlaTrack *nlt) bool BKE_nlatracks_have_animated_strips(ListBase *tracks) { NlaTrack *nlt; - + /* sanity checks */ if (ELEM(NULL, tracks, tracks->first)) return false; - + /* check each track, stopping on the first hit */ for (nlt = tracks->first; nlt; nlt = nlt->next) { if (BKE_nlatrack_has_animated_strips(nlt)) return true; } - + /* none found */ return false; } @@ -1369,56 +1370,56 @@ bool BKE_nlatracks_have_animated_strips(ListBase *tracks) void BKE_nlastrip_validate_fcurves(NlaStrip *strip) { FCurve *fcu; - + /* sanity checks */ if (strip == NULL) return; - + /* if controlling influence... */ if (strip->flag & NLASTRIP_FLAG_USR_INFLUENCE) { /* try to get F-Curve */ fcu = list_find_fcurve(&strip->fcurves, "influence", 0); - + /* add one if not found */ if (fcu == NULL) { /* make new F-Curve */ fcu = MEM_callocN(sizeof(FCurve), "NlaStrip FCurve"); BLI_addtail(&strip->fcurves, fcu); - + /* set default flags */ fcu->flag = (FCURVE_VISIBLE | FCURVE_SELECTED); fcu->auto_smoothing = FCURVE_SMOOTH_CONT_ACCEL; - + /* store path - make copy, and store that */ fcu->rna_path = BLI_strdupn("influence", 9); - + /* insert keyframe to ensure current value stays on first refresh */ fcu->bezt = MEM_callocN(sizeof(BezTriple), "nlastrip influence bezt"); fcu->totvert = 1; - + fcu->bezt->vec[1][0] = strip->start; fcu->bezt->vec[1][1] = strip->influence; } } - + /* if controlling time... */ if (strip->flag & NLASTRIP_FLAG_USR_TIME) { /* try to get F-Curve */ fcu = list_find_fcurve(&strip->fcurves, "strip_time", 0); - + /* add one if not found */ if (fcu == NULL) { /* make new F-Curve */ fcu = MEM_callocN(sizeof(FCurve), "NlaStrip FCurve"); BLI_addtail(&strip->fcurves, fcu); - + /* set default flags */ fcu->flag = (FCURVE_VISIBLE | FCURVE_SELECTED); fcu->auto_smoothing = FCURVE_SMOOTH_CONT_ACCEL; - + /* store path - make copy, and store that */ fcu->rna_path = BLI_strdupn("strip_time", 10); - + /* TODO: insert a few keyframes to ensure default behavior? */ } } @@ -1432,28 +1433,28 @@ bool BKE_nlastrip_has_curves_for_property(const PointerRNA *ptr, const PropertyR /* sanity checks */ if (ELEM(NULL, ptr, prop)) return false; - + /* 1) Must be NLA strip */ if (ptr->type == &RNA_NlaStrip) { /* 2) Must be one of the predefined properties */ - static PropertyRNA *prop_influence = NULL; + static PropertyRNA *prop_influence = NULL; static PropertyRNA *prop_time = NULL; static bool needs_init = true; - + /* Init the properties on first use */ if (needs_init) { prop_influence = RNA_struct_type_find_property(&RNA_NlaStrip, "influence"); prop_time = RNA_struct_type_find_property(&RNA_NlaStrip, "strip_time"); - + needs_init = false; } - + /* Check if match */ if (ELEM(prop, prop_influence, prop_time)) { return true; } } - + /* No criteria met */ return false; } @@ -1465,7 +1466,7 @@ static bool nla_editbone_name_check(void *arg, const char *name) return BLI_ghash_haskey((GHash *)arg, (const void *)name); } -/* Find (and set) a unique name for a strip from the whole AnimData block +/* Find (and set) a unique name for a strip from the whole AnimData block * Uses a similar method to the BLI method, but is implemented differently * as we need to ensure that the name is unique over several lists of tracks, * not just a single track. @@ -1475,11 +1476,11 @@ void BKE_nlastrip_validate_name(AnimData *adt, NlaStrip *strip) GHash *gh; NlaStrip *tstrip; NlaTrack *nlt; - + /* sanity checks */ if (ELEM(NULL, adt, strip)) return; - + /* give strip a default name if none already */ if (strip->name[0] == 0) { switch (strip->type) { @@ -1497,25 +1498,25 @@ void BKE_nlastrip_validate_name(AnimData *adt, NlaStrip *strip) break; } } - - /* build a hash-table of all the strips in the tracks + + /* build a hash-table of all the strips in the tracks * - this is easier than iterating over all the tracks+strips hierarchy every time * (and probably faster) */ gh = BLI_ghash_str_new("nlastrip_validate_name gh"); - + for (nlt = adt->nla_tracks.first; nlt; nlt = nlt->next) { for (tstrip = nlt->strips.first; tstrip; tstrip = tstrip->next) { /* don't add the strip of interest */ - if (tstrip == strip) + if (tstrip == strip) continue; - + /* use the name of the strip as the key, and the strip as the value, since we're mostly interested in the keys */ BLI_ghash_insert(gh, tstrip->name, tstrip); } } - - /* if the hash-table has a match for this name, try other names... + + /* if the hash-table has a match for this name, try other names... * - in an extreme case, it might not be able to find a name, but then everything else in Blender would fail too :) */ BLI_uniquename_cb(nla_editbone_name_check, (void *)gh, DATA_("NlaStrip"), '.', strip->name, sizeof(strip->name)); @@ -1526,7 +1527,7 @@ void BKE_nlastrip_validate_name(AnimData *adt, NlaStrip *strip) /* ---- */ -/* Get strips which overlap the given one at the start/end of its range +/* Get strips which overlap the given one at the start/end of its range * - strip: strip that we're finding overlaps for * - track: nla-track that the overlapping strips should be found from * - start, end: frames for the offending endpoints @@ -1534,9 +1535,9 @@ void BKE_nlastrip_validate_name(AnimData *adt, NlaStrip *strip) static void nlastrip_get_endpoint_overlaps(NlaStrip *strip, NlaTrack *track, float **start, float **end) { NlaStrip *nls; - + /* find strips that overlap over the start/end of the given strip, - * but which don't cover the entire length + * but which don't cover the entire length */ /* TODO: this scheme could get quite slow for doing this on many strips... */ for (nls = track->strips.first; nls; nls = nls->next) { @@ -1546,13 +1547,13 @@ static void nlastrip_get_endpoint_overlaps(NlaStrip *strip, NlaTrack *track, flo *end = NULL; return; } - + /* check if strip doesn't even occur anywhere near... */ if (nls->end < strip->start) continue; /* skip checking this strip... not worthy of mention */ if (nls->start > strip->end) return; /* the range we're after has already passed */ - + /* if this strip is not part of an island of continuous strips, it can be used * - this check needs to be done for each end of the strip we try and use... */ @@ -1572,7 +1573,7 @@ static void BKE_nlastrip_validate_autoblends(NlaTrack *nlt, NlaStrip *nls) { float *ps = NULL, *pe = NULL; float *ns = NULL, *ne = NULL; - + /* sanity checks */ if (ELEM(NULL, nls, nlt)) return; @@ -1580,16 +1581,16 @@ static void BKE_nlastrip_validate_autoblends(NlaTrack *nlt, NlaStrip *nls) return; if ((nls->flag & NLASTRIP_FLAG_AUTO_BLENDS) == 0) return; - + /* get test ranges */ if (nlt->prev) nlastrip_get_endpoint_overlaps(nls, nlt->prev, &ps, &pe); if (nlt->next) nlastrip_get_endpoint_overlaps(nls, nlt->next, &ns, &ne); - - /* set overlaps for this strip - * - don't use the values obtained though if the end in question - * is directly followed/preceded by another strip, forming an + + /* set overlaps for this strip + * - don't use the values obtained though if the end in question + * is directly followed/preceded by another strip, forming an * 'island' of continuous strips */ if ((ps || ns) && ((nls->prev == NULL) || IS_EQF(nls->prev->end, nls->start) == 0)) { @@ -1601,7 +1602,7 @@ static void BKE_nlastrip_validate_autoblends(NlaTrack *nlt, NlaStrip *nls) } else /* no overlap allowed/needed */ nls->blendin = 0.0f; - + if ((pe || ne) && ((nls->next == NULL) || IS_EQF(nls->next->start, nls->end) == 0)) { /* end overlaps - pick the largest overlap */ if ( ((pe && ne) && (*pe > *ne)) || (pe) ) @@ -1618,33 +1619,33 @@ void BKE_nla_validate_state(AnimData *adt) { NlaStrip *strip, *fstrip = NULL; NlaTrack *nlt; - + /* sanity checks */ if (ELEM(NULL, adt, adt->nla_tracks.first)) return; - + /* adjust blending values for auto-blending, and also do an initial pass to find the earliest strip */ for (nlt = adt->nla_tracks.first; nlt; nlt = nlt->next) { for (strip = nlt->strips.first; strip; strip = strip->next) { /* auto-blending first */ BKE_nlastrip_validate_autoblends(nlt, strip); - + /* extend mode - find first strip */ if ((fstrip == NULL) || (strip->start < fstrip->start)) fstrip = strip; } } - + /* second pass over the strips to adjust the extend-mode to fix any problems */ for (nlt = adt->nla_tracks.first; nlt; nlt = nlt->next) { for (strip = nlt->strips.first; strip; strip = strip->next) { - /* apart from 'nothing' option which user has to explicitly choose, we don't really know if + /* apart from 'nothing' option which user has to explicitly choose, we don't really know if * we should be overwriting the extend setting (but assume that's what the user wanted) */ /* TODO: 1 solution is to tie this in with auto-blending... */ if (strip->extendmode != NLASTRIP_EXTEND_NOTHING) { /* 1) First strip must be set to extend hold, otherwise, stuff before acts dodgy - * 2) Only overwrite extend mode if *not* changing it will most probably result in + * 2) Only overwrite extend mode if *not* changing it will most probably result in * occlusion problems, which will occur if... * - blendmode = REPLACE * - all channels the same (this is fiddly to test, so is currently assumed) @@ -1675,7 +1676,7 @@ bool BKE_nla_action_is_stashed(AnimData *adt, bAction *act) { NlaTrack *nlt; NlaStrip *strip; - + for (nlt = adt->nla_tracks.first; nlt; nlt = nlt->next) { if (strstr(nlt->name, STASH_TRACK_NAME)) { for (strip = nlt->strips.first; strip; strip = strip->next) { @@ -1684,7 +1685,7 @@ bool BKE_nla_action_is_stashed(AnimData *adt, bAction *act) } } } - + return false; } @@ -1696,60 +1697,60 @@ bool BKE_nla_action_stash(AnimData *adt) NlaTrack *prev_track = NULL; NlaTrack *nlt; NlaStrip *strip; - + /* sanity check */ if (ELEM(NULL, adt, adt->action)) { printf("%s: Invalid argument - %p %p\n", __func__, adt, adt->action); return false; } - + /* do not add if it is already stashed */ if (BKE_nla_action_is_stashed(adt, adt->action)) return false; - + /* create a new track, and add this immediately above the previous stashing track */ for (prev_track = adt->nla_tracks.last; prev_track; prev_track = prev_track->prev) { if (strstr(prev_track->name, STASH_TRACK_NAME)) { break; } } - + nlt = BKE_nlatrack_add(adt, prev_track); BLI_assert(nlt != NULL); - + /* we need to ensure that if there wasn't any previous instance, it must go to tbe bottom of the stack */ if (prev_track == NULL) { BLI_remlink(&adt->nla_tracks, nlt); BLI_addhead(&adt->nla_tracks, nlt); } - + BLI_strncpy(nlt->name, STASH_TRACK_NAME, sizeof(nlt->name)); BLI_uniquename(&adt->nla_tracks, nlt, STASH_TRACK_NAME, '.', offsetof(NlaTrack, name), sizeof(nlt->name)); - + /* add the action as a strip in this new track * NOTE: a new user is created here */ strip = BKE_nlastrip_new(adt->action); BLI_assert(strip != NULL); - + BKE_nlatrack_add_strip(nlt, strip); BKE_nlastrip_validate_name(adt, strip); - + /* mark the stash track and strip so that they doesn't disturb the stack animation, * and are unlikely to draw attention to itself (or be accidentally bumped around) - * + * * NOTE: this must be done *after* adding the strip to the track, or else * the strip locking will prevent the strip from getting added */ nlt->flag = (NLATRACK_MUTED | NLATRACK_PROTECTED); strip->flag &= ~(NLASTRIP_FLAG_SELECT | NLASTRIP_FLAG_ACTIVE); - + /* also mark the strip for auto syncing the length, so that the strips accurately * reflect the length of the action * XXX: we could do with some extra flags here to prevent repeats/scaling options from working! */ strip->flag |= NLASTRIP_FLAG_SYNC_LENGTH; - + /* succeeded */ return true; } @@ -1766,7 +1767,7 @@ void BKE_nla_action_pushdown(AnimData *adt) { NlaStrip *strip; const bool is_first = (adt) && (adt->nla_tracks.first == NULL); - + /* sanity checks */ /* TODO: need to report the error for this */ if (ELEM(NULL, adt, adt->action)) @@ -1780,16 +1781,16 @@ void BKE_nla_action_pushdown(AnimData *adt) printf("BKE_nla_action_pushdown(): action has no data\n"); return; } - + /* add a new NLA strip to the track, which references the active action */ strip = BKE_nlastack_add_strip(adt, adt->action); - + /* do other necessary work on strip */ if (strip) { /* clear reference to action now that we've pushed it onto the stack */ id_us_min(&adt->action->id); adt->action = NULL; - + /* copy current "action blending" settings from adt to the strip, * as it was keyframed with these settings, so omitting them will * change the effect [T54233] @@ -1800,7 +1801,7 @@ void BKE_nla_action_pushdown(AnimData *adt) strip->blendmode = adt->act_blendmode; strip->influence = adt->act_influence; strip->extendmode = adt->act_extendmode; - + if (adt->act_influence < 1.0f) { /* enable "user-controlled" influence (which will insert a default keyframe) * so that the influence doesn't get lost on the new update @@ -1815,7 +1816,7 @@ void BKE_nla_action_pushdown(AnimData *adt) BKE_nlastrip_validate_fcurves(strip); } } - + /* if the strip is the first one in the track it lives in, check if there * are strips in any other tracks that may be before this, and set the extend * mode accordingly @@ -1828,7 +1829,7 @@ void BKE_nla_action_pushdown(AnimData *adt) if (strip->extendmode == NLASTRIP_EXTEND_HOLD) strip->extendmode = NLASTRIP_EXTEND_HOLD_FORWARD; } - + /* make strip the active one... */ BKE_nlastrip_set_active(adt, strip); } @@ -1841,17 +1842,17 @@ bool BKE_nla_tweakmode_enter(AnimData *adt) { NlaTrack *nlt, *activeTrack = NULL; NlaStrip *strip, *activeStrip = NULL; - + /* verify that data is valid */ if (ELEM(NULL, adt, adt->nla_tracks.first)) return false; - - /* if block is already in tweakmode, just leave, but we should report + + /* if block is already in tweakmode, just leave, but we should report * that this block is in tweakmode (as our returncode) */ if (adt->flag & ADT_NLA_EDIT_ON) return true; - + /* go over the tracks, finding the active one, and its active strip * - if we cannot find both, then there's nothing to do */ @@ -1860,16 +1861,16 @@ bool BKE_nla_tweakmode_enter(AnimData *adt) if (nlt->flag & NLATRACK_ACTIVE) { /* store reference to this active track */ activeTrack = nlt; - + /* now try to find active strip */ activeStrip = BKE_nlastrip_find_active(nlt); break; } } - - /* There are situations where we may have multiple strips selected and we want to enter tweakmode on all - * of those at once. Usually in those cases, it will usually just be a single strip per AnimData. - * In such cases, compromise and take the last selected track and/or last selected strip [#28468] + + /* There are situations where we may have multiple strips selected and we want to enter tweakmode on all + * of those at once. Usually in those cases, it will usually just be a single strip per AnimData. + * In such cases, compromise and take the last selected track and/or last selected strip [#28468] */ if (activeTrack == NULL) { /* try last selected track for active strip */ @@ -1877,7 +1878,7 @@ bool BKE_nla_tweakmode_enter(AnimData *adt) if (nlt->flag & NLATRACK_SELECTED) { /* assume this is the active track */ activeTrack = nlt; - + /* try to find active strip */ activeStrip = BKE_nlastrip_find_active(nlt); break; @@ -1893,7 +1894,7 @@ bool BKE_nla_tweakmode_enter(AnimData *adt) } } } - + if (ELEM(NULL, activeTrack, activeStrip, activeStrip->act)) { if (G.debug & G_DEBUG) { printf("NLA tweakmode enter - neither active requirement found\n"); @@ -1901,8 +1902,8 @@ bool BKE_nla_tweakmode_enter(AnimData *adt) } return false; } - - /* go over all the tracks up to the active one, tagging each strip that uses the same + + /* go over all the tracks up to the active one, tagging each strip that uses the same * action as the active strip, but leaving everything else alone */ for (nlt = activeTrack->prev; nlt; nlt = nlt->prev) { @@ -1913,7 +1914,7 @@ bool BKE_nla_tweakmode_enter(AnimData *adt) strip->flag &= ~NLASTRIP_FLAG_TWEAKUSER; } } - + /* tag all other strips in active track that uses the same action as the active strip */ for (strip = activeTrack->strips.first; strip; strip = strip->next) { if ((strip->act == activeStrip->act) && (strip != activeStrip)) @@ -1921,13 +1922,13 @@ bool BKE_nla_tweakmode_enter(AnimData *adt) else strip->flag &= ~NLASTRIP_FLAG_TWEAKUSER; } - - /* go over all the tracks after AND INCLUDING the active one, tagging them as being disabled + + /* go over all the tracks after AND INCLUDING the active one, tagging them as being disabled * - the active track needs to also be tagged, otherwise, it'll overlap with the tweaks going on */ for (nlt = activeTrack; nlt; nlt = nlt->next) nlt->flag |= NLATRACK_DISABLED; - + /* handle AnimData level changes: * - 'real' active action to temp storage (no need to change user-counts) * - action of active strip set to be the 'active action', and have its usercount incremented @@ -1940,7 +1941,7 @@ bool BKE_nla_tweakmode_enter(AnimData *adt) adt->actstrip = activeStrip; id_us_plus(&activeStrip->act->id); adt->flag |= ADT_NLA_EDIT_ON; - + /* done! */ return true; } @@ -1950,27 +1951,27 @@ void BKE_nla_tweakmode_exit(AnimData *adt) { NlaStrip *strip; NlaTrack *nlt; - + /* verify that data is valid */ if (ELEM(NULL, adt, adt->nla_tracks.first)) return; - + /* hopefully the flag is correct - skip if not on */ if ((adt->flag & ADT_NLA_EDIT_ON) == 0) return; - + /* sync the length of the user-strip with the new state of the action * but only if the user has explicitly asked for this to happen * (see [#34645] for things to be careful about) */ if ((adt->actstrip) && (adt->actstrip->flag & NLASTRIP_FLAG_SYNC_LENGTH)) { strip = adt->actstrip; - + /* must be action-clip only (transitions don't have scale) */ if ((strip->type == NLASTRIP_TYPE_CLIP) && (strip->act)) { /* recalculate the length of the action */ calc_action_range(strip->act, &strip->actstart, &strip->actend, 0); - + /* adjust the strip extents in response to this */ BKE_nlastrip_recalculate_bounds(strip); } @@ -1981,22 +1982,22 @@ void BKE_nla_tweakmode_exit(AnimData *adt) */ for (nlt = adt->nla_tracks.first; nlt; nlt = nlt->next) { nlt->flag &= ~NLATRACK_DISABLED; - + for (strip = nlt->strips.first; strip; strip = strip->next) { /* sync strip extents if this strip uses the same action */ if ((adt->actstrip) && (adt->actstrip->act == strip->act) && (strip->flag & NLASTRIP_FLAG_SYNC_LENGTH)) { /* recalculate the length of the action */ calc_action_range(strip->act, &strip->actstart, &strip->actend, 0); - + /* adjust the strip extents in response to this */ BKE_nlastrip_recalculate_bounds(strip); } - + /* clear tweakuser flag */ strip->flag &= ~NLASTRIP_FLAG_TWEAKUSER; } } - + /* handle AnimData level changes: * - 'temporary' active action needs its usercount decreased, since we're removing this reference * - 'real' active action is restored from storage @@ -2018,23 +2019,23 @@ void BKE_nla_tweakmode_exit(AnimData *adt) static void UNUSED_FUNCTION(BKE_nla_bake) (Scene *scene, ID *UNUSED(id), AnimData *adt, int UNUSED(flag)) { - /* verify that data is valid - * 1) Scene and AnimData must be provided + /* verify that data is valid + * 1) Scene and AnimData must be provided * 2) there must be tracks to merge... */ if (ELEM(NULL, scene, adt, adt->nla_tracks.first)) return; - + /* if animdata currently has an action, 'push down' this onto the stack first */ if (adt->action) BKE_nla_action_pushdown(adt); - + /* get range of motion to bake, and the channels involved... */ - + /* temporarily mute the action, and start keying to it */ - + /* start keying... */ - + /* unmute the action */ } diff --git a/source/blender/blenkernel/intern/node.c b/source/blender/blenkernel/intern/node.c index 72a34d35715..9de31205504 100644 --- a/source/blender/blenkernel/intern/node.c +++ b/source/blender/blenkernel/intern/node.c @@ -94,7 +94,7 @@ static void node_add_sockets_from_type(bNodeTree *ntree, bNode *node, bNodeType sockdef = ntype->inputs; while (sockdef->type != -1) { /* sock = */ node_add_socket_from_template(ntree, node, sockdef, SOCK_IN); - + sockdef++; } } @@ -102,7 +102,7 @@ static void node_add_sockets_from_type(bNodeTree *ntree, bNode *node, bNodeType sockdef = ntype->outputs; while (sockdef->type != -1) { /* sock = */ node_add_socket_from_template(ntree, node, sockdef, SOCK_OUT); - + sockdef++; } } @@ -117,11 +117,11 @@ static void node_init(const struct bContext *C, bNodeTree *ntree, bNode *node) bNodeType *ntype = node->typeinfo; if (ntype == &NodeTypeUndefined) return; - + /* only do this once */ if (node->flag & NODE_INIT) return; - + node->flag = NODE_SELECT | NODE_OPTIONS | ntype->flag; node->width = ntype->width; node->miniwidth = 42.0f; @@ -136,7 +136,7 @@ static void node_init(const struct bContext *C, bNodeTree *ntree, bNode *node) * than adding "do_translate" flags to this func (and labelfunc() as well). */ BLI_strncpy(node->name, DATA_(ntype->ui_name), NODE_MAXSTR); nodeUniqueName(ntree, node); - + node_add_sockets_from_type(ntree, node, ntype); if (ntype->initfunc != NULL) @@ -149,17 +149,17 @@ static void node_init(const struct bContext *C, bNodeTree *ntree, bNode *node) if (ntype->initfunc_api) { PointerRNA ptr; RNA_pointer_create((ID *)ntree, &RNA_Node, node, &ptr); - + /* XXX Warning: context can be NULL in case nodes are added in do_versions. * Delayed init is not supported for nodes with context-based initfunc_api atm. */ BLI_assert(C != NULL); ntype->initfunc_api(C, &ptr); } - + if (node->id) id_us_plus(node->id); - + node->flag |= NODE_INIT; } @@ -167,13 +167,13 @@ static void ntree_set_typeinfo(bNodeTree *ntree, bNodeTreeType *typeinfo) { if (typeinfo) { ntree->typeinfo = typeinfo; - + /* deprecated integer type */ ntree->type = typeinfo->type; } else { ntree->typeinfo = &NodeTreeTypeUndefined; - + ntree->init &= ~NTREE_TYPE_INIT; } } @@ -185,19 +185,19 @@ static void node_set_typeinfo(const struct bContext *C, bNodeTree *ntree, bNode if (typeinfo && typeinfo->storagename[0] && !node->storage) typeinfo = NULL; } - + if (typeinfo) { node->typeinfo = typeinfo; - + /* deprecated integer type */ node->type = typeinfo->type; - + /* initialize the node if necessary */ node_init(C, ntree, node); } else { node->typeinfo = &NodeTypeUndefined; - + ntree->init &= ~NTREE_TYPE_INIT; } } @@ -206,10 +206,10 @@ static void node_socket_set_typeinfo(bNodeTree *ntree, bNodeSocket *sock, bNodeS { if (typeinfo) { sock->typeinfo = typeinfo; - + /* deprecated integer type */ sock->type = typeinfo->type; - + if (sock->default_value == NULL) { /* initialize the default_value pointer used by standard socket types */ node_socket_init_default_value(sock); @@ -217,7 +217,7 @@ static void node_socket_set_typeinfo(bNodeTree *ntree, bNodeSocket *sock, bNodeS } else { sock->typeinfo = &NodeSocketTypeUndefined; - + ntree->init &= ~NTREE_TYPE_INIT; } } @@ -227,21 +227,21 @@ static void update_typeinfo(Main *bmain, const struct bContext *C, bNodeTreeType { if (!bmain) return; - + FOREACH_NODETREE(bmain, ntree, id) { bNode *node; bNodeSocket *sock; - + ntree->init |= NTREE_TYPE_INIT; - + if (treetype && STREQ(ntree->idname, treetype->idname)) ntree_set_typeinfo(ntree, unregister ? NULL : treetype); - + /* initialize nodes */ for (node = ntree->nodes.first; node; node = node->next) { if (nodetype && STREQ(node->idname, nodetype->idname)) node_set_typeinfo(C, ntree, node, unregister ? NULL : nodetype); - + /* initialize node sockets */ for (sock = node->inputs.first; sock; sock = sock->next) if (socktype && STREQ(sock->idname, socktype->idname)) @@ -250,7 +250,7 @@ static void update_typeinfo(Main *bmain, const struct bContext *C, bNodeTreeType if (socktype && STREQ(sock->idname, socktype->idname)) node_socket_set_typeinfo(ntree, sock, unregister ? NULL : socktype); } - + /* initialize tree sockets */ for (sock = ntree->inputs.first; sock; sock = sock->next) if (socktype && STREQ(sock->idname, socktype->idname)) @@ -271,20 +271,20 @@ void ntreeSetTypes(const struct bContext *C, bNodeTree *ntree) { bNode *node; bNodeSocket *sock; - + ntree->init |= NTREE_TYPE_INIT; - + ntree_set_typeinfo(ntree, ntreeTypeFind(ntree->idname)); - + for (node = ntree->nodes.first; node; node = node->next) { node_set_typeinfo(C, ntree, node, nodeTypeFind(node->idname)); - + for (sock = node->inputs.first; sock; sock = sock->next) node_socket_set_typeinfo(ntree, sock, nodeSocketTypeFind(sock->idname)); for (sock = node->outputs.first; sock; sock = sock->next) node_socket_set_typeinfo(ntree, sock, nodeSocketTypeFind(sock->idname)); } - + for (sock = ntree->inputs.first; sock; sock = sock->next) node_socket_set_typeinfo(ntree, sock, nodeSocketTypeFind(sock->idname)); for (sock = ntree->outputs.first; sock; sock = sock->next) @@ -314,7 +314,9 @@ void ntreeTypeAdd(bNodeTreeType *nt) { BLI_ghash_insert(nodetreetypes_hash, nt->idname, nt); /* XXX pass Main to register function? */ - update_typeinfo(G.main, NULL, nt, NULL, NULL, false); + /* Probably not. It is pretty much expected we want to update G_MAIN her I think - or we'd want to update *all* + * active Mains, which we cannot do anyway currently. */ + update_typeinfo(G_MAIN, NULL, nt, NULL, NULL, false); } /* callback for hash value free function */ @@ -322,7 +324,9 @@ static void ntree_free_type(void *treetype_v) { bNodeTreeType *treetype = treetype_v; /* XXX pass Main to unregister function? */ - update_typeinfo(G.main, NULL, treetype, NULL, NULL, true); + /* Probably not. It is pretty much expected we want to update G_MAIN her I think - or we'd want to update *all* + * active Mains, which we cannot do anyway currently. */ + update_typeinfo(G_MAIN, NULL, treetype, NULL, NULL, true); MEM_freeN(treetype); } @@ -371,12 +375,14 @@ static void node_free_type(void *nodetype_v) { bNodeType *nodetype = nodetype_v; /* XXX pass Main to unregister function? */ - update_typeinfo(G.main, NULL, NULL, nodetype, NULL, true); - + /* Probably not. It is pretty much expected we want to update G_MAIN her I think - or we'd want to update *all* + * active Mains, which we cannot do anyway currently. */ + update_typeinfo(G_MAIN, NULL, NULL, nodetype, NULL, true); + /* XXX deprecated */ if (nodetype->type == NODE_DYNAMIC) free_dynamic_typeinfo(nodetype); - + if (nodetype->needs_free) MEM_freeN(nodetype); } @@ -386,10 +392,12 @@ void nodeRegisterType(bNodeType *nt) /* debug only: basic verification of registered types */ BLI_assert(nt->idname[0] != '\0'); BLI_assert(nt->poll != NULL); - + BLI_ghash_insert(nodetypes_hash, nt->idname, nt); /* XXX pass Main to register function? */ - update_typeinfo(G.main, NULL, NULL, nt, NULL, false); + /* Probably not. It is pretty much expected we want to update G_MAIN her I think - or we'd want to update *all* + * active Mains, which we cannot do anyway currently. */ + update_typeinfo(G_MAIN, NULL, NULL, nt, NULL, false); } void nodeUnregisterType(bNodeType *nt) @@ -425,8 +433,10 @@ static void node_free_socket_type(void *socktype_v) { bNodeSocketType *socktype = socktype_v; /* XXX pass Main to unregister function? */ - update_typeinfo(G.main, NULL, NULL, NULL, socktype, true); - + /* Probably not. It is pretty much expected we want to update G_MAIN her I think - or we'd want to update *all* + * active Mains, which we cannot do anyway currently. */ + update_typeinfo(G_MAIN, NULL, NULL, NULL, socktype, true); + MEM_freeN(socktype); } @@ -434,7 +444,9 @@ void nodeRegisterSocketType(bNodeSocketType *st) { BLI_ghash_insert(nodesockettypes_hash, (void *)st->idname, st); /* XXX pass Main to register function? */ - update_typeinfo(G.main, NULL, NULL, NULL, st, false); + /* Probably not. It is pretty much expected we want to update G_MAIN her I think - or we'd want to update *all* + * active Mains, which we cannot do anyway currently. */ + update_typeinfo(G_MAIN, NULL, NULL, NULL, st, false); } void nodeUnregisterSocketType(bNodeSocketType *st) @@ -479,7 +491,7 @@ static bNodeSocket *make_socket(bNodeTree *ntree, bNode *UNUSED(node), int in_ou { bNodeSocket *sock; char auto_identifier[MAX_NAME]; - + if (identifier && identifier[0] != '\0') { /* use explicit identifier */ BLI_strncpy(auto_identifier, identifier, sizeof(auto_identifier)); @@ -490,21 +502,21 @@ static bNodeSocket *make_socket(bNodeTree *ntree, bNode *UNUSED(node), int in_ou } /* make the identifier unique */ BLI_uniquename_cb(unique_identifier_check, lb, "socket", '.', auto_identifier, sizeof(auto_identifier)); - + sock = MEM_callocN(sizeof(bNodeSocket), "sock"); sock->in_out = in_out; - + BLI_strncpy(sock->identifier, auto_identifier, NODE_MAXSTR); sock->limit = (in_out == SOCK_IN ? 1 : 0xFFF); - + BLI_strncpy(sock->name, name, NODE_MAXSTR); sock->storage = NULL; sock->flag |= SOCK_COLLAPSED; sock->type = SOCK_CUSTOM; /* int type undefined by default */ - + BLI_strncpy(sock->idname, idname, sizeof(sock->idname)); node_socket_set_typeinfo(ntree, sock, nodeSocketTypeFind(idname)); - + return sock; } @@ -533,12 +545,12 @@ bNodeSocket *nodeAddSocket(bNodeTree *ntree, bNode *node, int in_out, const char { ListBase *lb = (in_out == SOCK_IN ? &node->inputs : &node->outputs); bNodeSocket *sock = make_socket(ntree, node, in_out, lb, idname, identifier, name); - + BLI_remlink(lb, sock); /* does nothing for new socket */ BLI_addtail(lb, sock); - + node->update |= NODE_UPDATE; - + return sock; } @@ -547,12 +559,12 @@ bNodeSocket *nodeInsertSocket(bNodeTree *ntree, bNode *node, int in_out, const c { ListBase *lb = (in_out == SOCK_IN ? &node->inputs : &node->outputs); bNodeSocket *sock = make_socket(ntree, node, in_out, lb, idname, identifier, name); - + BLI_remlink(lb, sock); /* does nothing for new socket */ BLI_insertlinkbefore(lb, next_sock, sock); - + node->update |= NODE_UPDATE; - + return sock; } @@ -683,12 +695,12 @@ bNodeSocket *nodeAddStaticSocket(bNodeTree *ntree, bNode *node, int in_out, int { const char *idname = nodeStaticSocketType(type, subtype); bNodeSocket *sock; - + if (!idname) { printf("Error: static node socket type %d undefined\n", type); return NULL; } - + sock = nodeAddSocket(ntree, node, in_out, idname, identifier, name); sock->type = type; return sock; @@ -699,12 +711,12 @@ bNodeSocket *nodeInsertStaticSocket(bNodeTree *ntree, bNode *node, int in_out, i { const char *idname = nodeStaticSocketType(type, subtype); bNodeSocket *sock; - + if (!idname) { printf("Error: static node socket type %d undefined\n", type); return NULL; } - + sock = nodeInsertSocket(ntree, node, in_out, idname, next_sock, identifier, name); sock->type = type; return sock; @@ -716,7 +728,7 @@ static void node_socket_free(bNodeTree *UNUSED(ntree), bNodeSocket *sock, bNode IDP_FreeProperty(sock->prop); MEM_freeN(sock->prop); } - + if (sock->default_value) MEM_freeN(sock->default_value); } @@ -724,21 +736,21 @@ static void node_socket_free(bNodeTree *UNUSED(ntree), bNodeSocket *sock, bNode void nodeRemoveSocket(bNodeTree *ntree, bNode *node, bNodeSocket *sock) { bNodeLink *link, *next; - + for (link = ntree->links.first; link; link = next) { next = link->next; if (link->fromsock == sock || link->tosock == sock) { nodeRemLink(ntree, link); } } - + /* this is fast, this way we don't need an in_out argument */ BLI_remlink(&node->inputs, sock); BLI_remlink(&node->outputs, sock); - + node_socket_free(ntree, sock, node); MEM_freeN(sock); - + node->update |= NODE_UPDATE; } @@ -746,14 +758,14 @@ void nodeRemoveAllSockets(bNodeTree *ntree, bNode *node) { bNodeSocket *sock, *sock_next; bNodeLink *link, *next; - + for (link = ntree->links.first; link; link = next) { next = link->next; if (link->fromnode == node || link->tonode == node) { nodeRemLink(ntree, link); } } - + for (sock = node->inputs.first; sock; sock = sock_next) { sock_next = sock->next; node_socket_free(ntree, sock, node); @@ -767,7 +779,7 @@ void nodeRemoveAllSockets(bNodeTree *ntree, bNode *node) MEM_freeN(sock); } BLI_listbase_clear(&node->outputs); - + node->update |= NODE_UPDATE; } @@ -784,7 +796,7 @@ int nodeFindNode(bNodeTree *ntree, bNodeSocket *sock, bNode **nodep, int *sockin bNode *node; bNodeSocket *tsock; int index = 0; - + for (node = ntree->nodes.first; node; node = node->next) { tsock = (in_out == SOCK_IN ? node->inputs.first : node->outputs.first); for (index = 0; tsock; tsock = tsock->next, index++) { @@ -800,7 +812,7 @@ int nodeFindNode(bNodeTree *ntree, bNodeSocket *sock, bNode **nodep, int *sockin if (sockindex) *sockindex = index; return 1; } - + *nodep = NULL; return 0; } @@ -892,22 +904,22 @@ void nodeUniqueName(bNodeTree *ntree, bNode *node) bNode *nodeAddNode(const struct bContext *C, bNodeTree *ntree, const char *idname) { bNode *node; - + node = MEM_callocN(sizeof(bNode), "new node"); BLI_addtail(&ntree->nodes, node); - + BLI_strncpy(node->idname, idname, sizeof(node->idname)); node_set_typeinfo(C, ntree, node, nodeTypeFind(idname)); - + ntree->update |= NTREE_UPDATE_NODES; - + return node; } bNode *nodeAddStaticNode(const struct bContext *C, bNodeTree *ntree, int type) { const char *idname = NULL; - + NODE_TYPES_BEGIN(ntype) /* do an extra poll here, because some int types are used * for multiple node types, this helps find the desired type @@ -1024,11 +1036,11 @@ bNode *nodeCopyNode(bNodeTree *ntree, bNode *node) bNodeLink *nodeAddLink(bNodeTree *ntree, bNode *fromnode, bNodeSocket *fromsock, bNode *tonode, bNodeSocket *tosock) { bNodeLink *link = NULL; - + /* test valid input */ BLI_assert(fromnode); BLI_assert(tonode); - + if (fromsock->in_out == SOCK_OUT && tosock->in_out == SOCK_IN) { link = MEM_callocN(sizeof(bNodeLink), "link"); if (ntree) @@ -1048,10 +1060,10 @@ bNodeLink *nodeAddLink(bNodeTree *ntree, bNode *fromnode, bNodeSocket *fromsock, link->tonode = fromnode; link->tosock = fromsock; } - + if (ntree) ntree->update |= NTREE_UPDATE_LINKS; - + return link; } @@ -1064,7 +1076,7 @@ void nodeRemLink(bNodeTree *ntree, bNodeLink *link) if (link->tosock) link->tosock->link = NULL; MEM_freeN(link); - + if (ntree) ntree->update |= NTREE_UPDATE_LINKS; } @@ -1072,14 +1084,14 @@ void nodeRemLink(bNodeTree *ntree, bNodeLink *link) void nodeRemSocketLinks(bNodeTree *ntree, bNodeSocket *sock) { bNodeLink *link, *next; - + for (link = ntree->links.first; link; link = next) { next = link->next; if (link->fromsock == sock || link->tosock == sock) { nodeRemLink(ntree, link); } } - + ntree->update |= NTREE_UPDATE_LINKS; } @@ -1091,15 +1103,15 @@ bool nodeLinkIsHidden(bNodeLink *link) void nodeInternalRelink(bNodeTree *ntree, bNode *node) { bNodeLink *link, *link_next; - + /* store link pointers in output sockets, for efficient lookup */ for (link = node->internal_links.first; link; link = link->next) link->tosock->link = link; - + /* redirect downstream links */ for (link = ntree->links.first; link; link = link_next) { link_next = link->next; - + /* do we have internal link? */ if (link->fromnode == node) { if (link->fromsock->link) { @@ -1109,13 +1121,13 @@ void nodeInternalRelink(bNodeTree *ntree, bNode *node) if (fromlink) { link->fromnode = fromlink->fromnode; link->fromsock = fromlink->fromsock; - + /* if the up- or downstream link is invalid, * the replacement link will be invalid too. */ if (!(fromlink->flag & NODE_LINK_VALID)) link->flag &= ~NODE_LINK_VALID; - + ntree->update |= NTREE_UPDATE_LINKS; } else @@ -1125,11 +1137,11 @@ void nodeInternalRelink(bNodeTree *ntree, bNode *node) nodeRemLink(ntree, link); } } - + /* remove remaining upstream links */ for (link = ntree->links.first; link; link = link_next) { link_next = link->next; - + if (link->tonode == node) nodeRemLink(ntree, link); } @@ -1179,7 +1191,7 @@ void nodeAttachNode(bNode *node, bNode *parent) BLI_assert(nodeAttachNodeCheck(parent, node) == false); nodeToView(node, 0.0f, 0.0f, &locx, &locy); - + node->parent = parent; /* transform to parent space */ nodeFromView(parent, locx, locy, &node->locx, &node->locy); @@ -1188,7 +1200,7 @@ void nodeAttachNode(bNode *node, bNode *parent) void nodeDetachNode(struct bNode *node) { float locx, locy; - + if (node->parent) { BLI_assert(node->parent->type == NODE_FRAME); @@ -1209,7 +1221,7 @@ void ntreeInitDefault(bNodeTree *ntree) bNodeTree *ntreeAddTree(Main *bmain, const char *name, const char *idname) { bNodeTree *ntree; - + /* trees are created as local trees for compositor, material or texture nodes, * node groups and other tree types are created as library data. */ @@ -1221,15 +1233,15 @@ bNodeTree *ntreeAddTree(Main *bmain, const char *name, const char *idname) *( (short *)ntree->id.name ) = ID_NT; BLI_strncpy(ntree->id.name + 2, name, sizeof(ntree->id.name)); } - + /* Types are fully initialized at this point, * if an undefined node is added later this will be reset. */ ntree->init |= NTREE_TYPE_INIT; - + BLI_strncpy(ntree->idname, idname, sizeof(ntree->idname)); ntree_set_typeinfo(ntree, ntreeTypeFind(idname)); - + return ntree; } @@ -1360,7 +1372,7 @@ int BKE_node_preview_used(bNode *node) bNodePreview *BKE_node_preview_verify(bNodeInstanceHash *previews, bNodeInstanceKey key, int xsize, int ysize, bool create) { bNodePreview *preview; - + preview = BKE_node_instance_hash_lookup(previews, key); if (!preview) { if (create) { @@ -1370,11 +1382,11 @@ bNodePreview *BKE_node_preview_verify(bNodeInstanceHash *previews, bNodeInstance else return NULL; } - + /* node previews can get added with variable size this way */ if (xsize == 0 || ysize == 0) return preview; - + /* sanity checks & initialize */ if (preview->rect) { if (preview->xsize != xsize || preview->ysize != ysize) { @@ -1382,14 +1394,14 @@ bNodePreview *BKE_node_preview_verify(bNodeInstanceHash *previews, bNodeInstance preview->rect = NULL; } } - + if (preview->rect == NULL) { preview->rect = MEM_callocN(4 * xsize + xsize * ysize * sizeof(char) * 4, "node preview rect"); preview->xsize = xsize; preview->ysize = ysize; } /* no clear, makes nicer previews */ - + return preview; } @@ -1413,14 +1425,14 @@ static void node_preview_init_tree_recursive(bNodeInstanceHash *previews, bNodeT bNode *node; for (node = ntree->nodes.first; node; node = node->next) { bNodeInstanceKey key = BKE_node_instance_key(parent_key, ntree, node); - + if (BKE_node_preview_used(node)) { node->preview_xsize = xsize; node->preview_ysize = ysize; - + BKE_node_preview_verify(previews, key, xsize, ysize, create); } - + if (node->type == NODE_GROUP && node->id) node_preview_init_tree_recursive(previews, (bNodeTree *)node->id, key, xsize, ysize, create); } @@ -1430,10 +1442,10 @@ void BKE_node_preview_init_tree(bNodeTree *ntree, int xsize, int ysize, int crea { if (!ntree) return; - + if (!ntree->previews) ntree->previews = BKE_node_instance_hash_new("node previews"); - + node_preview_init_tree_recursive(ntree->previews, ntree, NODE_INSTANCE_KEY_BASE, xsize, ysize, create_previews); } @@ -1442,10 +1454,10 @@ static void node_preview_tag_used_recursive(bNodeInstanceHash *previews, bNodeTr bNode *node; for (node = ntree->nodes.first; node; node = node->next) { bNodeInstanceKey key = BKE_node_instance_key(parent_key, ntree, node); - + if (BKE_node_preview_used(node)) BKE_node_instance_hash_tag_key(previews, key); - + if (node->type == NODE_GROUP && node->id) node_preview_tag_used_recursive(previews, (bNodeTree *)node->id, key); } @@ -1455,11 +1467,11 @@ void BKE_node_preview_remove_unused(bNodeTree *ntree) { if (!ntree || !ntree->previews) return; - + /* use the instance hash functions for tagging and removing unused previews */ BKE_node_instance_hash_clear_tags(ntree->previews); node_preview_tag_used_recursive(ntree->previews, ntree, NODE_INSTANCE_KEY_BASE); - + BKE_node_instance_hash_remove_untagged(ntree->previews, (bNodeInstanceValueFP)BKE_node_preview_free); } @@ -1467,7 +1479,7 @@ void BKE_node_preview_free_tree(bNodeTree *ntree) { if (!ntree) return; - + if (ntree->previews) { BKE_node_instance_hash_free(ntree->previews, (bNodeInstanceValueFP)BKE_node_preview_free); ntree->previews = NULL; @@ -1483,10 +1495,10 @@ void BKE_node_preview_clear(bNodePreview *preview) void BKE_node_preview_clear_tree(bNodeTree *ntree) { bNodeInstanceHashIterator iter; - + if (!ntree || !ntree->previews) return; - + NODE_INSTANCE_HASH_ITER(iter, ntree->previews) { bNodePreview *preview = BKE_node_instance_hash_iterator_get_value(&iter); BKE_node_preview_clear(preview); @@ -1497,7 +1509,7 @@ static void node_preview_sync(bNodePreview *to, bNodePreview *from) { /* sizes should have been initialized by BKE_node_preview_init_tree */ BLI_assert(to->xsize == from->xsize && to->ysize == from->ysize); - + /* copy over contents of previews */ if (to->rect && from->rect) { int xsize = to->xsize; @@ -1511,15 +1523,15 @@ void BKE_node_preview_sync_tree(bNodeTree *to_ntree, bNodeTree *from_ntree) bNodeInstanceHash *from_previews = from_ntree->previews; bNodeInstanceHash *to_previews = to_ntree->previews; bNodeInstanceHashIterator iter; - + if (!from_previews || !to_previews) return; - + NODE_INSTANCE_HASH_ITER(iter, from_previews) { bNodeInstanceKey key = BKE_node_instance_hash_iterator_get_key(&iter); bNodePreview *from = BKE_node_instance_hash_iterator_get_value(&iter); bNodePreview *to = BKE_node_instance_hash_lookup(to_previews, key); - + if (from && to) node_preview_sync(to, from); } @@ -1531,27 +1543,27 @@ void BKE_node_preview_merge_tree(bNodeTree *to_ntree, bNodeTree *from_ntree, boo /* free old previews */ if (to_ntree->previews) BKE_node_instance_hash_free(to_ntree->previews, (bNodeInstanceValueFP)BKE_node_preview_free); - + /* transfer previews */ to_ntree->previews = from_ntree->previews; from_ntree->previews = NULL; - + /* clean up, in case any to_ntree nodes have been removed */ BKE_node_preview_remove_unused(to_ntree); } else { bNodeInstanceHashIterator iter; - + if (from_ntree->previews) { NODE_INSTANCE_HASH_ITER(iter, from_ntree->previews) { bNodeInstanceKey key = BKE_node_instance_hash_iterator_get_key(&iter); bNodePreview *preview = BKE_node_instance_hash_iterator_get_value(&iter); - + /* replace existing previews */ BKE_node_instance_hash_remove(to_ntree->previews, key, (bNodeInstanceValueFP)BKE_node_preview_free); BKE_node_instance_hash_insert(to_ntree->previews, key, preview); } - + /* Note: NULL free function here, because pointers have already been moved over to to_ntree->previews! */ BKE_node_instance_hash_free(from_ntree->previews, NULL); from_ntree->previews = NULL; @@ -1559,7 +1571,7 @@ void BKE_node_preview_merge_tree(bNodeTree *to_ntree, bNodeTree *from_ntree, boo } } -/* hack warning! this function is only used for shader previews, and +/* hack warning! this function is only used for shader previews, and * since it gets called multiple times per pixel for Ztransp we only * add the color once. Preview gets cleared before it starts render though */ void BKE_node_preview_set_pixel(bNodePreview *preview, const float col[4], int x, int y, bool do_manage) @@ -1568,7 +1580,7 @@ void BKE_node_preview_set_pixel(bNodePreview *preview, const float col[4], int x if (x >= 0 && y >= 0) { if (x < preview->xsize && y < preview->ysize) { unsigned char *tar = preview->rect + 4 * ((preview->xsize * y) + x); - + if (do_manage) { linearrgb_to_srgb_uchar4(tar, col); } @@ -1593,10 +1605,10 @@ static void nodeClearPreview(bNode *node) void ntreeClearPreview(bNodeTree *ntree) { bNode *node; - + if (ntree == NULL) return; - + for (node = ntree->nodes.first; node; node = node->next) { if (node->typeinfo->flag & NODE_PREVIEW) nodeClearPreview(node); @@ -1605,7 +1617,7 @@ void ntreeClearPreview(bNodeTree *ntree) } } -/* hack warning! this function is only used for shader previews, and +/* hack warning! this function is only used for shader previews, and * since it gets called multiple times per pixel for Ztransp we only * add the color once. Preview gets cleared before it starts render though */ void nodeAddToPreview(bNode *node, const float col[4], int x, int y, int do_manage) @@ -1615,7 +1627,7 @@ void nodeAddToPreview(bNode *node, const float col[4], int x, int y, int do_mana if (x >= 0 && y >= 0) { if (x < preview->xsize && y < preview->ysize) { unsigned char *tar = preview->rect + 4 * ((preview->xsize * y) + x); - + if (do_manage) { linearrgb_to_srgb_uchar4(tar, col); } @@ -1638,10 +1650,10 @@ void nodeUnlinkNode(bNodeTree *ntree, bNode *node) bNodeLink *link, *next; bNodeSocket *sock; ListBase *lb; - + for (link = ntree->links.first; link; link = next) { next = link->next; - + if (link->fromnode == node) { lb = &node->outputs; if (link->tonode) @@ -1677,30 +1689,30 @@ static void node_unlink_attached(bNodeTree *ntree, bNode *parent) static void node_free_node_ex(bNodeTree *ntree, bNode *node, bool remove_animdata, bool use_api_free_cb) { bNodeSocket *sock, *nextsock; - + /* don't remove node animdata if the tree is localized, * Action is shared with the original tree (T38221) */ remove_animdata &= ntree && !(ntree->flag & NTREE_IS_LOCALIZED); - + /* extra free callback */ if (use_api_free_cb && node->typeinfo->freefunc_api) { PointerRNA ptr; RNA_pointer_create((ID *)ntree, &RNA_Node, node, &ptr); - + node->typeinfo->freefunc_api(&ptr); } - + /* since it is called while free database, node->id is undefined */ - + /* can be called for nodes outside a node tree (e.g. clipboard) */ if (ntree) { /* remove all references to this node */ nodeUnlinkNode(ntree, node); node_unlink_attached(ntree, node); - + BLI_remlink(&ntree->nodes, node); - + if (remove_animdata) { char propname_esc[MAX_IDPROP_NAME * 2]; char prefix[MAX_IDPROP_NAME * 2]; @@ -1713,7 +1725,7 @@ static void node_free_node_ex(bNodeTree *ntree, bNode *node, bool remove_animdat if (ntree->typeinfo->free_node_cache) ntree->typeinfo->free_node_cache(ntree, node); - + /* texture node has bad habit of keeping exec data around */ if (ntree->type == NTREE_TEXTURE && ntree->execdata) { ntreeTexEndExecTree(ntree->execdata); @@ -1744,7 +1756,7 @@ static void node_free_node_ex(bNodeTree *ntree, bNode *node, bool remove_animdat } MEM_freeN(node); - + if (ntree) ntree->update |= NTREE_UPDATE_NODES; } @@ -1760,7 +1772,7 @@ static void node_socket_interface_free(bNodeTree *UNUSED(ntree), bNodeSocket *so IDP_FreeProperty(sock->prop); MEM_freeN(sock->prop); } - + if (sock->default_value) MEM_freeN(sock->default_value); } @@ -1768,7 +1780,7 @@ static void node_socket_interface_free(bNodeTree *UNUSED(ntree), bNodeSocket *so static void free_localized_node_groups(bNodeTree *ntree) { bNode *node; - + /* Only localized node trees store a copy for each node group tree. * Each node group tree in a localized node tree can be freed, * since it is a localized copy itself (no risk of accessing free'd @@ -1776,7 +1788,7 @@ static void free_localized_node_groups(bNodeTree *ntree) */ if (!(ntree->flag & NTREE_IS_LOCALIZED)) return; - + for (node = ntree->nodes.first; node; node = node->next) { if (node->type == NODE_GROUP && node->id) { bNodeTree *ngroup = (bNodeTree *)node->id; @@ -1789,7 +1801,6 @@ static void free_localized_node_groups(bNodeTree *ntree) /** Free (or release) any data used by this nodetree (does not free the nodetree itself). */ void ntreeFreeTree(bNodeTree *ntree) { - bNodeTree *tntree; bNode *node, *next; bNodeSocket *sock, *nextsock; @@ -1811,15 +1822,15 @@ void ntreeFreeTree(bNodeTree *ntree) break; } } - + /* XXX not nice, but needed to free localized node groups properly */ free_localized_node_groups(ntree); - + /* unregister associated RNA types */ ntreeInterfaceTypeFree(ntree); - + BLI_freelistN(&ntree->links); /* do first, then unlink_node goes fast */ - + for (node = ntree->nodes.first; node; node = next) { next = node->next; node_free_node_ex(ntree, node, false, false); @@ -1836,7 +1847,7 @@ void ntreeFreeTree(bNodeTree *ntree) node_socket_interface_free(ntree, sock); MEM_freeN(sock); } - + /* free preview hash */ if (ntree->previews) { BKE_node_instance_hash_free(ntree->previews, (bNodeInstanceValueFP)BKE_node_preview_free); @@ -1844,12 +1855,9 @@ void ntreeFreeTree(bNodeTree *ntree) if (ntree->duplilock) BLI_mutex_free(ntree->duplilock); - + /* if ntree is not part of library, free the libblock data explicitly */ - for (tntree = G.main->nodetree.first; tntree; tntree = tntree->id.next) - if (tntree == ntree) - break; - if (tntree == NULL) { + if (ntree->id.tag & LIB_TAG_NO_MAIN) { BKE_libblock_free_data(&ntree->id, true); } } @@ -1857,7 +1865,7 @@ void ntreeFreeTree(bNodeTree *ntree) void ntreeFreeCache(bNodeTree *ntree) { if (ntree == NULL) return; - + if (ntree->typeinfo->free_cache) ntree->typeinfo->free_cache(ntree); } @@ -1871,7 +1879,7 @@ void ntreeSetOutput(bNodeTree *ntree) if (node->typeinfo->nclass == NODE_CLASS_OUTPUT) { bNode *tnode; int output = 0; - + /* we need a check for which output node should be tagged like this, below an exception */ if (node->type == CMP_NODE_OUTPUT_FILE) continue; @@ -1879,9 +1887,9 @@ void ntreeSetOutput(bNodeTree *ntree) /* there is more types having output class, each one is checked */ for (tnode = ntree->nodes.first; tnode; tnode = tnode->next) { if (tnode->typeinfo->nclass == NODE_CLASS_OUTPUT) { - + if (ntree->type == NTREE_COMPOSIT) { - + /* same type, exception for viewer */ if (tnode->type == node->type || (ELEM(tnode->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER) && @@ -1909,12 +1917,12 @@ void ntreeSetOutput(bNodeTree *ntree) if (output == 0) node->flag |= NODE_DO_OUTPUT; } - + /* group node outputs use this flag too */ if (node->type == NODE_GROUP_OUTPUT) { bNode *tnode; int output = 0; - + for (tnode = ntree->nodes.first; tnode; tnode = tnode->next) { if (tnode->type == NODE_GROUP_OUTPUT) { if (tnode->flag & NODE_DO_OUTPUT) { @@ -1928,7 +1936,7 @@ void ntreeSetOutput(bNodeTree *ntree) node->flag |= NODE_DO_OUTPUT; } } - + /* here we could recursively set which nodes have to be done, * might be different for editor or for "real" use... */ } @@ -2055,7 +2063,7 @@ void ntreeLocalMerge(Main *bmain, bNodeTree *localtree, bNodeTree *ntree) if (ntree && localtree) { if (ntree->typeinfo->local_merge) ntree->typeinfo->local_merge(bmain, localtree, ntree); - + ntreeFreeTree(localtree); MEM_freeN(localtree); } @@ -2080,7 +2088,7 @@ static bNodeSocket *make_socket_interface(bNodeTree *ntree, int in_out, node_socket_set_typeinfo(ntree, sock, stype); sock->in_out = in_out; sock->type = SOCK_CUSTOM; /* int type undefined by default */ - + /* assign new unique index */ own_index = ntree->cur_index++; /* use the own_index as socket identifier */ @@ -2107,13 +2115,13 @@ static bNodeSocket *make_socket_interface(bNodeTree *ntree, int in_out, #endif #endif /* USE_NODE_COMPAT_CUSTOMNODES */ - + sock->limit = (in_out == SOCK_IN ? 1 : 0xFFF); - + BLI_strncpy(sock->name, name, NODE_MAXSTR); sock->storage = NULL; sock->flag |= SOCK_COLLAPSED; - + return sock; } @@ -2129,7 +2137,7 @@ bNodeSocket *ntreeFindSocketInterface(bNodeTree *ntree, int in_out, const char * bNodeSocket *ntreeAddSocketInterface(bNodeTree *ntree, int in_out, const char *idname, const char *name) { bNodeSocket *iosock; - + iosock = make_socket_interface(ntree, in_out, idname, name); if (in_out == SOCK_IN) { BLI_addtail(&ntree->inputs, iosock); @@ -2139,7 +2147,7 @@ bNodeSocket *ntreeAddSocketInterface(bNodeTree *ntree, int in_out, const char *i BLI_addtail(&ntree->outputs, iosock); ntree->update |= NTREE_UPDATE_GROUP_OUT; } - + return iosock; } @@ -2147,7 +2155,7 @@ bNodeSocket *ntreeInsertSocketInterface(bNodeTree *ntree, int in_out, const char bNodeSocket *next_sock, const char *name) { bNodeSocket *iosock; - + iosock = make_socket_interface(ntree, in_out, idname, name); if (in_out == SOCK_IN) { BLI_insertlinkbefore(&ntree->inputs, next_sock, iosock); @@ -2157,7 +2165,7 @@ bNodeSocket *ntreeInsertSocketInterface(bNodeTree *ntree, int in_out, const char BLI_insertlinkbefore(&ntree->outputs, next_sock, iosock); ntree->update |= NTREE_UPDATE_GROUP_OUT; } - + return iosock; } @@ -2186,10 +2194,10 @@ void ntreeRemoveSocketInterface(bNodeTree *ntree, bNodeSocket *sock) /* this is fast, this way we don't need an in_out argument */ BLI_remlink(&ntree->inputs, sock); BLI_remlink(&ntree->outputs, sock); - + node_socket_interface_free(ntree, sock); MEM_freeN(sock); - + ntree->update |= NTREE_UPDATE_GROUP; } @@ -2216,7 +2224,7 @@ static void ntree_interface_identifier(bNodeTree *ntree, const char *base, char */ identifier[0] = '\0'; BLI_uniquename_cb(ntree_interface_unique_identifier_check, NULL, base, '_', identifier, maxlen); - + sprintf(name, "Node Tree %s Interface", ntree->id.name + 2); sprintf(description, "Interface properties of node group %s", ntree->id.name + 2); } @@ -2227,20 +2235,20 @@ static void ntree_interface_type_create(bNodeTree *ntree) bNodeSocket *sock; /* strings are generated from base string + ID name, sizes are sufficient */ char base[MAX_ID_NAME + 64], identifier[MAX_ID_NAME + 64], name[MAX_ID_NAME + 64], description[MAX_ID_NAME + 64]; - + /* generate a valid RNA identifier */ ntree_interface_identifier_base(ntree, base); ntree_interface_identifier(ntree, base, identifier, sizeof(identifier), name, description); - + /* register a subtype of PropertyGroup */ srna = RNA_def_struct_ptr(&BLENDER_RNA, identifier, &RNA_PropertyGroup); RNA_def_struct_ui_text(srna, name, description); RNA_def_struct_duplicate_pointers(&BLENDER_RNA, srna); - + /* associate the RNA type with the node tree */ ntree->interface_type = srna; RNA_struct_blender_type_set(srna, ntree); - + /* add socket properties */ for (sock = ntree->inputs.first; sock; sock = sock->next) { bNodeSocketType *stype = sock->typeinfo; @@ -2259,20 +2267,20 @@ StructRNA *ntreeInterfaceTypeGet(bNodeTree *ntree, int create) if (ntree->interface_type) { /* strings are generated from base string + ID name, sizes are sufficient */ char base[MAX_ID_NAME + 64], identifier[MAX_ID_NAME + 64], name[MAX_ID_NAME + 64], description[MAX_ID_NAME + 64]; - + /* A bit of a hack: when changing the ID name, update the RNA type identifier too, * so that the names match. This is not strictly necessary to keep it working, * but better for identifying associated NodeTree blocks and RNA types. */ StructRNA *srna = ntree->interface_type; - + ntree_interface_identifier_base(ntree, base); - + /* RNA identifier may have a number suffix, but should start with the idbase string */ if (!STREQLEN(RNA_struct_identifier(srna), base, sizeof(base))) { /* generate new unique RNA identifier from the ID name */ ntree_interface_identifier(ntree, base, identifier, sizeof(identifier), name, description); - + /* rename the RNA type */ RNA_def_struct_free_pointers(&BLENDER_RNA, srna); RNA_def_struct_identifier(&BLENDER_RNA, srna, identifier); @@ -2283,7 +2291,7 @@ StructRNA *ntreeInterfaceTypeGet(bNodeTree *ntree, int create) else if (create) { ntree_interface_type_create(ntree); } - + return ntree->interface_type; } @@ -2344,7 +2352,7 @@ bool ntreeHasTree(const bNodeTree *ntree, const bNodeTree *lookup) bNodeLink *nodeFindLink(bNodeTree *ntree, bNodeSocket *from, bNodeSocket *to) { bNodeLink *link; - + for (link = ntree->links.first; link; link = link->next) { if (link->fromsock == from && link->tosock == to) return link; @@ -2358,7 +2366,7 @@ int nodeCountSocketLinks(bNodeTree *ntree, bNodeSocket *sock) { bNodeLink *link; int tot = 0; - + for (link = ntree->links.first; link; link = link->next) { if (link->fromsock == sock || link->tosock == sock) tot++; @@ -2369,9 +2377,9 @@ int nodeCountSocketLinks(bNodeTree *ntree, bNodeSocket *sock) bNode *nodeGetActive(bNodeTree *ntree) { bNode *node; - + if (ntree == NULL) return NULL; - + for (node = ntree->nodes.first; node; node = node->next) if (node->flag & NODE_ACTIVE) break; @@ -2402,7 +2410,7 @@ static bNode *node_get_active_id_recursive(bNodeInstanceKey active_key, bNodeIns } } } - + return NULL; } @@ -2451,9 +2459,9 @@ bool nodeSetActiveID(bNodeTree *ntree, short idtype, ID *id) void nodeClearActiveID(bNodeTree *ntree, short idtype) { bNode *node; - + if (ntree == NULL) return; - + for (node = ntree->nodes.first; node; node = node->next) if (node->id && GS(node->id->name) == idtype) node->flag &= ~NODE_ACTIVE_ID; @@ -2466,9 +2474,9 @@ void nodeSetSelected(bNode *node, bool select) } else { bNodeSocket *sock; - + node->flag &= ~NODE_SELECT; - + /* deselect sockets too */ for (sock = node->inputs.first; sock; sock = sock->next) sock->flag &= ~NODE_SELECT; @@ -2491,11 +2499,11 @@ void nodeClearActive(bNodeTree *ntree) void nodeSetActive(bNodeTree *ntree, bNode *node) { bNode *tnode; - + /* make sure only one node is active, and only one per ID type */ for (tnode = ntree->nodes.first; tnode; tnode = tnode->next) { tnode->flag &= ~NODE_ACTIVE; - + if (node->id && tnode->id) { if (GS(node->id->name) == GS(tnode->id->name)) tnode->flag &= ~NODE_ACTIVE_ID; @@ -2503,7 +2511,7 @@ void nodeSetActive(bNodeTree *ntree, bNode *node) if (node->typeinfo->nclass == NODE_CLASS_TEXTURE) tnode->flag &= ~NODE_ACTIVE_TEXTURE; } - + node->flag |= NODE_ACTIVE; if (node->id) node->flag |= NODE_ACTIVE_ID; @@ -2559,13 +2567,13 @@ void BKE_node_clipboard_clear(void) { bNode *node, *node_next; bNodeLink *link, *link_next; - + for (link = node_clipboard.links.first; link; link = link_next) { link_next = link->next; nodeRemLink(NULL, link); } BLI_listbase_clear(&node_clipboard.links); - + for (node = node_clipboard.nodes.first; node; node = node_next) { node_next = node->next; node_free_node_ex(NULL, node, false, false); @@ -2603,7 +2611,8 @@ bool BKE_node_clipboard_validate(void) /* currently only validate the ID */ if (node->id) { - ListBase *lb = which_libbase(G.main, GS(node_info->id_name)); + /* We want to search into current blend file, so using G_MAIN is valid here too. */ + ListBase *lb = which_libbase(G_MAIN, GS(node_info->id_name)); BLI_assert(lb != NULL); if (BLI_findindex(lb, node_info->id) == -1) { @@ -2684,25 +2693,25 @@ const bNodeInstanceKey NODE_INSTANCE_KEY_NONE = {0}; static bNodeInstanceKey node_hash_int_str(bNodeInstanceKey hash, const char *str) { char c; - + while ((c = *str++)) hash.value = ((hash.value << 5) + hash.value) ^ c; /* (hash * 33) ^ c */ - + /* separator '\0' character, to avoid ambiguity from concatenated strings */ hash.value = (hash.value << 5) + hash.value; /* hash * 33 */ - + return hash; } bNodeInstanceKey BKE_node_instance_key(bNodeInstanceKey parent_key, bNodeTree *ntree, bNode *node) { bNodeInstanceKey key; - + key = node_hash_int_str(parent_key, ntree->id.name + 2); - + if (node) key = node_hash_int_str(key, node->name); - + return key; } @@ -2773,10 +2782,10 @@ int BKE_node_instance_hash_size(bNodeInstanceHash *hash) void BKE_node_instance_hash_clear_tags(bNodeInstanceHash *hash) { bNodeInstanceHashIterator iter; - + NODE_INSTANCE_HASH_ITER(iter, hash) { bNodeInstanceHashEntry *value = BKE_node_instance_hash_iterator_get_value(&iter); - + value->tag = 0; } } @@ -2790,7 +2799,7 @@ void BKE_node_instance_hash_tag(bNodeInstanceHash *UNUSED(hash), void *value) bool BKE_node_instance_hash_tag_key(bNodeInstanceHash *hash, bNodeInstanceKey key) { bNodeInstanceHashEntry *entry = BKE_node_instance_hash_lookup(hash, key); - + if (entry) { entry->tag = 1; return true; @@ -2807,19 +2816,19 @@ void BKE_node_instance_hash_remove_untagged(bNodeInstanceHash *hash, bNodeInstan bNodeInstanceKey *untagged = MEM_mallocN(sizeof(bNodeInstanceKey) * BKE_node_instance_hash_size(hash), "temporary node instance key list"); bNodeInstanceHashIterator iter; int num_untagged, i; - + num_untagged = 0; NODE_INSTANCE_HASH_ITER(iter, hash) { bNodeInstanceHashEntry *value = BKE_node_instance_hash_iterator_get_value(&iter); - + if (!value->tag) untagged[num_untagged++] = BKE_node_instance_hash_iterator_get_key(&iter); } - + for (i = 0; i < num_untagged; ++i) { BKE_node_instance_hash_remove(hash, untagged[i], valfreefp); } - + MEM_freeN(untagged); } @@ -2832,9 +2841,9 @@ static int node_get_deplist_recurs(bNodeTree *ntree, bNode *node, bNode ***nsort bNode *fromnode; bNodeLink *link; int level = 0xFFF; - + node->done = true; - + /* check linked nodes */ for (link = ntree->links.first; link; link = link->next) { if (link->tonode == node) { @@ -2845,7 +2854,7 @@ static int node_get_deplist_recurs(bNodeTree *ntree, bNode *node, bNode ***nsort level = fromnode->level - 1; } } - + /* check parent node */ if (node->parent) { if (node->parent->done == 0) @@ -2853,21 +2862,21 @@ static int node_get_deplist_recurs(bNodeTree *ntree, bNode *node, bNode ***nsort if (node->parent->level <= level) level = node->parent->level - 1; } - + if (nsort) { **nsort = node; (*nsort)++; } - + return level; } void ntreeGetDependencyList(struct bNodeTree *ntree, struct bNode ***deplist, int *totnodes) { bNode *node, **nsort; - + *totnodes = 0; - + /* first clear data */ for (node = ntree->nodes.first; node; node = node->next) { node->done = false; @@ -2877,9 +2886,9 @@ void ntreeGetDependencyList(struct bNodeTree *ntree, struct bNode ***deplist, in *deplist = NULL; return; } - + nsort = *deplist = MEM_callocN((*totnodes) * sizeof(bNode *), "sorted node array"); - + /* recursive check */ for (node = ntree->nodes.first; node; node = node->next) { if (node->done == 0) { @@ -2892,12 +2901,12 @@ void ntreeGetDependencyList(struct bNodeTree *ntree, struct bNode ***deplist, in static void ntree_update_node_level(bNodeTree *ntree) { bNode *node; - + /* first clear tag */ for (node = ntree->nodes.first; node; node = node->next) { node->done = false; } - + /* recursive check */ for (node = ntree->nodes.first; node; node = node->next) { if (node->done == 0) { @@ -2911,7 +2920,7 @@ void ntreeTagUsedSockets(bNodeTree *ntree) bNode *node; bNodeSocket *sock; bNodeLink *link; - + /* first clear data */ for (node = ntree->nodes.first; node; node = node->next) { for (sock = node->inputs.first; sock; sock = sock->next) { @@ -2921,12 +2930,12 @@ void ntreeTagUsedSockets(bNodeTree *ntree) sock->flag &= ~SOCK_IN_USE; } } - + for (link = ntree->links.first; link; link = link->next) { /* link is unused if either side is disabled */ if ((link->fromsock->flag & SOCK_UNAVAIL) || (link->tosock->flag & SOCK_UNAVAIL)) continue; - + link->fromsock->flag |= SOCK_IN_USE; link->tosock->flag |= SOCK_IN_USE; } @@ -2937,7 +2946,7 @@ static void ntree_update_link_pointers(bNodeTree *ntree) bNode *node; bNodeSocket *sock; bNodeLink *link; - + /* first clear data */ for (node = ntree->nodes.first; node; node = node->next) { for (sock = node->inputs.first; sock; sock = sock->next) { @@ -2948,14 +2957,14 @@ static void ntree_update_link_pointers(bNodeTree *ntree) for (link = ntree->links.first; link; link = link->next) { link->tosock->link = link; } - + ntreeTagUsedSockets(ntree); } static void ntree_validate_links(bNodeTree *ntree) { bNodeLink *link; - + for (link = ntree->links.first; link; link = link->next) { link->flag |= NODE_LINK_VALID; if (link->fromnode && link->tonode && link->fromnode->level <= link->tonode->level) @@ -2971,7 +2980,7 @@ void ntreeVerifyNodes(struct Main *main, struct ID *id) { FOREACH_NODETREE(main, ntree, owner_id) { bNode *node; - + for (node = ntree->nodes.first; node; node = node->next) if (node->typeinfo->verifyfunc) node->typeinfo->verifyfunc(ntree, node, id); @@ -2981,31 +2990,31 @@ void ntreeVerifyNodes(struct Main *main, struct ID *id) void ntreeUpdateTree(Main *bmain, bNodeTree *ntree) { bNode *node; - + if (!ntree) return; - + /* avoid reentrant updates, can be caused by RNA update callbacks */ if (ntree->is_updating) return; ntree->is_updating = true; - + if (ntree->update & (NTREE_UPDATE_LINKS | NTREE_UPDATE_NODES)) { /* set the bNodeSocket->link pointers */ ntree_update_link_pointers(ntree); } - + /* update individual nodes */ for (node = ntree->nodes.first; node; node = node->next) { /* node tree update tags override individual node update flags */ if ((node->update & NODE_UPDATE) || (ntree->update & NTREE_UPDATE)) { if (node->typeinfo->updatefunc) node->typeinfo->updatefunc(ntree, node); - + nodeUpdateInternalLinks(ntree, node); } } - + /* generic tree update callback */ if (ntree->typeinfo->update) ntree->typeinfo->update(ntree); @@ -3014,28 +3023,28 @@ void ntreeUpdateTree(Main *bmain, bNodeTree *ntree) */ if (ntree->update & NTREE_UPDATE_GROUP) ntreeInterfaceTypeUpdate(ntree); - + /* XXX hack, should be done by depsgraph!! */ if (bmain) ntreeVerifyNodes(bmain, &ntree->id); - + if (ntree->update & (NTREE_UPDATE_LINKS | NTREE_UPDATE_NODES)) { /* node updates can change sockets or links, repeat link pointer update afterward */ ntree_update_link_pointers(ntree); - + /* update the node level from link dependencies */ ntree_update_node_level(ntree); - + /* check link validity */ ntree_validate_links(ntree); } - + /* clear update flags */ for (node = ntree->nodes.first; node; node = node->next) { node->update = 0; } ntree->update = 0; - + ntree->is_updating = false; } @@ -3045,15 +3054,15 @@ void nodeUpdate(bNodeTree *ntree, bNode *node) if (ntree->is_updating) return; ntree->is_updating = true; - + if (node->typeinfo->updatefunc) node->typeinfo->updatefunc(ntree, node); - + nodeUpdateInternalLinks(ntree, node); - + /* clear update flag */ node->update = 0; - + ntree->is_updating = false; } @@ -3061,15 +3070,15 @@ bool nodeUpdateID(bNodeTree *ntree, ID *id) { bNode *node; bool changed = false; - + if (ELEM(NULL, id, ntree)) return changed; - + /* avoid reentrant updates, can be caused by RNA update callbacks */ if (ntree->is_updating) return changed; ntree->is_updating = true; - + for (node = ntree->nodes.first; node; node = node->next) { if (node->id == id) { changed = true; @@ -3080,11 +3089,11 @@ bool nodeUpdateID(bNodeTree *ntree, ID *id) node->update = 0; } } - + for (node = ntree->nodes.first; node; node = node->next) { nodeUpdateInternalLinks(ntree, node); } - + ntree->is_updating = false; return changed; } @@ -3092,7 +3101,7 @@ bool nodeUpdateID(bNodeTree *ntree, ID *id) void nodeUpdateInternalLinks(bNodeTree *ntree, bNode *node) { BLI_freelistN(&node->internal_links); - + if (node->typeinfo && node->typeinfo->update_internal_links) node->typeinfo->update_internal_links(ntree, node); } @@ -3159,14 +3168,14 @@ void node_type_base(bNodeType *ntype, int type, const char *name, short nclass, BLI_assert(ntype->ext.srna != NULL); \ RNA_struct_blender_type_set(ntype->ext.srna, ntype); \ break; - + switch (type) { #include "NOD_static_types.h" } - + /* make sure we have a valid type (everything registered) */ BLI_assert(ntype->idname[0] != '\0'); - + ntype->type = type; BLI_strncpy(ntype->ui_name, name, sizeof(ntype->ui_name)); ntype->nclass = nclass; @@ -3193,7 +3202,7 @@ static bool unique_socket_template_identifier_check(void *arg, const char *name) { bNodeSocketTemplate *ntemp; struct {bNodeSocketTemplate *list; bNodeSocketTemplate *ntemp;} *data = arg; - + for (ntemp = data->list; ntemp->type >= 0; ++ntemp) { if (ntemp != data->ntemp) { if (STREQ(ntemp->identifier, name)) { @@ -3201,7 +3210,7 @@ static bool unique_socket_template_identifier_check(void *arg, const char *name) } } } - + return false; } @@ -3217,16 +3226,16 @@ static void unique_socket_template_identifier(bNodeSocketTemplate *list, bNodeSo void node_type_socket_templates(struct bNodeType *ntype, struct bNodeSocketTemplate *inputs, struct bNodeSocketTemplate *outputs) { bNodeSocketTemplate *ntemp; - + ntype->inputs = inputs; ntype->outputs = outputs; - + /* automatically generate unique identifiers */ if (inputs) { /* clear identifier strings (uninitialized memory) */ for (ntemp = inputs; ntemp->type >= 0; ++ntemp) ntemp->identifier[0] = '\0'; - + for (ntemp = inputs; ntemp->type >= 0; ++ntemp) { BLI_strncpy(ntemp->identifier, ntemp->name, sizeof(ntemp->identifier)); unique_socket_template_identifier(inputs, ntemp, ntemp->identifier, '_'); @@ -3236,7 +3245,7 @@ void node_type_socket_templates(struct bNodeType *ntype, struct bNodeSocketTempl /* clear identifier strings (uninitialized memory) */ for (ntemp = outputs; ntemp->type >= 0; ++ntemp) ntemp->identifier[0] = '\0'; - + for (ntemp = outputs; ntemp->type >= 0; ++ntemp) { BLI_strncpy(ntemp->identifier, ntemp->name, sizeof(ntemp->identifier)); unique_socket_template_identifier(outputs, ntemp, ntemp->identifier, '_'); @@ -3343,14 +3352,14 @@ static void register_undefined_types(void) /* Note: these types are not registered in the type hashes, * they are just used as placeholders in case the actual types are not registered. */ - + strcpy(NodeTreeTypeUndefined.idname, "NodeTreeUndefined"); strcpy(NodeTreeTypeUndefined.ui_name, "Undefined"); strcpy(NodeTreeTypeUndefined.ui_description, "Undefined Node Tree Type"); - + node_type_base_custom(&NodeTypeUndefined, "NodeUndefined", "Undefined", 0, 0); NodeTypeUndefined.poll = node_undefined_poll; - + BLI_strncpy(NodeSocketTypeUndefined.idname, "NodeSocketUndefined", sizeof(NodeSocketTypeUndefined.idname)); /* extra type info for standard socket types */ NodeSocketTypeUndefined.type = SOCK_CUSTOM; @@ -3360,7 +3369,7 @@ static void register_undefined_types(void) static void registerCompositNodes(void) { register_node_type_cmp_group(); - + register_node_type_cmp_rlayers(); register_node_type_cmp_image(); register_node_type_cmp_texture(); @@ -3368,13 +3377,13 @@ static void registerCompositNodes(void) register_node_type_cmp_rgb(); register_node_type_cmp_curve_time(); register_node_type_cmp_movieclip(); - + register_node_type_cmp_composite(); register_node_type_cmp_viewer(); register_node_type_cmp_splitviewer(); register_node_type_cmp_output_file(); register_node_type_cmp_view_levels(); - + register_node_type_cmp_curve_rgb(); register_node_type_cmp_mix_rgb(); register_node_type_cmp_hue_sat(); @@ -3385,13 +3394,13 @@ static void registerCompositNodes(void) register_node_type_cmp_zcombine(); register_node_type_cmp_colorbalance(); register_node_type_cmp_huecorrect(); - + register_node_type_cmp_normal(); register_node_type_cmp_curve_vec(); register_node_type_cmp_map_value(); register_node_type_cmp_map_range(); register_node_type_cmp_normalize(); - + register_node_type_cmp_filter(); register_node_type_cmp_blur(); register_node_type_cmp_dblur(); @@ -3402,7 +3411,7 @@ static void registerCompositNodes(void) register_node_type_cmp_despeckle(); register_node_type_cmp_defocus(); register_node_type_cmp_sunbeams(); - + register_node_type_cmp_valtorgb(); register_node_type_cmp_rgbtobw(); register_node_type_cmp_setalpha(); @@ -3417,7 +3426,7 @@ static void registerCompositNodes(void) register_node_type_cmp_sepycca(); register_node_type_cmp_combycca(); register_node_type_cmp_premulkey(); - + register_node_type_cmp_diff_matte(); register_node_type_cmp_distance_matte(); register_node_type_cmp_chroma_matte(); @@ -3458,7 +3467,7 @@ static void registerCompositNodes(void) register_node_type_cmp_cornerpin(); } -static void registerShaderNodes(void) +static void registerShaderNodes(void) { register_node_type_sh_group(); @@ -3552,7 +3561,7 @@ static void registerTextureNodes(void) { register_node_type_tex_group(); - + register_node_type_tex_math(); register_node_type_tex_mix_rgb(); register_node_type_tex_valtorgb(); @@ -3566,26 +3575,26 @@ static void registerTextureNodes(void) register_node_type_tex_distance(); register_node_type_tex_compose(); register_node_type_tex_decompose(); - + register_node_type_tex_output(); register_node_type_tex_viewer(); register_node_type_sh_script(); register_node_type_sh_tangent(); register_node_type_sh_normal_map(); register_node_type_sh_hair_info(); - + register_node_type_tex_checker(); register_node_type_tex_texture(); register_node_type_tex_bricks(); register_node_type_tex_image(); register_node_type_sh_bsdf_refraction(); register_node_type_sh_ambient_occlusion(); - + register_node_type_tex_rotate(); register_node_type_tex_translate(); register_node_type_tex_scale(); register_node_type_tex_at(); - + register_node_type_tex_proc_voronoi(); register_node_type_tex_proc_blend(); register_node_type_tex_proc_magic(); @@ -3598,7 +3607,7 @@ static void registerTextureNodes(void) register_node_type_tex_proc_distnoise(); } -void init_nodesystem(void) +void init_nodesystem(void) { nodetreetypes_hash = BLI_ghash_str_new("nodetreetypes_hash gh"); nodetypes_hash = BLI_ghash_str_new("nodetypes_hash gh"); @@ -3617,13 +3626,13 @@ void init_nodesystem(void) register_node_type_reroute(); register_node_type_group_input(); register_node_type_group_output(); - + registerCompositNodes(); registerShaderNodes(); registerTextureNodes(); } -void free_nodesystem(void) +void free_nodesystem(void) { if (nodetypes_hash) { NODE_TYPES_BEGIN(nt) diff --git a/source/blender/blenkernel/intern/object.c b/source/blender/blenkernel/intern/object.c index f55925f64f5..5ca9b9d2203 100644 --- a/source/blender/blenkernel/intern/object.c +++ b/source/blender/blenkernel/intern/object.c @@ -148,7 +148,7 @@ static ThreadMutex vparent_lock = BLI_MUTEX_INITIALIZER; void BKE_object_workob_clear(Object *workob) { memset(workob, 0, sizeof(Object)); - + workob->size[0] = workob->size[1] = workob->size[2] = 1.0f; workob->dscale[0] = workob->dscale[1] = workob->dscale[2] = 1.0f; workob->rotmode = ROT_MODE_EUL; @@ -436,9 +436,9 @@ void BKE_object_free(Object *ob) animviz_free_motionpath(ob->mpath); ob->mpath = NULL; } - + BKE_constraints_free_ex(&ob->constraints, false); - + free_partdeflect(ob->pd); BKE_rigidbody_free_object(ob); BKE_rigidbody_free_constraint(ob); @@ -478,7 +478,7 @@ bool BKE_object_is_in_editmode(const Object *ob) { if (ob->data == NULL) return false; - + if (ob->type == OB_MESH) { Mesh *me = ob->data; if (me->edit_btmesh) @@ -486,25 +486,25 @@ bool BKE_object_is_in_editmode(const Object *ob) } else if (ob->type == OB_ARMATURE) { bArmature *arm = ob->data; - + if (arm->edbo) return true; } else if (ob->type == OB_FONT) { Curve *cu = ob->data; - + if (cu->editfont) return true; } else if (ob->type == OB_MBALL) { MetaBall *mb = ob->data; - + if (mb->editelems) return true; } else if (ob->type == OB_LATTICE) { Lattice *lt = ob->data; - + if (lt->editlatt) return true; } @@ -628,9 +628,9 @@ bool BKE_object_is_visible(Object *ob, const eObjectVisibilityCheck mode) bool BKE_object_exists_check(Main *bmain, const Object *obtest) { Object *ob; - + if (obtest == NULL) return false; - + ob = bmain->object.first; while (ob) { if (ob == obtest) return true; @@ -692,12 +692,12 @@ void BKE_object_init(Object *ob) ob->col[0] = ob->col[1] = ob->col[2] = 1.0; ob->col[3] = 1.0; - + ob->size[0] = ob->size[1] = ob->size[2] = 1.0; ob->dscale[0] = ob->dscale[1] = ob->dscale[2] = 1.0; - - /* objects should default to having Euler XYZ rotations, - * but rotations default to quaternions + + /* objects should default to having Euler XYZ rotations, + * but rotations default to quaternions */ ob->rotmode = ROT_MODE_EUL; @@ -709,7 +709,7 @@ void BKE_object_init(Object *ob) /* rotation locks should be 4D for 4 component rotations by default... */ ob->protectflag = OB_LOCK_ROT4D; - + unit_m4(ob->constinv); unit_m4(ob->parentinv); unit_m4(ob->obmat); @@ -725,7 +725,7 @@ void BKE_object_init(Object *ob) ob->trackflag = OB_POSY; ob->upflag = OB_POSZ; } - + ob->dupon = 1; ob->dupoff = 0; ob->dupsta = 1; ob->dupend = 100; ob->dupfacesca = 1.0; @@ -739,7 +739,7 @@ void BKE_object_init(Object *ob) ob->fluidsimSettings = NULL; BLI_listbase_clear(&ob->pc_ids); - + /* Animation Visualization defaults */ animviz_settings_init(&ob->avs); @@ -830,9 +830,9 @@ Object *BKE_object_add_from( SoftBody *copy_softbody(const SoftBody *sb, const int flag) { SoftBody *sbn; - + if (sb == NULL) return(NULL); - + sbn = MEM_dupallocN(sb); if ((flag & LIB_ID_COPY_CACHES) == 0) { @@ -858,10 +858,10 @@ SoftBody *copy_softbody(const SoftBody *sb, const int flag) if (sb->bspring) sbn->bspring = MEM_dupallocN(sb->bspring); } - + sbn->keys = NULL; sbn->totkey = sbn->totpointkey = 0; - + sbn->scratch = NULL; sbn->pointcache = BKE_ptcache_copy_list(&sbn->ptcaches, &sb->ptcaches, flag); @@ -874,38 +874,9 @@ SoftBody *copy_softbody(const SoftBody *sb, const int flag) ParticleSystem *BKE_object_copy_particlesystem(ParticleSystem *psys, const int flag) { - ParticleSystem *psysn; - ParticleData *pa; - int p; - - psysn = MEM_dupallocN(psys); - psysn->particles = MEM_dupallocN(psys->particles); - psysn->child = MEM_dupallocN(psys->child); - - if (psys->part->type == PART_HAIR) { - for (p = 0, pa = psysn->particles; p < psysn->totpart; p++, pa++) - pa->hair = MEM_dupallocN(pa->hair); - } - - if (psysn->particles && (psysn->particles->keys || psysn->particles->boid)) { - ParticleKey *key = psysn->particles->keys; - BoidParticle *boid = psysn->particles->boid; - - if (key) - key = MEM_dupallocN(key); - - if (boid) - boid = MEM_dupallocN(boid); - - for (p = 0, pa = psysn->particles; p < psysn->totpart; p++, pa++) { - if (boid) - pa->boid = boid++; - if (key) { - pa->keys = key; - key += pa->totkey; - } - } - } + ParticleSystem *psysn = MEM_dupallocN(psys); + + psys_copy_particles(psysn, psys); if (psys->clmd) { psysn->clmd = (ClothModifierData *)modifier_new(eModifierType_Cloth); @@ -923,10 +894,10 @@ ParticleSystem *BKE_object_copy_particlesystem(ParticleSystem *psys, const int f psysn->tree = NULL; psysn->bvhtree = NULL; psysn->batch_cache = NULL; - + BLI_listbase_clear(&psysn->pathcachebufs); BLI_listbase_clear(&psysn->childcachebufs); - + psysn->pointcache = BKE_ptcache_copy_list(&psysn->ptcaches, &psys->ptcaches, flag); /* XXX - from reading existing code this seems correct but intended usage of @@ -975,7 +946,7 @@ void BKE_object_copy_particlesystems(Object *ob_dst, const Object *ob_src, const } else if (md->type == eModifierType_Smoke) { SmokeModifierData *smd = (SmokeModifierData *) md; - + if (smd->type == MOD_SMOKE_TYPE_FLOW) { if (smd->flow) { if (smd->flow->psys == psys) @@ -998,31 +969,31 @@ void BKE_object_copy_softbody(Object *ob_dst, const Object *ob_src) static void copy_object_pose(Object *obn, const Object *ob, const int flag) { bPoseChannel *chan; - + /* note: need to clear obn->pose pointer first, so that BKE_pose_copy_data works (otherwise there's a crash) */ obn->pose = NULL; BKE_pose_copy_data_ex(&obn->pose, ob->pose, flag, true); /* true = copy constraints */ for (chan = obn->pose->chanbase.first; chan; chan = chan->next) { bConstraint *con; - + chan->flag &= ~(POSE_LOC | POSE_ROT | POSE_SIZE); - + /* XXX Remapping object pointing onto itself should be handled by generic BKE_library_remap stuff, but... * the flush_constraint_targets callback am not sure about, so will delay that for now. */ for (con = chan->constraints.first; con; con = con->next) { const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con); ListBase targets = {NULL, NULL}; bConstraintTarget *ct; - + if (cti && cti->get_constraint_targets) { cti->get_constraint_targets(con, &targets); - + for (ct = targets.first; ct; ct = ct->next) { if (ct->tar == ob) ct->tar = obn; } - + if (cti->flush_constraint_targets) cti->flush_constraint_targets(con, &targets, 0); } @@ -1191,11 +1162,11 @@ void BKE_object_copy_data(Main *UNUSED(bmain), Object *ob_dst, const Object *ob_ } if (ob_src->iuser) ob_dst->iuser = MEM_dupallocN(ob_src->iuser); - + if (ob_src->bb) ob_dst->bb = MEM_dupallocN(ob_src->bb); - + BLI_listbase_clear(&ob_dst->modifiers); - + for (md = ob_src->modifiers.first; md; md = md->next) { ModifierData *nmd = modifier_new(md->type); BLI_strncpy(nmd->name, md->name, sizeof(nmd->name)); @@ -1227,7 +1198,7 @@ void BKE_object_copy_data(Main *UNUSED(bmain), Object *ob_dst, const Object *ob_ ob_dst->rigidbody_constraint = BKE_rigidbody_copy_constraint(ob_src, flag_subdata); BKE_object_copy_particlesystems(ob_dst, ob_src, flag_subdata); - + ob_dst->derivedDeform = NULL; ob_dst->derivedFinal = NULL; @@ -1239,7 +1210,7 @@ void BKE_object_copy_data(Main *UNUSED(bmain), Object *ob_dst, const Object *ob_ ob_dst->mpath = animviz_copy_motionpath(ob_src->mpath); copy_object_lod(ob_dst, ob_src, flag_subdata); - + /* Do not copy runtime curve data. */ ob_dst->curve_cache = NULL; @@ -1335,34 +1306,34 @@ static void armature_set_id_extern(Object *ob) bArmature *arm = ob->data; bPoseChannel *pchan; unsigned int lay = arm->layer_protected; - + for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) { if (!(pchan->bone->layer & lay)) id_lib_extern((ID *)pchan->custom); } - + } void BKE_object_copy_proxy_drivers(Object *ob, Object *target) { if ((target->adt) && (target->adt->drivers.first)) { FCurve *fcu; - + /* add new animdata block */ if (!ob->adt) ob->adt = BKE_animdata_add_id(&ob->id); - + /* make a copy of all the drivers (for now), then correct any links that need fixing */ free_fcurves(&ob->adt->drivers); copy_fcurves(&ob->adt->drivers, &target->adt->drivers); - + for (fcu = ob->adt->drivers.first; fcu; fcu = fcu->next) { ChannelDriver *driver = fcu->driver; DriverVar *dvar; - + for (dvar = driver->variables.first; dvar; dvar = dvar->next) { /* all drivers */ - DRIVER_TARGETS_LOOPER(dvar) + DRIVER_TARGETS_LOOPER(dvar) { if (dtar->id) { if ((Object *)dtar->id == target) @@ -1393,14 +1364,14 @@ void BKE_object_make_proxy(Object *ob, Object *target, Object *cob) printf("cannot make proxy\n"); return; } - + ob->proxy = target; ob->proxy_group = cob; id_lib_extern(&target->id); - + DEG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME); DEG_id_tag_update(&target->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME); - + /* copy transform * - cob means this proxy comes from a collection, just apply the matrix * so the object wont move from its dupli-transform. @@ -1422,13 +1393,13 @@ void BKE_object_make_proxy(Object *ob, Object *target, Object *cob) ob->parent = target->parent; /* libdata */ copy_m4_m4(ob->parentinv, target->parentinv); } - + /* copy animdata stuff - drivers only for now... */ BKE_object_copy_proxy_drivers(ob, target); /* skip constraints? */ /* FIXME: this is considered by many as a bug */ - + /* set object type and link to data */ ob->type = target->type; ob->data = target->data; @@ -1445,24 +1416,24 @@ void BKE_object_make_proxy(Object *ob, Object *target, Object *cob) ob->matbits = NULL; if ((target->totcol) && (target->mat) && OB_TYPE_SUPPORT_MATERIAL(ob->type)) { int i; - + ob->actcol = target->actcol; ob->totcol = target->totcol; - + ob->mat = MEM_dupallocN(target->mat); ob->matbits = MEM_dupallocN(target->matbits); for (i = 0; i < target->totcol; i++) { /* don't need to run test_object_materials since we know this object is new and not used elsewhere */ - id_us_plus((ID *)ob->mat[i]); + id_us_plus((ID *)ob->mat[i]); } } - + /* type conversions */ if (target->type == OB_ARMATURE) { copy_object_pose(ob, target, 0); /* data copy, object pointers in constraints */ BKE_pose_rest(ob->pose); /* clear all transforms in channels */ BKE_pose_rebuild(ob, ob->data); /* set all internal links */ - + armature_set_id_extern(ob); } else if (target->type == OB_EMPTY) { @@ -1546,7 +1517,7 @@ void BKE_object_scale_to_mat3(Object *ob, float mat[3][3]) void BKE_object_rot_to_mat3(Object *ob, float mat[3][3], bool use_drot) { float rmat[3][3], dmat[3][3]; - + /* 'dmat' is the delta-rotation matrix, which will get (pre)multiplied * with the rotation matrix to yield the appropriate rotation */ @@ -1565,14 +1536,14 @@ void BKE_object_rot_to_mat3(Object *ob, float mat[3][3], bool use_drot) else { /* quats are normalized before use to eliminate scaling issues */ float tquat[4]; - + normalize_qt_qt(tquat, ob->quat); quat_to_mat3(rmat, tquat); - + normalize_qt_qt(tquat, ob->dquat); quat_to_mat3(dmat, tquat); } - + /* combine these rotations */ if (use_drot) mul_m3_m3m3(mat, dmat, rmat); @@ -1696,7 +1667,7 @@ void BKE_object_to_mat3(Object *ob, float mat[3][3]) /* no parent */ float smat[3][3]; float rmat[3][3]; /*float q1[4];*/ - + /* size */ BKE_object_scale_to_mat3(ob, smat); @@ -1708,9 +1679,9 @@ void BKE_object_to_mat3(Object *ob, float mat[3][3]) /* no parent */ void BKE_object_to_mat4(Object *ob, float mat[4][4]) { float tmat[3][3]; - + BKE_object_to_mat3(ob, tmat); - + copy_m4_m3(mat, tmat); add_v3_v3v3(mat[3], ob->loc, ob->dloc); @@ -1760,7 +1731,7 @@ static bool ob_parcurve(Depsgraph *depsgraph, Scene *UNUSED(scene), Object *ob, /* catch exceptions: curve paths used as a duplicator */ if (enable_cu_speed) { /* ctime is now a proper var setting of Curve which gets set by Animato like any other var that's animated, - * but this will only work if it actually is animated... + * but this will only work if it actually is animated... * * we divide the curvetime calculated in the previous step by the length of the path, to get a time * factor, which then gets clamped to lie within 0.0 - 1.0 range @@ -1784,10 +1755,10 @@ static bool ob_parcurve(Depsgraph *depsgraph, Scene *UNUSED(scene), Object *ob, if (cu->pathlen) { ctime /= cu->pathlen; } - + CLAMP(ctime, 0.0f, 1.0f); } - + unit_m4(mat); /* vec: 4 items! */ @@ -1797,7 +1768,7 @@ static bool ob_parcurve(Depsgraph *depsgraph, Scene *UNUSED(scene), Object *ob, #if 0 float si, q[4]; vec_to_quat(quat, dir, ob->trackflag, ob->upflag); - + /* the tilt */ normalize_v3(dir); q[0] = cosf(0.5 * vec[3]); @@ -1812,7 +1783,7 @@ static bool ob_parcurve(Depsgraph *depsgraph, Scene *UNUSED(scene), Object *ob, normalize_qt(quat); quat_to_mat4(mat, quat); } - + if (cu->flag & CU_PATH_RADIUS) { float tmat[4][4], rmat[4][4]; scale_m4_fl(tmat, radius); @@ -1821,22 +1792,22 @@ static bool ob_parcurve(Depsgraph *depsgraph, Scene *UNUSED(scene), Object *ob, } copy_v3_v3(mat[3], vec); - + } return true; } static void ob_parbone(Object *ob, Object *par, float mat[4][4]) -{ +{ bPoseChannel *pchan; float vec[3]; - + if (par->type != OB_ARMATURE) { unit_m4(mat); return; } - + /* Make sure the bone is still valid */ pchan = BKE_pose_channel_find_name(par->pose, ob->parsubstr); if (!pchan || !pchan->bone) { @@ -1864,14 +1835,14 @@ static void ob_parbone(Object *ob, Object *par, float mat[4][4]) static void give_parvert(Object *par, int nr, float vec[3]) { zero_v3(vec); - + if (par->type == OB_MESH) { Mesh *me = par->data; BMEditMesh *em = me->edit_btmesh; DerivedMesh *dm; dm = (em) ? em->derivedFinal : par->derivedFinal; - + if (dm) { int count = 0; int numVerts = dm->getNumVerts(dm); @@ -2047,16 +2018,16 @@ void BKE_object_get_parent_matrix(Depsgraph *depsgraph, Scene *scene, Object *ob ok = 1; } } - + if (ok) mul_m4_m4m4(parentmat, par->obmat, tmat); else copy_m4_m4(parentmat, par->obmat); - + break; case PARBONE: ob_parbone(ob, par, tmat); mul_m4_m4m4(parentmat, par->obmat, tmat); break; - + case PARVERT1: unit_m4(parentmat); give_parvert(par, ob->par1, vec); @@ -2064,10 +2035,10 @@ void BKE_object_get_parent_matrix(Depsgraph *depsgraph, Scene *scene, Object *ob break; case PARVERT3: ob_parvert3(ob, par, tmat); - + mul_m4_m4m4(parentmat, par->obmat, tmat); break; - + case PARSKEL: copy_m4_m4(parentmat, par->obmat); break; @@ -2085,22 +2056,22 @@ static void solve_parenting(Depsgraph *depsgraph, float totmat[4][4]; float tmat[4][4]; float locmat[4][4]; - + BKE_object_to_mat4(ob, locmat); - + if (ob->partype & PARSLOW) copy_m4_m4(slowmat, obmat); BKE_object_get_parent_matrix(depsgraph, scene, ob, par, totmat); - + /* total */ mul_m4_m4m4(tmat, totmat, ob->parentinv); mul_m4_m4m4(obmat, tmat, locmat); - + if (r_originmat) { /* usable originmat */ copy_m3_m4(r_originmat, tmat); } - + /* origin, for help line */ if (set_origin) { if ((ob->partype & PARTYPE) == PARSKEL) { @@ -2138,18 +2109,18 @@ void BKE_object_where_is_calc_time_ex( RigidBodyWorld *rbw, float r_originmat[3][3]) { if (ob == NULL) return; - + /* execute drivers only, as animation has already been done */ BKE_animsys_evaluate_animdata(depsgraph, scene, &ob->id, ob->adt, ctime, ADT_RECALC_DRIVERS); - + if (ob->parent) { Object *par = ob->parent; float slowmat[4][4]; - + /* calculate parent matrix */ solve_parenting(depsgraph, scene, ob, par, ob->obmat, slowmat, r_originmat, true); - - /* "slow parent" is definitely not threadsafe, and may also give bad results jumping around + + /* "slow parent" is definitely not threadsafe, and may also give bad results jumping around * An old-fashioned hack which probably doesn't really cut it anymore */ if (ob->partype & PARSLOW) { @@ -2165,7 +2136,7 @@ void BKE_object_where_is_calc_time_ex( rbw = rbw ? rbw : scene->rigidbody_world; /* read values pushed into RBO from sim/cache... */ BKE_rigidbody_sync_transforms(rbw, ob, ctime); - + /* solve constraints */ if (ob->constraints.first && !(ob->transflag & OB_NO_CONSTRAINTS)) { bConstraintOb *cob; @@ -2173,7 +2144,7 @@ void BKE_object_where_is_calc_time_ex( BKE_constraints_solve(depsgraph, &ob->constraints, cob, ctime); BKE_constraints_clear_evalob(cob); } - + /* set negative scale flag in object */ if (is_negative_m4(ob->obmat)) ob->transflag |= OB_NEG_SCALE; else ob->transflag &= ~OB_NEG_SCALE; @@ -2195,9 +2166,9 @@ void BKE_object_where_is_calc_mat4(Depsgraph *depsgraph, Scene *scene, Object *o float slowmat[4][4]; Object *par = ob->parent; - + solve_parenting(depsgraph, scene, ob, par, obmat, slowmat, NULL, false); - + if (ob->partype & PARSLOW) where_is_object_parslow(ob, obmat, slowmat); } @@ -2227,7 +2198,7 @@ void BKE_object_workob_calc_parent(Depsgraph *depsgraph, Scene *scene, Object *o { Object *ob_eval = DEG_get_evaluated_object(depsgraph, ob); BKE_object_workob_clear(workob); - + unit_m4(workob->obmat); unit_m4(workob->parentinv); unit_m4(workob->constinv); @@ -2237,7 +2208,7 @@ void BKE_object_workob_calc_parent(Depsgraph *depsgraph, Scene *scene, Object *o workob->trackflag = ob_eval->trackflag; workob->upflag = ob_eval->upflag; - + workob->partype = ob_eval->partype; workob->par1 = ob_eval->par1; workob->par2 = ob_eval->par2; @@ -2303,7 +2274,7 @@ BoundBox *BKE_boundbox_alloc_unit(void) bb = MEM_callocN(sizeof(BoundBox), "OB-BoundBox"); BKE_boundbox_init_from_minmax(bb, min, max); - + return bb; } @@ -2311,7 +2282,7 @@ void BKE_boundbox_init_from_minmax(BoundBox *bb, const float min[3], const float { bb->vec[0][0] = bb->vec[1][0] = bb->vec[2][0] = bb->vec[3][0] = min[0]; bb->vec[4][0] = bb->vec[5][0] = bb->vec[6][0] = bb->vec[7][0] = max[0]; - + bb->vec[0][1] = bb->vec[1][1] = bb->vec[4][1] = bb->vec[5][1] = min[1]; bb->vec[2][1] = bb->vec[3][1] = bb->vec[6][1] = bb->vec[7][1] = max[1]; @@ -2346,7 +2317,7 @@ void BKE_boundbox_minmax(const BoundBox *bb, float obmat[4][4], float r_min[3], BoundBox *BKE_object_boundbox_get(Object *ob) { BoundBox *bb = NULL; - + if (ob->type == OB_MESH) { bb = BKE_mesh_boundbox_get(ob); } @@ -2378,13 +2349,13 @@ void BKE_object_boundbox_flag(Object *ob, int flag, const bool set) void BKE_object_dimensions_get(Object *ob, float vec[3]) { BoundBox *bb = NULL; - + bb = BKE_object_boundbox_get(ob); if (bb) { float scale[3]; - + mat4_to_size(scale, ob->obmat); - + vec[0] = fabsf(scale[0]) * (bb->vec[4][0] - bb->vec[0][0]); vec[1] = fabsf(scale[1]) * (bb->vec[2][1] - bb->vec[0][1]); vec[2] = fabsf(scale[2]) * (bb->vec[1][2] - bb->vec[0][2]); @@ -2397,17 +2368,17 @@ void BKE_object_dimensions_get(Object *ob, float vec[3]) void BKE_object_dimensions_set(Object *ob, const float value[3]) { BoundBox *bb = NULL; - + bb = BKE_object_boundbox_get(ob); if (bb) { float scale[3], len[3]; - + mat4_to_size(scale, ob->obmat); - + len[0] = bb->vec[4][0] - bb->vec[0][0]; len[1] = bb->vec[2][1] - bb->vec[0][1]; len[2] = bb->vec[1][2] - bb->vec[0][2]; - + if (len[0] > 0.f) ob->size[0] = value[0] / len[0]; if (len[1] > 0.f) ob->size[1] = value[1] / len[1]; if (len[2] > 0.f) ob->size[2] = value[2] / len[2]; @@ -2419,7 +2390,7 @@ void BKE_object_minmax(Object *ob, float min_r[3], float max_r[3], const bool us BoundBox bb; float vec[3]; bool changed = false; - + switch (ob->type) { case OB_CURVE: case OB_FONT: @@ -2767,7 +2738,7 @@ void BKE_object_handle_update_ex(Depsgraph *depsgraph, object_handle_update_proxy(depsgraph, scene, ob, do_proxy_update); } -/* WARNING: "scene" here may not be the scene object actually resides in. +/* WARNING: "scene" here may not be the scene object actually resides in. * When dealing with background-sets, "scene" is actually the active scene. * e.g. "scene" <-- set 1 <-- set 2 ("ob" lives here) <-- set 3 <-- ... <-- set n * rigid bodies depend on their world so use BKE_object_handle_update_ex() to also pass along the corrent rigid body world @@ -2812,10 +2783,10 @@ void BKE_object_sculpt_modifiers_changed(Object *ob) int BKE_object_obdata_texspace_get(Object *ob, short **r_texflag, float **r_loc, float **r_size, float **r_rot) { - + if (ob->data == NULL) return 0; - + switch (GS(((ID *)ob->data)->name)) { case ID_ME: { @@ -2919,7 +2890,7 @@ static int pc_cmp(const void *a, const void *b) else return 0; } -int BKE_object_insert_ptcache(Object *ob) +int BKE_object_insert_ptcache(Object *ob) { LinkData *link = NULL; int i = 0; @@ -2944,18 +2915,18 @@ static int pc_findindex(ListBase *listbase, int index) { LinkData *link = NULL; int number = 0; - + if (listbase == NULL) return -1; - + link = listbase->first; while (link) { if (GET_INT_FROM_POINTER(link->data) == index) return number; - + number++; link = link->next; } - + return -1; } @@ -2969,7 +2940,7 @@ void BKE_object_delete_ptcache(Object *ob, int index) /* shape key utility function */ /************************* Mesh ************************/ -static KeyBlock *insert_meshkey(Object *ob, const char *name, const bool from_mix) +static KeyBlock *insert_meshkey(Main *bmain, Object *ob, const char *name, const bool from_mix) { Mesh *me = ob->data; Key *key = me->key; @@ -2977,7 +2948,7 @@ static KeyBlock *insert_meshkey(Object *ob, const char *name, const bool from_mi int newkey = 0; if (key == NULL) { - key = me->key = BKE_key_add((ID *)me); + key = me->key = BKE_key_add(bmain, (ID *)me); key->type = KEY_RELATIVE; newkey = 1; } @@ -3001,7 +2972,7 @@ static KeyBlock *insert_meshkey(Object *ob, const char *name, const bool from_mi return kb; } /************************* Lattice ************************/ -static KeyBlock *insert_lattkey(Object *ob, const char *name, const bool from_mix) +static KeyBlock *insert_lattkey(Main *bmain, Object *ob, const char *name, const bool from_mix) { Lattice *lt = ob->data; Key *key = lt->key; @@ -3009,7 +2980,7 @@ static KeyBlock *insert_lattkey(Object *ob, const char *name, const bool from_mi int newkey = 0; if (key == NULL) { - key = lt->key = BKE_key_add((ID *)lt); + key = lt->key = BKE_key_add(bmain, (ID *)lt); key->type = KEY_RELATIVE; newkey = 1; } @@ -3039,7 +3010,7 @@ static KeyBlock *insert_lattkey(Object *ob, const char *name, const bool from_mi return kb; } /************************* Curve ************************/ -static KeyBlock *insert_curvekey(Object *ob, const char *name, const bool from_mix) +static KeyBlock *insert_curvekey(Main *bmain, Object *ob, const char *name, const bool from_mix) { Curve *cu = ob->data; Key *key = cu->key; @@ -3048,7 +3019,7 @@ static KeyBlock *insert_curvekey(Object *ob, const char *name, const bool from_m int newkey = 0; if (key == NULL) { - key = cu->key = BKE_key_add((ID *)cu); + key = cu->key = BKE_key_add(bmain, (ID *)cu); key->type = KEY_RELATIVE; newkey = 1; } @@ -3079,16 +3050,16 @@ static KeyBlock *insert_curvekey(Object *ob, const char *name, const bool from_m return kb; } -KeyBlock *BKE_object_shapekey_insert(Object *ob, const char *name, const bool from_mix) -{ +KeyBlock *BKE_object_shapekey_insert(Main *bmain, Object *ob, const char *name, const bool from_mix) +{ switch (ob->type) { case OB_MESH: - return insert_meshkey(ob, name, from_mix); + return insert_meshkey(bmain, ob, name, from_mix); case OB_CURVE: case OB_SURF: - return insert_curvekey(ob, name, from_mix); + return insert_curvekey(bmain, ob, name, from_mix); case OB_LATTICE: - return insert_lattkey(ob, name, from_mix); + return insert_lattkey(bmain, ob, name, from_mix); default: return NULL; } diff --git a/source/blender/blenkernel/intern/object_deform.c b/source/blender/blenkernel/intern/object_deform.c index fb2e824b299..2de81864512 100644 --- a/source/blender/blenkernel/intern/object_deform.c +++ b/source/blender/blenkernel/intern/object_deform.c @@ -133,7 +133,7 @@ bDeformGroup *BKE_object_defgroup_add_name(Object *ob, const char *name) /** * Add a vgroup of default name to object. *Does not* handle MDeformVert data at all! */ -bDeformGroup *BKE_object_defgroup_add(Object *ob) +bDeformGroup *BKE_object_defgroup_add(Object *ob) { return BKE_object_defgroup_add_name(ob, DATA_("Group")); } diff --git a/source/blender/blenkernel/intern/object_dupli.c b/source/blender/blenkernel/intern/object_dupli.c index e9b1e79dc67..b7748039f62 100644 --- a/source/blender/blenkernel/intern/object_dupli.c +++ b/source/blender/blenkernel/intern/object_dupli.c @@ -124,7 +124,7 @@ static void init_context( static void copy_dupli_context(DupliContext *r_ctx, const DupliContext *ctx, Object *ob, float mat[4][4], int index) { *r_ctx = *ctx; - + /* XXX annoying, previously was done by passing an ID* argument, this at least is more explicit */ if (ctx->gen->type == OB_DUPLICOLLECTION) r_ctx->collection = ctx->object->dup_group; @@ -233,13 +233,12 @@ static void make_child_duplis(const DupliContext *ctx, void *userdata, MakeChild Object *parent = ctx->object; if (ctx->collection) { - int collectionid = 0; - FOREACH_COLLECTION_BASE_RECURSIVE_BEGIN(ctx->collection, base) + eEvaluationMode mode = DEG_get_mode(ctx->depsgraph); + FOREACH_COLLECTION_VISIBLE_OBJECT_RECURSIVE_BEGIN(ctx->collection, ob, mode) { - Object *ob = base->object; - if ((base->flag & BASE_VISIBLED) && ob != ctx->obedit && is_child(ob, parent)) { + if ((ob != ctx->obedit) && is_child(ob, parent)) { DupliContext pctx; - copy_dupli_context(&pctx, ctx, ctx->object, NULL, collectionid); + copy_dupli_context(&pctx, ctx, ctx->object, NULL, _base_id); /* mballs have a different dupli handling */ if (ob->type != OB_MBALL) { @@ -247,9 +246,8 @@ static void make_child_duplis(const DupliContext *ctx, void *userdata, MakeChild } make_child_duplis_cb(&pctx, userdata, ob); } - collectionid++; } - FOREACH_COLLECTION_BASE_RECURSIVE_END + FOREACH_COLLECTION_VISIBLE_OBJECT_RECURSIVE_END; } else { int baseid = 0; @@ -278,9 +276,7 @@ static void make_duplis_collection(const DupliContext *ctx) { Object *ob = ctx->object; Collection *collection; - Base *base; float collection_mat[4][4]; - int id; if (ob->dup_group == NULL) return; collection = ob->dup_group; @@ -291,20 +287,22 @@ static void make_duplis_collection(const DupliContext *ctx) mul_m4_m4m4(collection_mat, ob->obmat, collection_mat); /* don't access 'ob->obmat' from now on. */ - const ListBase dup_collection_objects = BKE_collection_object_cache_get(collection); - for (base = dup_collection_objects.first, id = 0; base; base = base->next, id++) { - if (base->object != ob && (base->flag & BASE_VISIBLED)) { + eEvaluationMode mode = DEG_get_mode(ctx->depsgraph); + FOREACH_COLLECTION_VISIBLE_OBJECT_RECURSIVE_BEGIN(collection, cob, mode) + { + if (cob != ob) { float mat[4][4]; /* collection dupli offset, should apply after everything else */ - mul_m4_m4m4(mat, collection_mat, base->object->obmat); + mul_m4_m4m4(mat, collection_mat, cob->obmat); - make_dupli(ctx, base->object, mat, id); + make_dupli(ctx, cob, mat, _base_id); /* recursion */ - make_recursive_duplis(ctx, base->object, collection_mat, id); + make_recursive_duplis(ctx, cob, collection_mat, _base_id); } } + FOREACH_COLLECTION_VISIBLE_OBJECT_RECURSIVE_END; } static const DupliGenerator gen_dupli_collection = { @@ -540,7 +538,7 @@ static const DupliGenerator gen_dupli_verts = { }; /* OB_DUPLIVERTS - FONT */ -static Object *find_family_object(const char *family, size_t family_len, unsigned int ch, GHash *family_gh) +static Object *find_family_object(Main *bmain, const char *family, size_t family_len, unsigned int ch, GHash *family_gh) { Object **ob_pt; Object *ob; @@ -557,7 +555,7 @@ static Object *find_family_object(const char *family, size_t family_len, unsigne ch_utf8[ch_utf8_len] = '\0'; ch_utf8_len += 1; /* compare with null terminator */ - for (ob = G.main->object.first; ob; ob = ob->id.next) { + for (ob = bmain->object.first; ob; ob = ob->id.next) { if (STREQLEN(ob->id.name + 2 + family_len, ch_utf8, ch_utf8_len)) { if (STREQLEN(ob->id.name + 2, family, family_len)) { break; @@ -593,7 +591,7 @@ static void make_duplis_font(const DupliContext *ctx) /* in par the family name is stored, use this to find the other objects */ - BKE_vfont_to_curve_ex(G.main, par, par->data, FO_DUPLI, NULL, + BKE_vfont_to_curve_ex(par, par->data, FO_DUPLI, NULL, &text, &text_len, &text_free, &chartransdata); if (text == NULL || chartransdata == NULL) { @@ -614,7 +612,9 @@ static void make_duplis_font(const DupliContext *ctx) /* advance matching BLI_strncpy_wchar_from_utf8 */ for (a = 0; a < text_len; a++, ct++) { - ob = find_family_object(cu->family, family_len, (unsigned int)text[a], family_gh); + /* XXX That G.main is *really* ugly, but not sure what to do here... + * Definitively don't think it would be safe to put back Main *bmain pointer in DupliContext as done in 2.7x? */ + ob = find_family_object(G.main, cu->family, family_len, (unsigned int)text[a], family_gh); if (ob) { vec[0] = fsize * (ct->xof - xof); vec[1] = fsize * (ct->yof - yof); @@ -820,7 +820,8 @@ static void make_duplis_particle_system(const DupliContext *ctx, ParticleSystem { Scene *scene = ctx->scene; Object *par = ctx->object; - bool for_render = DEG_get_mode(ctx->depsgraph) == DAG_EVAL_RENDER; + eEvaluationMode mode = DEG_get_mode(ctx->depsgraph); + bool for_render = mode == DAG_EVAL_RENDER; bool use_texcoords = for_render; Object *ob = NULL, **oblist = NULL, obcopy, *obcopylist = NULL; @@ -836,6 +837,7 @@ static void make_duplis_particle_system(const DupliContext *ctx, ParticleSystem float (*obmat)[4]; int a, b, hair = 0; int totpart, totchild, totcollection = 0 /*, pa_num */; + RNG *rng; int no_draw_flag = PARS_UNEXIST; @@ -846,7 +848,7 @@ static void make_duplis_particle_system(const DupliContext *ctx, ParticleSystem if (part == NULL) return; - if (!psys_check_enabled(par, psys, (DEG_get_mode(ctx->depsgraph) == DAG_EVAL_RENDER))) + if (!psys_check_enabled(par, psys, for_render)) return; if (!for_render) @@ -857,7 +859,7 @@ static void make_duplis_particle_system(const DupliContext *ctx, ParticleSystem totpart = psys->totpart; totchild = psys->totchild; - BLI_srandom((unsigned int)(31415926 + psys->seed)); + rng = BLI_rng_new_srandom(31415926u + (unsigned int)psys->seed); if ((for_render || part->draw_as == PART_DRAW_REND) && ELEM(part->ren_as, PART_DRAW_OB, PART_DRAW_GR)) { ParticleSimulationData sim = {NULL}; @@ -910,12 +912,12 @@ static void make_duplis_particle_system(const DupliContext *ctx, ParticleSystem totcollection += dw->count; } else { - FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(part->dup_group, object) + FOREACH_COLLECTION_VISIBLE_OBJECT_RECURSIVE_BEGIN(part->dup_group, object, mode) { (void) object; totcollection++; } - FOREACH_COLLECTION_OBJECT_RECURSIVE_END; + FOREACH_COLLECTION_VISIBLE_OBJECT_RECURSIVE_END; } /* we also copy the actual objects to restore afterwards, since @@ -935,7 +937,7 @@ static void make_duplis_particle_system(const DupliContext *ctx, ParticleSystem } else { a = 0; - FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(part->dup_group, object) + FOREACH_COLLECTION_VISIBLE_OBJECT_RECURSIVE_BEGIN(part->dup_group, object, mode) { oblist[a] = object; obcopylist[a] = *object; @@ -945,7 +947,7 @@ static void make_duplis_particle_system(const DupliContext *ctx, ParticleSystem continue; } } - FOREACH_COLLECTION_OBJECT_RECURSIVE_END; + FOREACH_COLLECTION_VISIBLE_OBJECT_RECURSIVE_END; } } else { @@ -992,7 +994,7 @@ static void make_duplis_particle_system(const DupliContext *ctx, ParticleSystem /* for collections, pick the object based on settings */ if (part->draw & PART_DRAW_RAND_GR) - b = BLI_rand() % totcollection; + b = BLI_rng_get_int(rng) % totcollection; else b = a % totcollection; @@ -1035,7 +1037,7 @@ static void make_duplis_particle_system(const DupliContext *ctx, ParticleSystem if (part->ren_as == PART_DRAW_GR && psys->part->draw & PART_DRAW_WHOLE_GR) { b = 0; - FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(part->dup_group, object) + FOREACH_COLLECTION_VISIBLE_OBJECT_RECURSIVE_BEGIN(part->dup_group, object, mode) { copy_m4_m4(tmat, oblist[b]->obmat); @@ -1060,7 +1062,7 @@ static void make_duplis_particle_system(const DupliContext *ctx, ParticleSystem b++; } - FOREACH_COLLECTION_OBJECT_RECURSIVE_END; + FOREACH_COLLECTION_VISIBLE_OBJECT_RECURSIVE_END; } else { /* to give ipos in object correct offset */ @@ -1131,6 +1133,8 @@ static void make_duplis_particle_system(const DupliContext *ctx, ParticleSystem end_latt_deform(psys->lattice_deform_data); psys->lattice_deform_data = NULL; } + + BLI_rng_free(rng); } static void make_duplis_particles(const DupliContext *ctx) @@ -1249,7 +1253,7 @@ DupliApplyData *duplilist_apply(Depsgraph *depsgraph, Object *ob, Scene *scene, { DupliApplyData *apply_data = NULL; int num_objects = BLI_listbase_count(duplilist); - + if (num_objects > 0) { DupliObject *dob; int i; @@ -1270,7 +1274,7 @@ DupliApplyData *duplilist_apply(Depsgraph *depsgraph, Object *ob, Scene *scene, /* copy obmat from duplis */ copy_m4_m4(apply_data->extra[i].obmat, dob->ob->obmat); copy_m4_m4(dob->ob->obmat, dob->mat); - + /* copy layers from the main duplicator object */ apply_data->extra[i].lay = dob->ob->lay; dob->ob->lay = ob->lay; @@ -1290,7 +1294,7 @@ void duplilist_restore(ListBase *duplilist, DupliApplyData *apply_data) for (dob = duplilist->last, i = apply_data->num_objects - 1; dob; dob = dob->prev, --i) { copy_m4_m4(dob->ob->obmat, apply_data->extra[i].obmat); dob->ob->transflag &= ~OB_DUPLICALCDERIVED; - + dob->ob->lay = apply_data->extra[i].lay; } } diff --git a/source/blender/blenkernel/intern/object_update.c b/source/blender/blenkernel/intern/object_update.c index f0f31eebfbd..4c38940b11d 100644 --- a/source/blender/blenkernel/intern/object_update.c +++ b/source/blender/blenkernel/intern/object_update.c @@ -242,7 +242,6 @@ void BKE_object_handle_data_update( if (!(ob->mode & OB_MODE_EDIT) && ob->particlesystem.first) { const bool use_render_params = (DEG_get_mode(depsgraph) == DAG_EVAL_RENDER); ParticleSystem *tpsys, *psys; - DerivedMesh *dm; ob->transflag &= ~OB_DUPLIPARTS; psys = ob->particlesystem.first; while (psys) { @@ -267,18 +266,6 @@ void BKE_object_handle_data_update( else psys = psys->next; } - - if (use_render_params && ob->transflag & OB_DUPLIPARTS) { - /* this is to make sure we get render level duplis in groups: - * the derivedmesh must be created before init_render_mesh, - * since object_duplilist does dupliparticles before that */ - CustomDataMask data_mask = CD_MASK_BAREMESH | CD_MASK_MFACE | CD_MASK_MTFACE | CD_MASK_MCOL; - dm = mesh_create_derived_render(depsgraph, scene, ob, data_mask); - dm->release(dm); - - for (psys = ob->particlesystem.first; psys; psys = psys->next) - psys_get_modifier(ob, psys)->flag &= ~eParticleSystemFlag_psys_updated; - } } /* quick cache removed */ @@ -417,6 +404,12 @@ void BKE_object_eval_flush_base_flags(Depsgraph *depsgraph, object->base_flag &= ~(BASE_SELECTED | BASE_SELECTABLED); } + /* Copy to original object datablock if needed. */ + if (DEG_is_active(depsgraph)) { + Object *object_orig = DEG_get_original_object(object); + object_orig->base_flag = object->base_flag; + } + if (object->mode == OB_MODE_PARTICLE_EDIT) { for (ParticleSystem *psys = object->particlesystem.first; psys != NULL; diff --git a/source/blender/blenkernel/intern/ocean.c b/source/blender/blenkernel/intern/ocean.c index 2d8527f23d6..7f3f916964a 100644 --- a/source/blender/blenkernel/intern/ocean.c +++ b/source/blender/blenkernel/intern/ocean.c @@ -156,7 +156,7 @@ static float gaussRand(RNG *rng) { /* Note: to avoid numerical problems with very small numbers, we make these variables singe-precision floats, * but later we call the double-precision log() and sqrt() functions instead of logf() and sqrtf(). - */ + */ float x; float y; float length2; diff --git a/source/blender/blenkernel/intern/packedFile.c b/source/blender/blenkernel/intern/packedFile.c index 07cd28da556..da455faaa86 100644 --- a/source/blender/blenkernel/intern/packedFile.c +++ b/source/blender/blenkernel/intern/packedFile.c @@ -34,7 +34,7 @@ #include <fcntl.h> #include <sys/stat.h> -#ifndef WIN32 +#ifndef WIN32 #include <unistd.h> #else #include <io.h> @@ -90,14 +90,14 @@ int seekPackedFile(PackedFile *pf, int offset, int whence) return(oldseek); } - + void rewindPackedFile(PackedFile *pf) { seekPackedFile(pf, 0, SEEK_SET); } int readPackedFile(PackedFile *pf, void *data, int size) -{ +{ if ((pf != NULL) && (size >= 0) && (data != NULL)) { if (size + pf->seek > pf->size) { size = pf->size - pf->seek; @@ -125,7 +125,7 @@ int countPackedFiles(Main *bmain) VFont *vf; bSound *sound; int count = 0; - + /* let's check if there are packed files... */ for (ima = bmain->image.first; ima; ima = ima->id.next) if (BKE_image_has_packedfile(ima)) @@ -167,7 +167,7 @@ PackedFile *newPackedFileMemory(void *mem, int memlen) PackedFile *pf = MEM_callocN(sizeof(*pf), "PackedFile"); pf->data = mem; pf->size = memlen; - + return pf; } @@ -177,14 +177,14 @@ PackedFile *newPackedFile(ReportList *reports, const char *filename, const char int file, filelen; char name[FILE_MAX]; void *data; - + /* render result has no filename and can be ignored * any other files with no name can be ignored too */ if (filename[0] == '\0') return NULL; //XXX waitcursor(1); - + /* convert relative filenames to absolute filenames */ BLI_strncpy(name, filename, sizeof(name)); @@ -219,7 +219,7 @@ PackedFile *newPackedFile(ReportList *reports, const char *filename, const char } //XXX waitcursor(0); - + return (pf); } @@ -230,7 +230,7 @@ void packAll(Main *bmain, ReportList *reports, bool verbose) VFont *vfont; bSound *sound; int tot = 0; - + for (ima = bmain->image.first; ima; ima = ima->id.next) { if (BKE_image_has_packedfile(ima) == false && !ID_IS_LINKED(ima)) { if (ima->source == IMA_SRC_FILE) { @@ -257,7 +257,7 @@ void packAll(Main *bmain, ReportList *reports, bool verbose) tot++; } } - + if (tot > 0) BKE_reportf(reports, RPT_INFO, "Packed %d files", tot); else if (verbose) @@ -275,7 +275,7 @@ static char *find_new_name(char *name) char tempname[FILE_MAX]; char *newname; size_t len; - + if (fop_exists(name)) { for (number = 1; number <= 999; number++) { BLI_snprintf(tempname, sizeof(tempname), "%s.%03d", name, number); @@ -300,12 +300,12 @@ int writePackedFile( char name[FILE_MAX]; char tempname[FILE_MAX]; /* void *data; */ - + if (guimode) {} //XXX waitcursor(1); - + BLI_strncpy(name, filename, sizeof(name)); BLI_path_abs(name, ref_file_name); - + if (BLI_exists(name)) { for (number = 1; number <= 999; number++) { BLI_snprintf(tempname, sizeof(tempname), "%s.%03d_", name, number); @@ -317,10 +317,10 @@ int writePackedFile( } } } - + /* make sure the path to the file exists... */ BLI_make_existing_file(name); - + file = BLI_open(name, O_BINARY + O_WRONLY + O_CREAT + O_TRUNC, 0666); if (file == -1) { BKE_reportf(reports, RPT_ERROR, "Error creating file '%s'", name); @@ -334,10 +334,10 @@ int writePackedFile( else { BKE_reportf(reports, RPT_INFO, "Saved packed file to: %s", name); } - + close(file); } - + if (remove_tmp) { if (ret_value == RET_ERROR) { if (BLI_rename(tempname, name) != 0) { @@ -350,7 +350,7 @@ int writePackedFile( } } } - + if (guimode) {} //XXX waitcursor(0); return (ret_value); @@ -370,10 +370,10 @@ int checkPackedFile(const char *ref_file_name, const char *filename, PackedFile int ret_val, i, len, file; char buf[4096]; char name[FILE_MAX]; - + BLI_strncpy(name, filename, sizeof(name)); BLI_path_abs(name, ref_file_name); - + if (BLI_stat(name, &st) == -1) { ret_val = PF_NOFILE; } @@ -408,11 +408,11 @@ int checkPackedFile(const char *ref_file_name, const char *filename, PackedFile } } } - + close(file); } } - + return(ret_val); } @@ -430,7 +430,7 @@ char *unpackFile( { char *newname = NULL; const char *temp = NULL; - + if (pf != NULL) { switch (how) { case -1: @@ -484,12 +484,12 @@ char *unpackFile( printf("unpackFile: unknown return_value %d\n", how); break; } - + if (temp) { newname = BLI_strdup(temp); } } - + return newname; } @@ -539,7 +539,7 @@ int unpackVFont(Main *bmain, ReportList *reports, VFont *vfont, int how) char localname[FILE_MAX], absname[FILE_MAX]; char *newname; int ret_value = RET_ERROR; - + if (vfont != NULL) { unpack_generate_paths(vfont->name, (ID *)vfont, absname, localname, sizeof(absname), sizeof(localname)); newname = unpackFile(reports, BKE_main_blendfile_path(bmain), absname, localname, vfont->packedfile, how); @@ -551,7 +551,7 @@ int unpackVFont(Main *bmain, ReportList *reports, VFont *vfont, int how) MEM_freeN(newname); } } - + return (ret_value); } @@ -576,7 +576,7 @@ int unpackSound(Main *bmain, ReportList *reports, bSound *sound, int how) ret_value = RET_OK; } } - + return(ret_value); } @@ -633,16 +633,16 @@ int unpackLibraries(Main *bmain, ReportList *reports) Library *lib; char *newname; int ret_value = RET_ERROR; - + for (lib = bmain->library.first; lib; lib = lib->id.next) { if (lib->packedfile && lib->name[0]) { - + newname = unpackFile(reports, BKE_main_blendfile_path(bmain), lib->filepath, lib->filepath, lib->packedfile, PF_WRITE_ORIGINAL); if (newname != NULL) { ret_value = RET_OK; - + printf("Unpacked .blend library: %s\n", newname); - + freePackedFile(lib->packedfile); lib->packedfile = NULL; @@ -650,24 +650,24 @@ int unpackLibraries(Main *bmain, ReportList *reports) } } } - + return(ret_value); } void packLibraries(Main *bmain, ReportList *reports) { Library *lib; - + /* test for relativenss */ for (lib = bmain->library.first; lib; lib = lib->id.next) if (!BLI_path_is_rel(lib->name)) break; - + if (lib) { BKE_reportf(reports, RPT_ERROR, "Cannot pack absolute file: '%s'", lib->name); return; } - + for (lib = bmain->library.first; lib; lib = lib->id.next) if (lib->packedfile == NULL) lib->packedfile = newPackedFile(reports, lib->name, BKE_main_blendfile_path(bmain)); diff --git a/source/blender/blenkernel/intern/paint.c b/source/blender/blenkernel/intern/paint.c index 20d68ee2a58..c1c3cbf1ca3 100644 --- a/source/blender/blenkernel/intern/paint.c +++ b/source/blender/blenkernel/intern/paint.c @@ -164,7 +164,7 @@ Paint *BKE_paint_get_active(Scene *sce, ViewLayer *view_layer) { if (sce && view_layer) { ToolSettings *ts = sce->toolsettings; - + if (view_layer->basact && view_layer->basact->object) { switch (view_layer->basact->object->mode) { case OB_MODE_SCULPT: @@ -607,7 +607,7 @@ float paint_grid_paint_mask(const GridPaintMask *gpm, unsigned level, { int factor = BKE_ccg_factor(level, gpm->level); int gridsize = BKE_ccg_gridsize(gpm->level); - + return gpm->data[(y * factor) * gridsize + (x * factor)]; } @@ -709,7 +709,7 @@ static void sculptsession_bm_to_me_update_data_only(Object *ob, bool reorder) } if (reorder) BM_log_mesh_elems_reorder(ss->bm, ss->bm_log); - BM_mesh_bm_to_me(ss->bm, ob->data, (&(struct BMeshToMeshParams){0})); + BM_mesh_bm_to_me(NULL, ss->bm, ob->data, (&(struct BMeshToMeshParams){.calc_object_remap = false})); } } } diff --git a/source/blender/blenkernel/intern/particle.c b/source/blender/blenkernel/intern/particle.c index 8c322f0c853..693d6ac587e 100644 --- a/source/blender/blenkernel/intern/particle.c +++ b/source/blender/blenkernel/intern/particle.c @@ -100,19 +100,19 @@ float PSYS_FRAND_BASE[PSYS_FRAND_COUNT]; void psys_init_rng(void) { - int i; - BLI_srandom(5831); /* arbitrary */ - for (i = 0; i < PSYS_FRAND_COUNT; ++i) { - PSYS_FRAND_BASE[i] = BLI_frand(); - PSYS_FRAND_SEED_OFFSET[i] = (unsigned int)BLI_rand(); - PSYS_FRAND_SEED_MULTIPLIER[i] = (unsigned int)BLI_rand(); + RNG *rng = BLI_rng_new_srandom(5831); /* arbitrary */ + for (int i = 0; i < PSYS_FRAND_COUNT; ++i) { + PSYS_FRAND_BASE[i] = BLI_rng_get_float(rng); + PSYS_FRAND_SEED_OFFSET[i] = (unsigned int)BLI_rng_get_int(rng); + PSYS_FRAND_SEED_MULTIPLIER[i] = (unsigned int)BLI_rng_get_int(rng); } + BLI_rng_free(rng); } static void get_child_modifier_parameters(ParticleSettings *part, ParticleThreadContext *ctx, ChildParticle *cpa, short cpa_from, int cpa_num, float *cpa_fuv, float *orco, ParticleTexture *ptex); static void get_cpa_texture(Mesh *mesh, ParticleSystem *psys, ParticleSettings *part, ParticleData *par, - int child_index, int face_index, const float fw[4], float *orco, ParticleTexture *ptex, int event, float cfra); + int child_index, int face_index, const float fw[4], float *orco, ParticleTexture *ptex, int event, float cfra); /* few helpers for countall etc. */ int count_particles(ParticleSystem *psys) @@ -201,7 +201,7 @@ ParticleSystem *psys_get_current(Object *ob) if (psys->flag & PSYS_CURRENT) return psys; } - + return NULL; } short psys_get_current_num(Object *ob) @@ -214,7 +214,7 @@ short psys_get_current_num(Object *ob) for (psys = ob->particlesystem.first, i = 0; psys; psys = psys->next, i++) if (psys->flag & PSYS_CURRENT) return i; - + return i; } void psys_set_current_num(Object *ob, int index) @@ -426,7 +426,7 @@ int psys_uses_gravity(ParticleSimulationData *sim) static void fluid_free_settings(SPHFluidSettings *fluid) { if (fluid) - MEM_freeN(fluid); + MEM_freeN(fluid); } /** Free (or release) any data used by this particle settings (does not free the partsett itself). */ @@ -435,7 +435,7 @@ void BKE_particlesettings_free(ParticleSettings *part) int a; BKE_animdata_free((ID *)part, false); - + for (a = 0; a < MAX_MTEX; a++) { MEM_SAFE_FREE(part->mtex[a]); } @@ -446,7 +446,7 @@ void BKE_particlesettings_free(ParticleSettings *part) curvemapping_free(part->roughcurve); if (part->twistcurve) curvemapping_free(part->twistcurve); - + free_partdeflect(part->pd); free_partdeflect(part->pd2); @@ -477,7 +477,7 @@ void free_hair(Object *UNUSED(ob), ParticleSystem *psys, int dynamics) psys->pointcache = NULL; modifier_free((ModifierData *)psys->clmd); - + psys->clmd = NULL; psys->pointcache = BKE_ptcache_add(&psys->ptcaches); } @@ -556,10 +556,10 @@ void psys_free_particles(ParticleSystem *psys) MEM_freeN(pa->hair); } } - + if (psys->particles->keys) MEM_freeN(psys->particles->keys); - + if (psys->particles->boid) MEM_freeN(psys->particles->boid); @@ -594,11 +594,11 @@ void psys_free_pdd(ParticleSystem *psys) } /* free everything */ void psys_free(Object *ob, ParticleSystem *psys) -{ +{ if (psys) { int nr = 0; ParticleSystem *tpsys; - + psys_free_path_cache(psys, NULL); free_hair(ob, psys, 1); @@ -613,7 +613,7 @@ void psys_free(Object *ob, ParticleSystem *psys) psys->child = NULL; psys->totchild = 0; } - + /* check if we are last non-visible particle system */ for (tpsys = ob->particlesystem.first; tpsys; tpsys = tpsys->next) { if (tpsys->part) { @@ -631,7 +631,7 @@ void psys_free(Object *ob, ParticleSystem *psys) BKE_ptcache_free_list(&psys->ptcaches); psys->pointcache = NULL; - + BLI_freelistN(&psys->targets); BLI_bvhtree_free(psys->bvhtree); @@ -653,6 +653,51 @@ void psys_free(Object *ob, ParticleSystem *psys) } } +void psys_copy_particles(ParticleSystem *psys_dst, ParticleSystem *psys_src) +{ + /* Free existing particles. */ + if (psys_dst->particles != psys_src->particles) { + psys_free_particles(psys_dst); + } + if (psys_dst->child != psys_src->child) { + psys_free_children(psys_dst); + } + /* Restore counters. */ + psys_dst->totpart = psys_src->totpart; + psys_dst->totchild = psys_src->totchild; + /* Copy particles and children. */ + psys_dst->particles = MEM_dupallocN(psys_src->particles); + psys_dst->child = MEM_dupallocN(psys_src->child); + if (psys_dst->part->type == PART_HAIR) { + ParticleData *pa; + int p; + for (p = 0, pa = psys_dst->particles; p < psys_dst->totpart; p++, pa++) { + pa->hair = MEM_dupallocN(pa->hair); + } + } + if (psys_dst->particles && (psys_dst->particles->keys || psys_dst->particles->boid)) { + ParticleKey *key = psys_dst->particles->keys; + BoidParticle *boid = psys_dst->particles->boid; + ParticleData *pa; + int p; + if (key != NULL) { + key = MEM_dupallocN(key); + } + if (boid != NULL) { + boid = MEM_dupallocN(boid); + } + for (p = 0, pa = psys_dst->particles; p < psys_dst->totpart; p++, pa++) { + if (boid != NULL) { + pa->boid = boid++; + } + if (key != NULL) { + pa->keys = key; + key += pa->totkey; + } + } + } +} + /************************************************/ /* Interpolation */ /************************************************/ @@ -665,7 +710,7 @@ static float interpolate_particle_value(float v1, float v2, float v3, float v4, value += w[3] * v4; CLAMP(value, 0.f, 1.f); - + return value; } @@ -918,7 +963,7 @@ static void do_particle_interpolation(ParticleSystem *psys, int p, ParticleData while (pind->kkey[1]->time < real_t) pind->kkey[1]++; - + pind->kkey[0] = pind->kkey[1] - 1; } else if (pind->cache) { @@ -1079,7 +1124,7 @@ void psys_interpolate_face(MVert *mvert, MFace *mface, MTFace *tface, float (*or if (mface->v4) { v4 = mvert[mface->v4].co; normal_short_to_float_v3(n4, mvert[mface->v4].no); - + interp_v3_v3v3v3v3(vec, v1, v2, v3, v4, w); if (nor) { @@ -1099,7 +1144,7 @@ void psys_interpolate_face(MVert *mvert, MFace *mface, MTFace *tface, float (*or normal_tri_v3(nor, v1, v2, v3); } } - + /* calculate tangent vectors */ if (utan && vtan) { if (tface) { @@ -1199,7 +1244,7 @@ void psys_interpolate_mcol(const MCol *mcol, int quad, const float w[4], MCol *m cp1 = (const char *)&mcol[0]; cp2 = (const char *)&mcol[1]; cp3 = (const char *)&mcol[2]; - + if (quad) { cp4 = (char *)&mcol[3]; @@ -1230,7 +1275,7 @@ static float psys_interpolate_value_from_verts(Mesh *mesh, short from, int index MFace *mf = &mesh->mface[index]; return interpolate_particle_value(values[mf->v1], values[mf->v2], values[mf->v3], values[mf->v4], fw, mf->v4); } - + } return 0.0f; } @@ -1253,7 +1298,7 @@ static void psys_origspace_to_w(OrigSpaceFace *osface, int quad, const float w[4 psys_w_to_origspace(w, co); co[2] = 0.0f; - + if (quad) { v[3][0] = osface->uv[3][0]; v[3][1] = osface->uv[3][1]; v[3][2] = 0.0f; interp_weights_poly_v3(neww, v, 4, co); @@ -1336,7 +1381,7 @@ int psys_particle_dm_face_lookup( } psys_w_to_origspace(fw, uv); - + if (poly_nodes) { /* we can have a restricted linked list of faces to check, faster! */ LinkNode *tessface_node = poly_nodes[pindex_orig]; @@ -1516,7 +1561,7 @@ float psys_particle_value_from_verts(Mesh *mesh, short from, ParticleData *pa, f if (!psys_map_index_on_dm(mesh, from, pa->num, pa->num_dmcache, pa->fuv, pa->foffset, &mapindex, mapfw)) return 0.0f; - + return psys_interpolate_value_from_verts(mesh, from, mapindex, mapfw, values); } @@ -1590,13 +1635,13 @@ CustomDataMask psys_emitter_customdata_mask(ParticleSystem *psys) break; } } - + /* particles only need this if they are after a non deform modifier, and * the modifier stack will only create them in that case. */ dataMask |= CD_MASK_ORIGSPACE_MLOOP | CD_MASK_ORIGINDEX; dataMask |= CD_MASK_ORCO; - + return dataMask; } @@ -1640,10 +1685,10 @@ void precalc_guides(ParticleSimulationData *sim, ListBase *effectors) LOOP_PARTICLES { psys_particle_on_emitter(sim->psmd, sim->psys->part->from, pa->num, pa->num_dmcache, pa->fuv, pa->foffset, state.co, 0, 0, 0, 0); - + mul_m4_v3(sim->ob->obmat, state.co); mul_mat3_m4_v3(sim->ob->obmat, state.vel); - + pd_point_from_particle(sim, pa, &state, &point); for (eff = effectors->first; eff; eff = eff->next) { @@ -1681,22 +1726,22 @@ int do_guides(Depsgraph *depsgraph, ParticleSettings *part, ListBase *effectors, if (effectors) for (eff = effectors->first; eff; eff = eff->next) { pd = eff->pd; - + if (pd->forcefield != PFIELD_GUIDE) continue; - + data = eff->guide_data + index; - + if (data->strength <= 0.0f) continue; - + guidetime = time / (1.0f - pd->free_end); - + if (guidetime > 1.0f) continue; - + cu = (Curve *)eff->ob->data; - + if (pd->flag & PFIELD_GUIDE_PATH_ADD) { if (where_on_path(eff->ob, data->strength * guidetime, guidevec, guidedir, NULL, &radius, &weight) == 0) return 0; @@ -1705,14 +1750,14 @@ int do_guides(Depsgraph *depsgraph, ParticleSettings *part, ListBase *effectors, if (where_on_path(eff->ob, guidetime, guidevec, guidedir, NULL, &radius, &weight) == 0) return 0; } - + mul_m4_v3(eff->ob->obmat, guidevec); mul_mat3_m4_v3(eff->ob->obmat, guidedir); - + normalize_v3(guidedir); - + copy_v3_v3(vec_to_point, data->vec_to_point); - + if (guidetime != 0.0f) { /* curve direction */ cross_v3_v3v3(temp, eff->guide_dir, guidedir); @@ -1720,52 +1765,52 @@ int do_guides(Depsgraph *depsgraph, ParticleSettings *part, ListBase *effectors, angle = saacos(angle); axis_angle_to_quat(rot2, temp, angle); mul_qt_v3(rot2, vec_to_point); - + /* curve tilt */ axis_angle_to_quat(rot2, guidedir, guidevec[3] - eff->guide_loc[3]); mul_qt_v3(rot2, vec_to_point); } - + /* curve taper */ if (cu->taperobj) mul_v3_fl(vec_to_point, BKE_displist_calc_taper(depsgraph, eff->scene, cu->taperobj, (int)(data->strength * guidetime * 100.0f), 100)); - + else { /* curve size*/ if (cu->flag & CU_PATH_RADIUS) { mul_v3_fl(vec_to_point, radius); } } - + if (clumpcurve) curvemapping_changed_all(clumpcurve); if (roughcurve) curvemapping_changed_all(roughcurve); - + { ParticleKey key; float par_co[3] = {0.0f, 0.0f, 0.0f}; float par_vel[3] = {0.0f, 0.0f, 0.0f}; float par_rot[4] = {1.0f, 0.0f, 0.0f, 0.0f}; float orco_offset[3] = {0.0f, 0.0f, 0.0f}; - + copy_v3_v3(key.co, vec_to_point); do_kink(&key, par_co, par_vel, par_rot, guidetime, pd->kink_freq, pd->kink_shape, pd->kink_amp, 0.f, pd->kink, pd->kink_axis, 0, 0); do_clump(&key, par_co, guidetime, orco_offset, pd->clump_fac, pd->clump_pow, 1.0f, part->child_flag & PART_CHILD_USE_CLUMP_NOISE, part->clump_noise_size, clumpcurve); copy_v3_v3(vec_to_point, key.co); } - + add_v3_v3(vec_to_point, guidevec); - + //sub_v3_v3v3(pa_loc, pa_loc, pa_zero); madd_v3_v3fl(effect, vec_to_point, data->strength); madd_v3_v3fl(veffect, guidedir, data->strength); totstrength += data->strength; - + if (pd->flag & PFIELD_GUIDE_PATH_WEIGHT) totstrength *= weight; } - + if (totstrength != 0.0f) { if (totstrength > 1.0f) mul_v3_fl(effect, 1.0f / totstrength); @@ -1922,7 +1967,7 @@ static bool psys_thread_context_init_path( if (totchild && part->childtype == PART_CHILD_FACES) { totparent = (int)(totchild * part->parents * 0.3f); - + if (use_render_params && part->child_nbr && part->ren_child_nbr) totparent *= (float)part->child_nbr / (float)part->ren_child_nbr; @@ -1996,7 +2041,7 @@ static void psys_task_init_path(ParticleTask *task, ParticleSimulationData *sim) { /* init random number generator */ int seed = 31415926 + sim->psys->seed; - + task->rng_path = BLI_rng_new(seed); } @@ -2104,7 +2149,7 @@ static void psys_thread_create_path(ParticleTask *task, struct ChildParticle *cp /* get the original coordinates (orco) for texture usage */ cpa_num = cpa->num; - + foffset = cpa->foffset; cpa_fuv = cpa->fuv; cpa_from = PART_FROM_FACE; @@ -2253,14 +2298,14 @@ static void psys_thread_create_path(ParticleTask *task, struct ChildParticle *cp if (pa->flag & PARS_UNEXIST) pa = NULL; } - + if (pa) { ListBase modifiers; BLI_listbase_clear(&modifiers); - + psys_particle_on_emitter(ctx->sim.psmd, part->from, pa->num, pa->num_dmcache, pa->fuv, pa->foffset, par_co, NULL, NULL, NULL, par_orco); - + psys_apply_child_modifiers(ctx, &modifiers, cpa, &ptex, orco, hairmat, child_keys, par, par_orco); } else @@ -2298,57 +2343,57 @@ void psys_cache_child_paths( ParticleTask *tasks_parent, *tasks_child; int numtasks_parent, numtasks_child; int i, totchild, totparent; - + if (sim->psys->flag & PSYS_GLOBAL_HAIR) return; - + /* create a task pool for child path tasks */ if (!psys_thread_context_init_path(&ctx, sim, sim->scene, cfra, editupdate, use_render_params)) return; - + task_scheduler = BLI_task_scheduler_get(); task_pool = BLI_task_pool_create(task_scheduler, &ctx); totchild = ctx.totchild; totparent = ctx.totparent; - + if (editupdate && sim->psys->childcache && totchild == sim->psys->totchildcache) { ; /* just overwrite the existing cache */ } else { /* clear out old and create new empty path cache */ free_child_path_cache(sim->psys); - + sim->psys->childcache = psys_alloc_path_cache_buffers(&sim->psys->childcachebufs, totchild, ctx.segments + ctx.extra_segments + 1); sim->psys->totchildcache = totchild; } - + /* cache parent paths */ ctx.parent_pass = 1; psys_tasks_create(&ctx, 0, totparent, &tasks_parent, &numtasks_parent); for (i = 0; i < numtasks_parent; ++i) { ParticleTask *task = &tasks_parent[i]; - + psys_task_init_path(task, sim); BLI_task_pool_push(task_pool, exec_child_path_cache, task, false, TASK_PRIORITY_LOW); } BLI_task_pool_work_and_wait(task_pool); - + /* cache child paths */ ctx.parent_pass = 0; psys_tasks_create(&ctx, totparent, totchild, &tasks_child, &numtasks_child); for (i = 0; i < numtasks_child; ++i) { ParticleTask *task = &tasks_child[i]; - + psys_task_init_path(task, sim); BLI_task_pool_push(task_pool, exec_child_path_cache, task, false, TASK_PRIORITY_LOW); } BLI_task_pool_work_and_wait(task_pool); BLI_task_pool_free(task_pool); - + psys_tasks_free(tasks_parent, numtasks_parent); psys_tasks_free(tasks_child, numtasks_child); - + psys_thread_context_free(&ctx); } @@ -2404,15 +2449,15 @@ void psys_cache_paths(ParticleSimulationData *sim, float cfra, const bool use_re ParticleCacheKey *ca, **cache; Mesh *hair_mesh = (psys->part->type == PART_HAIR && psys->flag & PSYS_HAIR_DYNAMICS) ? psys->hair_out_mesh : NULL; - + ParticleKey result; - + Material *ma; ParticleInterpolationData pind; ParticleTexture ptex; PARTICLE_P; - + float birthtime = 0.0, dietime = 0.0; float t, time = 0.0, dfra = 1.0 /* , frs_sec = sim->scene->r.frs_sec*/ /*UNUSED*/; float col[4] = {0.5f, 0.5f, 0.5f, 1.0f}; @@ -2449,7 +2494,7 @@ void psys_cache_paths(ParticleSimulationData *sim, float cfra, const bool use_re if ((psys->flag & PSYS_GLOBAL_HAIR) == 0) { if ((psys->part->flag & PART_CHILD_EFFECT) == 0) vg_effector = psys_cache_vgroup(psmd->mesh_final, psys, PSYS_VG_EFFECTOR); - + if (!psys->totchild) vg_length = psys_cache_vgroup(psmd->mesh_final, psys, PSYS_VG_LENGTH); } @@ -2524,7 +2569,7 @@ void psys_cache_paths(ParticleSimulationData *sim, float cfra, const bool use_re if (part->type == PART_HAIR) { HairKey *hkey; - + for (k = 0, hkey = pa->hair; k < pa->totkey; ++k, ++hkey) { mul_v3_m4v3(hkey->world_co, hairmat, hkey->co); } @@ -2598,204 +2643,235 @@ void psys_cache_paths(ParticleSimulationData *sim, float cfra, const bool use_re if (vg_length) MEM_freeN(vg_length); } -void psys_cache_edit_paths(Depsgraph *depsgraph, Scene *scene, Object *ob, PTCacheEdit *edit, float cfra, const bool use_render_params) -{ - ParticleCacheKey *ca, **cache = edit->pathcache; - ParticleEditSettings *pset = &scene->toolsettings->particle; - - PTCacheEditPoint *point = NULL; - PTCacheEditKey *ekey = NULL; - - ParticleSystem *psys = edit->psys; - ParticleSystemModifierData *psmd = psys_get_modifier(ob, psys); - ParticleData *pa = psys ? psys->particles : NULL; - - ParticleInterpolationData pind; - ParticleKey result; - - float birthtime = 0.0f, dietime = 0.0f; - float t, time = 0.0f, keytime = 0.0f /*, frs_sec */; - float hairmat[4][4], rotmat[3][3], prev_tangent[3] = {0.0f, 0.0f, 0.0f}; - int k, i; - int segments = 1 << pset->draw_step; - int totpart = edit->totpoint, recalc_set = 0; +typedef struct CacheEditrPathsIterData { + Object *object; + PTCacheEdit *edit; + ParticleSystemModifierData *psmd; + ParticleData *pa; + int segments; + bool use_weight; float sel_col[3]; float nosel_col[3]; +} CacheEditrPathsIterData; - segments = MAX2(segments, 4); - - if (!cache || edit->totpoint != edit->totcached) { - /* clear out old and create new empty path cache */ - psys_free_path_cache(edit->psys, edit); - cache = edit->pathcache = psys_alloc_path_cache_buffers(&edit->pathcachebufs, totpart, segments + 1); - - /* set flag for update (child particles check this too) */ - for (i = 0, point = edit->points; i < totpart; i++, point++) - point->flag |= PEP_EDIT_RECALC; - recalc_set = 1; +static void psys_cache_edit_paths_iter( + void *__restrict iter_data_v, + const int iter, + const ParallelRangeTLS *__restrict UNUSED(tls)) +{ + CacheEditrPathsIterData *iter_data = (CacheEditrPathsIterData *)iter_data_v; + PTCacheEdit *edit = iter_data->edit; + PTCacheEditPoint *point = &edit->points[iter]; + if (edit->totcached && !(point->flag & PEP_EDIT_RECALC)) { + return; + } + if (point->totkey == 0) { + return; } + Object *ob = iter_data->object; + ParticleSystem *psys = edit->psys; + ParticleCacheKey **cache = edit->pathcache; + ParticleSystemModifierData *psmd = iter_data->psmd; + ParticleData *pa = iter_data->pa ? iter_data->pa + iter : NULL; + PTCacheEditKey *ekey = point->keys; + const int segments = iter_data->segments; + const bool use_weight = iter_data->use_weight; - /* frs_sec = (psys || edit->pid.flag & PTCACHE_VEL_PER_SEC) ? 25.0f : 1.0f; */ /* UNUSED */ + float birthtime = 0.0f, dietime = 0.0f; + float hairmat[4][4], rotmat[3][3], prev_tangent[3] = {0.0f, 0.0f, 0.0f}; - const bool use_weight = (pset->brushtype == PE_BRUSH_WEIGHT) && (psys != NULL) && (psys->particles != NULL); + ParticleInterpolationData pind; + pind.keyed = 0; + pind.cache = NULL; + pind.epoint = point; + pind.bspline = psys ? (psys->part->flag & PART_HAIR_BSPLINE) : 0; + pind.mesh = NULL; + /* should init_particle_interpolation set this ? */ if (use_weight) { - ; /* use weight painting colors now... */ - } - else { - sel_col[0] = (float)edit->sel_col[0] / 255.0f; - sel_col[1] = (float)edit->sel_col[1] / 255.0f; - sel_col[2] = (float)edit->sel_col[2] / 255.0f; - nosel_col[0] = (float)edit->nosel_col[0] / 255.0f; - nosel_col[1] = (float)edit->nosel_col[1] / 255.0f; - nosel_col[2] = (float)edit->nosel_col[2] / 255.0f; + pind.hkey[0] = NULL; + /* pa != NULL since the weight brush is only available for hair */ + pind.hkey[0] = pa->hair; + pind.hkey[1] = pa->hair + 1; } - /*---first main loop: create all actual particles' paths---*/ - for (i = 0, point = edit->points; i < totpart; i++, pa += pa ? 1 : 0, point++) { - if (edit->totcached && !(point->flag & PEP_EDIT_RECALC)) - continue; + memset(cache[iter], 0, sizeof(*cache[iter]) * (segments + 1)); - if (point->totkey == 0) - continue; + cache[iter]->segments = segments; - ekey = point->keys; + /*--get the first data points--*/ + init_particle_interpolation(ob, psys, pa, &pind); - pind.keyed = 0; - pind.cache = NULL; - pind.epoint = point; - pind.bspline = psys ? (psys->part->flag & PART_HAIR_BSPLINE) : 0; - pind.mesh = NULL; + if (psys) { + psys_mat_hair_to_global(ob, psmd->mesh_final, psys->part->from, pa, hairmat); + copy_v3_v3(rotmat[0], hairmat[2]); + copy_v3_v3(rotmat[1], hairmat[1]); + copy_v3_v3(rotmat[2], hairmat[0]); + } + birthtime = pind.birthtime; + dietime = pind.dietime; - /* should init_particle_interpolation set this ? */ - if (use_weight) { - pind.hkey[0] = NULL; - /* pa != NULL since the weight brush is only available for hair */ - pind.hkey[0] = pa->hair; - pind.hkey[1] = pa->hair + 1; - } + if (birthtime >= dietime) { + cache[iter]->segments = -1; + return; + } + /*--interpolate actual path from data points--*/ + ParticleCacheKey *ca; + int k; + float t, time = 0.0f, keytime = 0.0f; + for (k = 0, ca = cache[iter]; k <= segments; k++, ca++) { + time = (float)k / (float)segments; + t = birthtime + time * (dietime - birthtime); + ParticleKey result; + result.time = -t; + do_particle_interpolation(psys, iter, pa, t, &pind, &result); + copy_v3_v3(ca->co, result.co); + + /* non-hair points are already in global space */ + if (psys && !(psys->flag & PSYS_GLOBAL_HAIR)) { + mul_m4_v3(hairmat, ca->co); - memset(cache[i], 0, sizeof(*cache[i]) * (segments + 1)); + if (k) { + cache_key_incremental_rotation(ca, ca - 1, ca - 2, prev_tangent, k); - cache[i]->segments = segments; + if (k == segments) + copy_qt_qt(ca->rot, (ca - 1)->rot); - /*--get the first data points--*/ - init_particle_interpolation(ob, psys, pa, &pind); + /* set velocity */ + sub_v3_v3v3(ca->vel, ca->co, (ca - 1)->co); - if (psys) { - psys_mat_hair_to_global(ob, psmd->mesh_final, psys->part->from, pa, hairmat); - copy_v3_v3(rotmat[0], hairmat[2]); - copy_v3_v3(rotmat[1], hairmat[1]); - copy_v3_v3(rotmat[2], hairmat[0]); + if (k == 1) + copy_v3_v3((ca - 1)->vel, ca->vel); + } } - - birthtime = pind.birthtime; - dietime = pind.dietime; - - if (birthtime >= dietime) { - cache[i]->segments = -1; - continue; + else { + ca->vel[0] = ca->vel[1] = 0.0f; + ca->vel[2] = 1.0f; } - /*--interpolate actual path from data points--*/ - for (k = 0, ca = cache[i]; k <= segments; k++, ca++) { - time = (float)k / (float)segments; - t = birthtime + time * (dietime - birthtime); - result.time = -t; - do_particle_interpolation(psys, i, pa, t, &pind, &result); - copy_v3_v3(ca->co, result.co); - - /* non-hair points are already in global space */ - if (psys && !(psys->flag & PSYS_GLOBAL_HAIR)) { - mul_m4_v3(hairmat, ca->co); - - if (k) { - cache_key_incremental_rotation(ca, ca - 1, ca - 2, prev_tangent, k); - - if (k == segments) - copy_qt_qt(ca->rot, (ca - 1)->rot); - - /* set velocity */ - sub_v3_v3v3(ca->vel, ca->co, (ca - 1)->co); - - if (k == 1) - copy_v3_v3((ca - 1)->vel, ca->vel); - } + /* selection coloring in edit mode */ + if (use_weight) { + if (k == 0) { + weight_to_rgb(ca->col, pind.hkey[1]->weight); } else { - ca->vel[0] = ca->vel[1] = 0.0f; - ca->vel[2] = 1.0f; - } - - /* selection coloring in edit mode */ - if (use_weight) { - if (k == 0) { - weight_to_rgb(ca->col, pind.hkey[1]->weight); + /* warning: copied from 'do_particle_interpolation' (without 'mvert' array stepping) */ + float real_t; + if (result.time < 0.0f) { + real_t = -result.time; } else { - /* warning: copied from 'do_particle_interpolation' (without 'mvert' array stepping) */ - float real_t; - if (result.time < 0.0f) { - real_t = -result.time; - } - else { - real_t = pind.hkey[0]->time + t * (pind.hkey[0][pa->totkey - 1].time - pind.hkey[0]->time); - } + real_t = pind.hkey[0]->time + t * (pind.hkey[0][pa->totkey - 1].time - pind.hkey[0]->time); + } - while (pind.hkey[1]->time < real_t) { - pind.hkey[1]++; - } - pind.hkey[0] = pind.hkey[1] - 1; - /* end copy */ + while (pind.hkey[1]->time < real_t) { + pind.hkey[1]++; + } + pind.hkey[0] = pind.hkey[1] - 1; + /* end copy */ - float w1[3], w2[3]; - keytime = (t - (*pind.ekey[0]->time)) / ((*pind.ekey[1]->time) - (*pind.ekey[0]->time)); + float w1[3], w2[3]; + keytime = (t - (*pind.ekey[0]->time)) / ((*pind.ekey[1]->time) - (*pind.ekey[0]->time)); - weight_to_rgb(w1, pind.hkey[0]->weight); - weight_to_rgb(w2, pind.hkey[1]->weight); + weight_to_rgb(w1, pind.hkey[0]->weight); + weight_to_rgb(w2, pind.hkey[1]->weight); - interp_v3_v3v3(ca->col, w1, w2, keytime); + interp_v3_v3v3(ca->col, w1, w2, keytime); + } + } + else { + if ((ekey + (pind.ekey[0] - point->keys))->flag & PEK_SELECT) { + if ((ekey + (pind.ekey[1] - point->keys))->flag & PEK_SELECT) { + copy_v3_v3(ca->col, iter_data->sel_col); + } + else { + keytime = (t - (*pind.ekey[0]->time)) / ((*pind.ekey[1]->time) - (*pind.ekey[0]->time)); + interp_v3_v3v3(ca->col, iter_data->sel_col, iter_data->nosel_col, keytime); } } else { - if ((ekey + (pind.ekey[0] - point->keys))->flag & PEK_SELECT) { - if ((ekey + (pind.ekey[1] - point->keys))->flag & PEK_SELECT) { - copy_v3_v3(ca->col, sel_col); - } - else { - keytime = (t - (*pind.ekey[0]->time)) / ((*pind.ekey[1]->time) - (*pind.ekey[0]->time)); - interp_v3_v3v3(ca->col, sel_col, nosel_col, keytime); - } + if ((ekey + (pind.ekey[1] - point->keys))->flag & PEK_SELECT) { + keytime = (t - (*pind.ekey[0]->time)) / ((*pind.ekey[1]->time) - (*pind.ekey[0]->time)); + interp_v3_v3v3(ca->col, iter_data->nosel_col, iter_data->sel_col, keytime); } else { - if ((ekey + (pind.ekey[1] - point->keys))->flag & PEK_SELECT) { - keytime = (t - (*pind.ekey[0]->time)) / ((*pind.ekey[1]->time) - (*pind.ekey[0]->time)); - interp_v3_v3v3(ca->col, nosel_col, sel_col, keytime); - } - else { - copy_v3_v3(ca->col, nosel_col); - } + copy_v3_v3(ca->col, iter_data->nosel_col); } } - - ca->time = t; } - if (psys && !(psys->flag & PSYS_GLOBAL_HAIR)) { - /* First rotation is based on emitting face orientation. - * This is way better than having flipping rotations resulting - * from using a global axis as a rotation pole (vec_to_quat()). - * It's not an ideal solution though since it disregards the - * initial tangent, but taking that in to account will allow - * the possibility of flipping again. -jahka - */ - mat3_to_quat_is_ok(cache[i]->rot, rotmat); + + ca->time = t; + } + if (psys && !(psys->flag & PSYS_GLOBAL_HAIR)) { + /* First rotation is based on emitting face orientation. + * This is way better than having flipping rotations resulting + * from using a global axis as a rotation pole (vec_to_quat()). + * It's not an ideal solution though since it disregards the + * initial tangent, but taking that in to account will allow + * the possibility of flipping again. -jahka + */ + mat3_to_quat_is_ok(cache[iter]->rot, rotmat); + } +} + +void psys_cache_edit_paths(Depsgraph *depsgraph, Scene *scene, Object *ob, PTCacheEdit *edit, float cfra, const bool use_render_params) +{ + ParticleCacheKey **cache = edit->pathcache; + ParticleEditSettings *pset = &scene->toolsettings->particle; + + ParticleSystem *psys = edit->psys; + + ParticleData *pa = psys ? psys->particles : NULL; + + int segments = 1 << pset->draw_step; + int totpart = edit->totpoint, recalc_set = 0; + + segments = MAX2(segments, 4); + + if (!cache || edit->totpoint != edit->totcached) { + /* Clear out old and create new empty path cache. */ + psys_free_path_cache(edit->psys, edit); + cache = edit->pathcache = psys_alloc_path_cache_buffers(&edit->pathcachebufs, totpart, segments + 1); + /* Set flag for update (child particles check this too). */ + int i; + PTCacheEditPoint *point; + for (i = 0, point = edit->points; i < totpart; i++, point++) { + point->flag |= PEP_EDIT_RECALC; } + recalc_set = 1; } + const bool use_weight = (pset->brushtype == PE_BRUSH_WEIGHT) && (psys != NULL) && (psys->particles != NULL); + + CacheEditrPathsIterData iter_data; + iter_data.object = ob; + iter_data.edit = edit; + iter_data.psmd = edit->psmd_eval; + iter_data.pa = pa; + iter_data.segments = segments; + iter_data.use_weight = use_weight; + + if (use_weight) { + ; /* use weight painting colors now... */ + } + else { + iter_data.sel_col[0] = (float)edit->sel_col[0] / 255.0f; + iter_data.sel_col[1] = (float)edit->sel_col[1] / 255.0f; + iter_data.sel_col[2] = (float)edit->sel_col[2] / 255.0f; + iter_data.nosel_col[0] = (float)edit->nosel_col[0] / 255.0f; + iter_data.nosel_col[1] = (float)edit->nosel_col[1] / 255.0f; + iter_data.nosel_col[2] = (float)edit->nosel_col[2] / 255.0f; + } + + ParallelRangeSettings settings; + BLI_parallel_range_settings_defaults(&settings); + settings.scheduling_mode = TASK_SCHEDULING_DYNAMIC; + BLI_task_parallel_range(0, edit->totpoint, &iter_data, psys_cache_edit_paths_iter, &settings); + edit->totcached = totpart; if (psys) { @@ -2804,15 +2880,18 @@ void psys_cache_edit_paths(Depsgraph *depsgraph, Scene *scene, Object *ob, PTCac sim.scene = scene; sim.ob = ob; sim.psys = psys; - sim.psmd = psys_get_modifier(ob, psys); + sim.psmd = edit->psmd_eval; psys_cache_child_paths(&sim, cfra, true, use_render_params); } /* clear recalc flag if set here */ if (recalc_set) { - for (i = 0, point = edit->points; i < totpart; i++, point++) + PTCacheEditPoint *point; + int i; + for (i = 0, point = edit->points; i < totpart; i++, point++) { point->flag &= ~PEP_EDIT_RECALC; + } } } /************************************************/ @@ -2889,7 +2968,7 @@ static void triatomat(float *v1, float *v2, float *v3, float (*uv)[2], float mat sub_v3_v3v3(mat[1], v2, v1); normalize_v3(mat[1]); } - + /* third as a cross product */ cross_v3_v3v3(mat[0], mat[1], mat[2]); } @@ -2906,7 +2985,7 @@ static void psys_face_mat(Object *ob, Mesh *mesh, ParticleData *pa, float mat[4] mface = &mesh->mface[i]; osface = CustomData_get(&mesh->fdata, i, CD_ORIGSPACE); - + if (orco && (orcodata = CustomData_get_layer(&mesh->vdata, CD_ORCO))) { copy_v3_v3(v[0], orcodata[mface->v1]); copy_v3_v3(v[1], orcodata[mface->v2]); @@ -2935,7 +3014,7 @@ void psys_mat_hair_to_object(Object *UNUSED(ob), Mesh *mesh, short from, Particl unit_m4(hairmat); return; } - + psys_face_mat(0, mesh, pa, hairmat, 0); psys_particle_on_dm(mesh, from, pa->num, pa->num_dmcache, pa->fuv, pa->foffset, vec, 0, 0, 0, 0); copy_v3_v3(hairmat[3], vec); @@ -2975,7 +3054,7 @@ void psys_mat_hair_to_global(Object *ob, Mesh *mesh, short from, ParticleData *p /************************************************/ /* ParticleSettings handling */ /************************************************/ -ModifierData *object_add_particle_system(Scene *scene, Object *ob, const char *name) +ModifierData *object_add_particle_system(Main *bmain, Scene *scene, Object *ob, const char *name) { ParticleSystem *psys; ModifierData *md; @@ -2992,7 +3071,7 @@ ModifierData *object_add_particle_system(Scene *scene, Object *ob, const char *n psys->pointcache = BKE_ptcache_add(&psys->ptcaches); BLI_addtail(&ob->particlesystem, psys); - psys->part = BKE_particlesettings_add(NULL, DATA_("ParticleSettings")); + psys->part = BKE_particlesettings_add(bmain, DATA_("ParticleSettings")); if (BLI_listbase_count_at_most(&ob->particlesystem, 2) > 1) BLI_snprintf(psys->name, sizeof(psys->name), DATA_("ParticleSystem %i"), BLI_listbase_count(&ob->particlesystem)); @@ -3015,12 +3094,12 @@ ModifierData *object_add_particle_system(Scene *scene, Object *ob, const char *n psys->flag = PSYS_CURRENT; psys->cfra = BKE_scene_frame_get_from_ctime(scene, CFRA + 1); - DEG_relations_tag_update(G.main); + DEG_relations_tag_update(bmain); DEG_id_tag_update(&ob->id, OB_RECALC_DATA); return md; } -void object_remove_particle_system(Scene *UNUSED(scene), Object *ob) +void object_remove_particle_system(Main *bmain, Scene *UNUSED(scene), Object *ob) { ParticleSystem *psys = psys_get_current(ob); ParticleSystemModifierData *psmd; @@ -3061,9 +3140,9 @@ void object_remove_particle_system(Scene *UNUSED(scene), Object *ob) else ob->mode &= ~OB_MODE_PARTICLE_EDIT; - DEG_relations_tag_update(G.main); + DEG_relations_tag_update(bmain); DEG_id_tag_update(&ob->id, OB_RECALC_DATA); - + /* Flush object mode. */ DEG_id_tag_update(&ob->id, DEG_TAG_COPY_ON_WRITE); } @@ -3087,7 +3166,7 @@ static void default_particle_settings(ParticleSettings *part) part->grid_res = 10; part->timetweak = 1.0; part->courant_target = 0.2; - + part->integrator = PART_INT_MIDPOINT; part->phystype = PART_PHYS_NEWTON; part->hair_step = 5; @@ -3155,15 +3234,12 @@ static void default_particle_settings(ParticleSettings *part) } -ParticleSettings *BKE_particlesettings_add(Main *main, const char *name) +ParticleSettings *BKE_particlesettings_add(Main *bmain, const char *name) { ParticleSettings *part; - if (main == NULL) - main = G.main; + part = BKE_libblock_alloc(bmain, ID_PA, name, 0); - part = BKE_libblock_alloc(main, ID_PA, name, 0); - default_particle_settings(part); return part; @@ -3172,24 +3248,24 @@ ParticleSettings *BKE_particlesettings_add(Main *main, const char *name) void BKE_particlesettings_clump_curve_init(ParticleSettings *part) { CurveMapping *cumap = curvemapping_add(1, 0.0f, 0.0f, 1.0f, 1.0f); - + cumap->cm[0].curve[0].x = 0.0f; cumap->cm[0].curve[0].y = 1.0f; cumap->cm[0].curve[1].x = 1.0f; cumap->cm[0].curve[1].y = 1.0f; - + part->clumpcurve = cumap; } void BKE_particlesettings_rough_curve_init(ParticleSettings *part) { CurveMapping *cumap = curvemapping_add(1, 0.0f, 0.0f, 1.0f, 1.0f); - + cumap->cm[0].curve[0].x = 0.0f; cumap->cm[0].curve[0].y = 1.0f; cumap->cm[0].curve[1].x = 1.0f; cumap->cm[0].curve[1].y = 1.0f; - + part->roughcurve = cumap; } @@ -3264,7 +3340,7 @@ static int get_particle_uv(Mesh *mesh, ParticleData *pa, int index, const float MFace *mf; MTFace *tf; int i; - + tf = CustomData_get_layer_named(&mesh->fdata, CD_MTFACE, name); if (tf == NULL) @@ -3461,7 +3537,7 @@ void psys_get_texture(ParticleSimulationData *sim, ParticleData *pa, ParticleTex ATTR_FALLTHROUGH; case TEXCO_ORCO: psys_particle_on_emitter(sim->psmd, sim->psys->part->from, pa->num, pa->num_dmcache, pa->fuv, pa->foffset, co, 0, 0, 0, texvec); - + if (me->bb == NULL || (me->bb->flag & BOUNDBOX_DIRTY)) { BKE_mesh_texspace_calc(me); } @@ -3557,7 +3633,7 @@ float psys_get_child_size(ParticleSystem *psys, ChildParticle *cpa, float UNUSED { ParticleSettings *part = psys->part; float size; // time XXX - + if (part->childtype == PART_CHILD_FACES) { int w = 0; size = 0.0; @@ -3694,7 +3770,7 @@ void psys_get_particle_on_path(ParticleSimulationData *sim, int p, ParticleKey * } else { float par_co[3], par_orco[3]; - + cpa = psys->child + p - totpart; if (state->time < 0.0f) @@ -3971,9 +4047,9 @@ int psys_get_particle_state(ParticleSimulationData *sim, int p, ParticleKey *sta /* convert velocity to timestep size */ mul_v3_fl(keys[1].vel, dfra * timestep); mul_v3_fl(keys[2].vel, dfra * timestep); - + psys_interpolate_particle(-1, keys, keytime, state, 1); - + /* convert back to real velocity */ mul_v3_fl(state->vel, 1.f / (dfra * timestep)); @@ -3999,7 +4075,7 @@ int psys_get_particle_state(ParticleSimulationData *sim, int p, ParticleKey *sta if (sim->psys->lattice_deform_data) calc_latt_deform(sim->psys->lattice_deform_data, state->co, psys->lattice_strength); } - + return 1; } } @@ -4037,7 +4113,7 @@ void psys_get_dupli_texture(ParticleSystem *psys, ParticleSettings *part, mtface += cpa->num; psys_interpolate_uvs(mtface, mface->v4, cpa->fuv, uv); } - + psys_particle_on_emitter(psmd, PART_FROM_FACE, cpa->num, DMCACHE_ISCHILD, cpa->fuv, cpa->foffset, loc, 0, 0, 0, orco); return; } @@ -4249,7 +4325,7 @@ void psys_apply_hair_lattice(Depsgraph *depsgraph, Scene *scene, Object *ob, Par mul_m4_v3(imat, hkey->co); } } - + end_latt_deform(psys->lattice_deform_data); psys->lattice_deform_data = NULL; diff --git a/source/blender/blenkernel/intern/particle_distribute.c b/source/blender/blenkernel/intern/particle_distribute.c index 846afd48064..2e056aa7a3f 100644 --- a/source/blender/blenkernel/intern/particle_distribute.c +++ b/source/blender/blenkernel/intern/particle_distribute.c @@ -85,6 +85,7 @@ static void distribute_simple_children(Scene *scene, Object *ob, Mesh *final_mes int i, p; int child_nbr= psys_get_child_number(scene, psys, use_render_params); int totpart= psys_get_tot_child(scene, psys, use_render_params); + RNG *rng = BLI_rng_new_srandom(31415926 + psys->seed + psys->child_seed); alloc_child_particles(psys, totpart); @@ -93,12 +94,12 @@ static void distribute_simple_children(Scene *scene, Object *ob, Mesh *final_mes for (p=0; p<psys->totpart; p++,cpa++) { float length=2.0; cpa->parent=p; - + /* create even spherical distribution inside unit sphere */ while (length>=1.0f) { - cpa->fuv[0]=2.0f*BLI_frand()-1.0f; - cpa->fuv[1]=2.0f*BLI_frand()-1.0f; - cpa->fuv[2]=2.0f*BLI_frand()-1.0f; + cpa->fuv[0]=2.0f*BLI_rng_get_float(rng)-1.0f; + cpa->fuv[1]=2.0f*BLI_rng_get_float(rng)-1.0f; + cpa->fuv[2]=2.0f*BLI_rng_get_float(rng)-1.0f; length=len_v3(cpa->fuv); } @@ -107,6 +108,8 @@ static void distribute_simple_children(Scene *scene, Object *ob, Mesh *final_mes } /* dmcache must be updated for parent particles if children from faces is used */ psys_calc_dmcache(ob, final_mesh, deform_mesh, psys); + + BLI_rng_free(rng); } static void distribute_grid(Mesh *mesh, ParticleSystem *psys) { @@ -135,7 +138,7 @@ static void distribute_grid(Mesh *mesh, ParticleSystem *psys) /* determine major axis */ axis = axis_dominant_v3_single(delta); - + d = delta[axis]/(float)res; size[axis] = res; @@ -197,7 +200,7 @@ static void distribute_grid(Mesh *mesh, ParticleSystem *psys) totface = mesh->totface; mface = mface_array = mesh->mface; - + for (a=0; a<amax; a++) { if (a==0) { a0mul=res*res; a1mul=res; a2mul=1; } else if (a==1) { a0mul=res; a1mul=1; a2mul=res*res; } @@ -346,13 +349,13 @@ static void init_mv_jit(float *jit, int num, int seed2, float amount) x= 0; num2 = 2 * num; for (i=0; i<num2; i+=2) { - + jit[i] = x + amount*rad1*(0.5f - BLI_rng_get_float(rng)); jit[i+1] = i/(2.0f*num) + amount*rad1*(0.5f - BLI_rng_get_float(rng)); - + jit[i]-= (float)floor(jit[i]); jit[i+1]-= (float)floor(jit[i+1]); - + x+= rad3; x -= (float)floor(x); } @@ -413,10 +416,10 @@ static int distribute_binary_search(float *sum, int n, float value) while (low < high) { mid = (low + high) / 2; - + if ((sum[mid] >= value) && (sum[mid - 1] < value)) return mid; - + if (sum[mid] > value) { high = mid - 1; } @@ -430,7 +433,7 @@ static int distribute_binary_search(float *sum, int n, float value) /* the max number if calls to rng_* funcs within psys_thread_distribute_particle * be sure to keep up to date if this changes */ -#define PSYS_RND_DIST_SKIP 2 +#define PSYS_RND_DIST_SKIP 3 /* note: this function must be thread safe, for from == PART_FROM_CHILD */ #define ONLY_WORKING_WITH_PA_VERTS 0 @@ -468,24 +471,26 @@ static void distribute_from_verts_exec(ParticleTask *thread, ParticleData *pa, i } } } - + #if ONLY_WORKING_WITH_PA_VERTS if (ctx->tree) { KDTreeNearest ptn[3]; int w, maxw; - + psys_particle_on_dm(ctx->mesh,from,pa->num,pa->num_dmcache,pa->fuv,pa->foffset,co1,0,0,0,orco1,0); BKE_mesh_orco_verts_transform((Mesh*)ob->data, &orco1, 1, 1); maxw = BLI_kdtree_find_nearest_n(ctx->tree,orco1,ptn,3); - + for (w=0; w<maxw; w++) { pa->verts[w]=ptn->num; } } #endif - - if (rng_skip_tot > 0) /* should never be below zero */ + + BLI_assert(rng_skip_tot > 0); /* should never be below zero */ + if (rng_skip_tot > 0) { BLI_rng_skip(thread->rng, rng_skip_tot); + } } static void distribute_from_faces_exec(ParticleTask *thread, ParticleData *pa, int p) { @@ -497,10 +502,10 @@ static void distribute_from_faces_exec(ParticleTask *thread, ParticleData *pa, i int rng_skip_tot= PSYS_RND_DIST_SKIP; /* count how many rng_* calls wont need skipping */ MFace *mface; - + pa->num = i = ctx->index[p]; mface = &mesh->mface[i]; - + switch (distr) { case PART_DISTR_JIT: if (ctx->jitlevel == 1) { @@ -520,14 +525,16 @@ static void distribute_from_faces_exec(ParticleTask *thread, ParticleData *pa, i randu= BLI_rng_get_float(thread->rng); randv= BLI_rng_get_float(thread->rng); rng_skip_tot -= 2; - + psys_uv_to_w(randu, randv, mface->v4, pa->fuv); break; } pa->foffset= 0.0f; - - if (rng_skip_tot > 0) /* should never be below zero */ + + BLI_assert(rng_skip_tot > 0); /* should never be below zero */ + if (rng_skip_tot > 0) { BLI_rng_skip(thread->rng, rng_skip_tot); + } } static void distribute_from_volume_exec(ParticleTask *thread, ParticleData *pa, int p) { @@ -538,13 +545,13 @@ static void distribute_from_volume_exec(ParticleTask *thread, ParticleData *pa, int distr= ctx->distr; int i, intersect, tot; int rng_skip_tot= PSYS_RND_DIST_SKIP; /* count how many rng_* calls wont need skipping */ - + MFace *mface; MVert *mvert = mesh->mvert; - + pa->num = i = ctx->index[p]; mface = &mesh->mface[i]; - + switch (distr) { case PART_DISTR_JIT: if (ctx->jitlevel == 1) { @@ -564,30 +571,30 @@ static void distribute_from_volume_exec(ParticleTask *thread, ParticleData *pa, randu= BLI_rng_get_float(thread->rng); randv= BLI_rng_get_float(thread->rng); rng_skip_tot -= 2; - + psys_uv_to_w(randu, randv, mface->v4, pa->fuv); break; } pa->foffset= 0.0f; - + /* experimental */ tot = mesh->totface; - + psys_interpolate_face(mvert,mface,0,0,pa->fuv,co,nor,0,0,0); - + normalize_v3(nor); negate_v3(nor); - + min_d=FLT_MAX; intersect=0; - + for (i=0, mface=mesh->mface; i<tot; i++,mface++) { if (i==pa->num) continue; - + v1=mvert[mface->v1].co; v2=mvert[mface->v2].co; v3=mvert[mface->v3].co; - + if (isect_ray_tri_v3(co, nor, v2, v3, v1, &cur_d, NULL)) { if (cur_d<min_d) { min_d=cur_d; @@ -597,7 +604,7 @@ static void distribute_from_volume_exec(ParticleTask *thread, ParticleData *pa, } if (mface->v4) { v4=mvert[mface->v4].co; - + if (isect_ray_tri_v3(co, nor, v4, v1, v3, &cur_d, NULL)) { if (cur_d<min_d) { min_d=cur_d; @@ -615,13 +622,16 @@ static void distribute_from_volume_exec(ParticleTask *thread, ParticleData *pa, pa->foffset *= ctx->jit[p % (2 * ctx->jitlevel)]; break; case PART_DISTR_RAND: - pa->foffset *= BLI_frand(); + pa->foffset *= BLI_rng_get_float(thread->rng); + rng_skip_tot--; break; } } - - if (rng_skip_tot > 0) /* should never be below zero */ + + BLI_assert(rng_skip_tot > 0); /* should never be below zero */ + if (rng_skip_tot > 0) { BLI_rng_skip(thread->rng, rng_skip_tot); + } } static void distribute_children_exec(ParticleTask *thread, ChildParticle *cpa, int p) { @@ -633,40 +643,40 @@ static void distribute_children_exec(ParticleTask *thread, ChildParticle *cpa, i int cfrom= ctx->cfrom; int i; int rng_skip_tot= PSYS_RND_DIST_SKIP; /* count how many rng_* calls wont need skipping */ - + MFace *mf; - + if (ctx->index[p] < 0) { cpa->num=0; cpa->fuv[0]=cpa->fuv[1]=cpa->fuv[2]=cpa->fuv[3]=0.0f; cpa->pa[0]=cpa->pa[1]=cpa->pa[2]=cpa->pa[3]=0; return; } - + mf = &mesh->mface[ctx->index[p]]; - + randu= BLI_rng_get_float(thread->rng); randv= BLI_rng_get_float(thread->rng); rng_skip_tot -= 2; - + psys_uv_to_w(randu, randv, mf->v4, cpa->fuv); - + cpa->num = ctx->index[p]; - + if (ctx->tree) { KDTreeNearest ptn[10]; int w,maxw;//, do_seams; float maxd /*, mind,dd */, totw= 0.0f; int parent[10]; float pweight[10]; - + psys_particle_on_dm(mesh,cfrom,cpa->num,DMCACHE_ISCHILD,cpa->fuv,cpa->foffset,co1,nor1,NULL,NULL,orco1); BKE_mesh_orco_verts_transform((Mesh*)ob->data, &orco1, 1, 1); maxw = BLI_kdtree_find_nearest_n(ctx->tree,orco1,ptn,3); - + maxd=ptn[maxw-1].dist; /* mind=ptn[0].dist; */ /* UNUSED */ - + /* the weights here could be done better */ for (w=0; w<maxw; w++) { parent[w]=ptn[w].index; @@ -676,7 +686,7 @@ static void distribute_children_exec(ParticleTask *thread, ChildParticle *cpa, i parent[w]=-1; pweight[w]=0.0f; } - + for (w=0,i=0; w<maxw && i<4; w++) { if (parent[w]>=0) { cpa->pa[i]=parent[w]; @@ -689,13 +699,13 @@ static void distribute_children_exec(ParticleTask *thread, ChildParticle *cpa, i cpa->pa[i]=-1; cpa->w[i]=0.0f; } - + if (totw > 0.0f) { for (w = 0; w < 4; w++) { cpa->w[w] /= totw; } } - + cpa->parent=cpa->pa[0]; } @@ -711,7 +721,7 @@ static void exec_distribute_parent(TaskPool * __restrict UNUSED(pool), void *tas int p; BLI_rng_skip(task->rng, PSYS_RND_DIST_SKIP * task->begin); - + pa= psys->particles + task->begin; switch (psys->part->from) { case PART_FROM_FACE: @@ -735,13 +745,13 @@ static void exec_distribute_child(TaskPool * __restrict UNUSED(pool), void *task ParticleSystem *psys = task->ctx->sim.psys; ChildParticle *cpa; int p; - + /* RNG skipping at the beginning */ cpa = psys->child; for (p = 0; p < task->begin; ++p, ++cpa) { BLI_rng_skip(task->rng, PSYS_RND_DIST_SKIP); } - + for (; p < task->end; ++p, ++cpa) { distribute_children_exec(task, cpa, p); } @@ -818,21 +828,22 @@ static int psys_thread_context_init_distribute(ParticleThreadContext *ctx, Parti int jitlevel= 1, distr; float *element_weight=NULL,*jitter_offset=NULL, *vweight=NULL; float cur, maxweight=0.0, tweight, totweight, inv_totweight, co[3], nor[3], orco[3]; - + RNG *rng = NULL; + if (ELEM(NULL, ob, psys, psys->part)) return 0; - + part=psys->part; totpart=psys->totpart; if (totpart==0) return 0; - + if (!final_mesh->runtime.deformed_only && !CustomData_get_layer(&final_mesh->fdata, CD_ORIGINDEX)) { printf("Can't create particles with the current modifier stack, disable destructive modifiers\n"); // XXX error("Can't paint with the current modifier stack, disable destructive modifiers"); return 0; } - + /* XXX This distribution code is totally broken in case from == PART_FROM_CHILD, it's always using finaldm * even if use_modifier_stack is unset... But making things consistent here break all existing edited * hair systems, so better wait for complete rewrite. @@ -841,12 +852,11 @@ static int psys_thread_context_init_distribute(ParticleThreadContext *ctx, Parti psys_thread_context_init(ctx, sim); const bool use_render_params = (DEG_get_mode(sim->depsgraph) == DAG_EVAL_RENDER); - + /* First handle special cases */ if (from == PART_FROM_CHILD) { /* Simple children */ if (part->childtype != PART_CHILD_FACES) { - BLI_srandom(31415926 + psys->seed + psys->child_seed); distribute_simple_children(scene, ob, final_mesh, sim->psmd->mesh_original, psys, use_render_params); return 0; } @@ -854,8 +864,6 @@ static int psys_thread_context_init_distribute(ParticleThreadContext *ctx, Parti else { /* Grid distribution */ if (part->distr==PART_DISTR_GRID && from != PART_FROM_VERT) { - BLI_srandom(31415926 + psys->seed); - if (psys->part->use_modifier_stack) { mesh = final_mesh; } @@ -879,11 +887,11 @@ static int psys_thread_context_init_distribute(ParticleThreadContext *ctx, Parti return 0; } } - + /* Create trees and original coordinates if needed */ if (from == PART_FROM_CHILD) { - distr=PART_DISTR_RAND; - BLI_srandom(31415926 + psys->seed + psys->child_seed); + distr = PART_DISTR_RAND; + rng = BLI_rng_new_srandom(31415926 + psys->seed + psys->child_seed); mesh= final_mesh; /* BMESH ONLY */ @@ -906,8 +914,9 @@ static int psys_thread_context_init_distribute(ParticleThreadContext *ctx, Parti } else { distr = part->distr; - BLI_srandom(31415926 + psys->seed); - + + rng = BLI_rng_new_srandom(31415926 + psys->seed); + if (psys->part->use_modifier_stack) mesh = final_mesh; else @@ -958,6 +967,7 @@ static int psys_thread_context_init_distribute(ParticleThreadContext *ctx, Parti if (mesh != final_mesh) BKE_id_free(NULL, mesh); BLI_kdtree_free(tree); + BLI_rng_free(rng); return 0; } @@ -971,7 +981,7 @@ static int psys_thread_context_init_distribute(ParticleThreadContext *ctx, Parti MVert *v1, *v2, *v3, *v4; float totarea=0.f, co1[3], co2[3], co3[3], co4[3]; float (*orcodata)[3]; - + orcodata = CustomData_get_layer(&mesh->vdata, CD_ORCO); for (i=0; i<totelem; i++) { @@ -1003,7 +1013,7 @@ static int psys_thread_context_init_distribute(ParticleThreadContext *ctx, Parti } cur = mf->v4 ? area_quad_v3(co1, co2, co3, co4) : area_tri_v3(co1, co2, co3); - + if (cur > maxweight) maxweight = cur; @@ -1035,7 +1045,7 @@ static int psys_thread_context_init_distribute(ParticleThreadContext *ctx, Parti for (i=0;i<totelem; i++) { MFace *mf = &mesh->mface[i]; tweight = vweight[mf->v1] + vweight[mf->v2] + vweight[mf->v3]; - + if (mf->v4) { tweight += vweight[mf->v4]; tweight /= 4.0f; @@ -1098,7 +1108,7 @@ static int psys_thread_context_init_distribute(ParticleThreadContext *ctx, Parti for (p = 0; p < totpart; p++) { /* In theory element_sum[totmapped - 1] should be 1.0, * but due to float errors this is not necessarily always true, so scale pos accordingly. */ - const float pos = BLI_frand() * element_sum[totmapped - 1]; + const float pos = BLI_rng_get_float(rng) * element_sum[totmapped - 1]; const int eidx = distribute_binary_search(element_sum, totmapped, pos); particle_element[p] = element_map[eidx]; BLI_assert(pos <= element_sum[eidx]); @@ -1108,7 +1118,7 @@ static int psys_thread_context_init_distribute(ParticleThreadContext *ctx, Parti } else { double step, pos; - + step = (totpart < 2) ? 0.5 : 1.0 / (double)totpart; /* This is to address tricky issues with vertex-emitting when user tries (and expects) exact 1-1 vert/part * distribution (see T47983 and its two example files). It allows us to consider pos as @@ -1152,17 +1162,17 @@ static int psys_thread_context_init_distribute(ParticleThreadContext *ctx, Parti /* Create jittering if needed */ if (distr==PART_DISTR_JIT && ELEM(from,PART_FROM_FACE,PART_FROM_VOLUME)) { jitlevel= part->userjit; - + if (jitlevel == 0) { jitlevel= totpart/totelem; if (part->flag & PART_EDISTR) jitlevel*= 2; /* looks better in general, not very scientific */ if (jitlevel<3) jitlevel= 3; } - + jit= MEM_callocN((2+ jitlevel*2)*sizeof(float), "jit"); /* for small amounts of particles we use regular jitter since it looks - * a bit better, for larger amounts we switch to hammersley sequence + * a bit better, for larger amounts we switch to hammersley sequence * because it is much faster */ if (jitlevel < 25) init_mv_jit(jit, jitlevel, psys->seed, part->jitfac); @@ -1191,6 +1201,8 @@ static int psys_thread_context_init_distribute(ParticleThreadContext *ctx, Parti alloc_child_particles(psys, totpart); } + BLI_rng_free(rng); + return 1; } @@ -1198,7 +1210,7 @@ static void psys_task_init_distribute(ParticleTask *task, ParticleSimulationData { /* init random number generator */ int seed = 31415926 + sim->psys->seed; - + task->rng = BLI_rng_new(seed); } @@ -1210,19 +1222,19 @@ static void distribute_particles_on_dm(ParticleSimulationData *sim, int from) ParticleTask *tasks; Mesh *final_mesh = sim->psmd->mesh_final; int i, totpart, numtasks; - + /* create a task pool for distribution tasks */ if (!psys_thread_context_init_distribute(&ctx, sim, from)) return; - + task_scheduler = BLI_task_scheduler_get(); task_pool = BLI_task_pool_create(task_scheduler, &ctx); - + totpart = (from == PART_FROM_CHILD ? sim->psys->totchild : sim->psys->totpart); psys_tasks_create(&ctx, 0, totpart, &tasks, &numtasks); for (i = 0; i < numtasks; ++i) { ParticleTask *task = &tasks[i]; - + psys_task_init_distribute(task, sim); if (from == PART_FROM_CHILD) BLI_task_pool_push(task_pool, exec_distribute_child, task, false, TASK_PRIORITY_LOW); @@ -1230,16 +1242,16 @@ static void distribute_particles_on_dm(ParticleSimulationData *sim, int from) BLI_task_pool_push(task_pool, exec_distribute_parent, task, false, TASK_PRIORITY_LOW); } BLI_task_pool_work_and_wait(task_pool); - + BLI_task_pool_free(task_pool); - + psys_calc_dmcache(sim->ob, final_mesh, sim->psmd->mesh_original, sim->psys); - + if (ctx.mesh != final_mesh) BKE_id_free(NULL, ctx.mesh); - + psys_tasks_free(tasks, numtasks); - + psys_thread_context_free(&ctx); } diff --git a/source/blender/blenkernel/intern/particle_system.c b/source/blender/blenkernel/intern/particle_system.c index 8d6991ff9f4..1c50e85668d 100644 --- a/source/blender/blenkernel/intern/particle_system.c +++ b/source/blender/blenkernel/intern/particle_system.c @@ -242,7 +242,7 @@ static void realloc_particles(ParticleSimulationData *sim, int new_totpart) } } } - + if (psys->particles) { totsaved=MIN2(psys->totpart,totpart); /*save old pars*/ @@ -272,7 +272,7 @@ static void realloc_particles(ParticleSimulationData *sim, int new_totpart) MEM_freeN(psys->particles); psys_free_pdd(psys); } - + psys->particles=newpars; psys->totpart=totpart; @@ -317,14 +317,14 @@ void psys_calc_dmcache(Object *ob, Mesh *mesh_final, Mesh *mesh_original, Partic { /* use for building derived mesh mapping info: * - * node: the allocated links - total derived mesh element count + * node: the allocated links - total derived mesh element count * nodearray: the array of nodes aligned with the base mesh's elements, so * each original elements can reference its derived elements */ Mesh *me= (Mesh*)ob->data; bool use_modifier_stack= psys->part->use_modifier_stack; PARTICLE_P; - + /* CACHE LOCATIONS */ if (!mesh_final->runtime.deformed_only) { /* Will use later to speed up subsurf/derivedmesh */ @@ -428,7 +428,7 @@ void psys_calc_dmcache(Object *ob, Mesh *mesh_final, Mesh *mesh_original, Partic /* TODO PARTICLE, make the following line unnecessary, each function * should know to use the num or num_dmcache, set the num_dmcache to * an invalid value, just in case */ - + LOOP_PARTICLES { pa->num_dmcache = DMCACHE_NOTFOUND; } @@ -457,15 +457,15 @@ void psys_tasks_create(ParticleThreadContext *ctx, int startpart, int endpart, P int numtasks = ceil_ii((endpart - startpart), MAX_PARTICLES_PER_TASK); float particles_per_task = (float)(endpart - startpart) / (float)numtasks, p, pnext; int i; - + tasks = MEM_callocN(sizeof(ParticleTask) * numtasks, "ParticleThread"); *r_numtasks = numtasks; *r_tasks = tasks; - + p = (float)startpart; for (i = 0; i < numtasks; i++, p = pnext) { pnext = p + particles_per_task; - + tasks[i].ctx = ctx; tasks[i].begin = (int)p; tasks[i].end = min_ii((int)pnext, endpart); @@ -475,7 +475,7 @@ void psys_tasks_create(ParticleThreadContext *ctx, int startpart, int endpart, P void psys_tasks_free(ParticleTask *tasks, int numtasks) { int i; - + /* threads */ for (i = 0; i < numtasks; ++i) { if (tasks[i].rng) @@ -537,7 +537,7 @@ static void initialize_particle_texture(ParticleSimulationData *sim, ParticleDat ParticleTexture ptex; psys_get_texture(sim, pa, &ptex, PAMAP_INIT, 0.f); - + switch (part->type) { case PART_EMITTER: if (ptex.exist < psys_frand(psys, p + 125)) { @@ -561,7 +561,7 @@ void initialize_particle(ParticleSimulationData *sim, ParticleData *pa) { ParticleSettings *part = sim->psys->part; float birth_time = (float)(pa - sim->psys->particles) / (float)sim->psys->totpart; - + pa->flag &= ~PARS_UNEXIST; pa->time = part->sta + (part->end - part->sta) * birth_time; @@ -620,7 +620,7 @@ static void free_unexisting_particles(ParticleSimulationData *sim) if (psys->totunexist) { int newtotpart = psys->totpart - psys->totunexist; ParticleData *npa, *newpars; - + npa = newpars = MEM_callocN(newtotpart * sizeof(ParticleData), "particles"); for (p=0, pa=psys->particles; p<newtotpart; p++, pa++, npa++) { @@ -708,7 +708,7 @@ void psys_get_birth_coords(ParticleSimulationData *sim, ParticleData *pa, Partic psys_particle_on_emitter(sim->psmd, part->from,pa->num, pa->num_dmcache, pa->fuv,pa->foffset,loc,nor,utan,vtan,0); else psys_particle_on_emitter(sim->psmd, part->from,pa->num, pa->num_dmcache, pa->fuv,pa->foffset,loc,nor,0,0,0); - + /* get possible textural influence */ psys_get_texture(sim, pa, &ptex, PAMAP_IVEL, cfra); @@ -716,7 +716,7 @@ void psys_get_birth_coords(ParticleSimulationData *sim, ParticleData *pa, Partic /* let's convert: */ /* -location */ mul_m4_v3(ob->obmat, loc); - + /* -normal */ mul_mat3_m4_v3(ob->obmat, nor); normalize_v3(nor); @@ -734,10 +734,10 @@ void psys_get_birth_coords(ParticleSimulationData *sim, ParticleData *pa, Partic copy_v3_v3(utan, nor); mul_v3_fl(utan,dot_v3v3(vtan,nor)); sub_v3_v3(vtan, utan); - + normalize_v3(vtan); } - + /* -velocity (boids need this even if there's no random velocity) */ if (part->randfac != 0.0f || (part->phystype==PART_PHYS_BOIDS && pa->boid)) { @@ -758,7 +758,7 @@ void psys_get_birth_coords(ParticleSimulationData *sim, ParticleData *pa, Partic mul_mat3_m4_v3(ob->obmat,r_ave); normalize_v3(r_ave); } - + /* -rotation */ if (part->randrotfac != 0.0f) { r_rot[0] = 2.0f * (psys_frand(psys, p + 16) - 0.5f); @@ -795,7 +795,7 @@ void psys_get_birth_coords(ParticleSimulationData *sim, ParticleData *pa, Partic negate_v3_v3(mat[2], r_vel); normalize_v3(mat[2]); cross_v3_v3v3(mat[1], mat[2], mat[0]); - + /* apply rotation */ mat3_to_quat_is_ok( q,mat); copy_qt_qt(state->rot, q); @@ -814,11 +814,11 @@ void psys_get_birth_coords(ParticleSimulationData *sim, ParticleData *pa, Partic sub_v3_v3v3(vel, loc, state->co); mul_v3_fl(vel, part->obfac/dtime); } - + /* *emitter normal */ if (part->normfac != 0.f) madd_v3_v3fl(vel, nor, part->normfac); - + /* *emitter tangent */ if (sim->psmd && part->tanfac != 0.f) madd_v3_v3fl(vel, vtan, part->tanfac); @@ -847,7 +847,7 @@ void psys_get_birth_coords(ParticleSimulationData *sim, ParticleData *pa, Partic /* *particle */ if (part->partfac != 0.f) madd_v3_v3fl(vel, p_vel, part->partfac); - + mul_v3_v3fl(state->vel, vel, ptex.ivel); /* -location from emitter */ @@ -886,7 +886,7 @@ void psys_get_birth_coords(ParticleSimulationData *sim, ParticleData *pa, Partic use_global_space = true; break; } - + /* create rotation quat */ @@ -995,7 +995,7 @@ static void evaluate_emitter_anim(struct Depsgraph *depsgraph, Scene *scene, Obj { if (ob->parent) evaluate_emitter_anim(depsgraph, scene, ob->parent, cfra); - + /* we have to force RECALC_ANIM here since where_is_objec_time only does drivers */ BKE_animsys_evaluate_animdata(depsgraph, scene, &ob->id, ob->adt, cfra, ADT_RECALC_ANIM); BKE_object_where_is_calc_time(depsgraph, scene, ob, cfra); @@ -1009,7 +1009,7 @@ void reset_particle(ParticleSimulationData *sim, ParticleData *pa, float dtime, ParticleTexture ptex; int p = pa - psys->particles; part=psys->part; - + /* get precise emitter matrix if particle is born */ if (part->type != PART_HAIR && dtime > 0.f && pa->time < cfra && pa->time >= sim->psys->cfra) { evaluate_emitter_anim(sim->depsgraph, sim->scene, sim->ob, pa->time); @@ -1086,7 +1086,7 @@ static void reset_all_particles(ParticleSimulationData *sim, float dtime, float { ParticleData *pa; int p, totpart=sim->psys->totpart; - + for (p=from, pa=sim->psys->particles+from; p<totpart; p++, pa++) reset_particle(sim, pa, dtime, cfra); } @@ -1148,7 +1148,7 @@ static void set_keyed_keys(ParticleSimulationData *sim) ksim.depsgraph = sim->depsgraph; ksim.scene = sim->scene; - + /* no proper targets so let's clear and bail out */ if (psys->totkeyed==0) { free_keyed_keys(psys); @@ -1158,16 +1158,16 @@ static void set_keyed_keys(ParticleSimulationData *sim) if (totpart && psys->particles->totkey != totkeys) { free_keyed_keys(psys); - + key = MEM_callocN(totpart*totkeys*sizeof(ParticleKey), "Keyed keys"); - + LOOP_PARTICLES { pa->keys = key; pa->totkey = totkeys; key += totkeys; } } - + psys->flag &= ~PSYS_KEYED; @@ -1249,17 +1249,17 @@ static void psys_update_particle_bvhtree(ParticleSystem *psys, float cfra) BLI_rw_mutex_lock(&psys_bvhtree_rwlock, THREAD_LOCK_READ); need_rebuild = !psys->bvhtree || psys->bvhtree_frame != cfra; BLI_rw_mutex_unlock(&psys_bvhtree_rwlock); - + if (need_rebuild) { LOOP_SHOWN_PARTICLES { totpart++; } - + BLI_rw_mutex_lock(&psys_bvhtree_rwlock, THREAD_LOCK_WRITE); - + BLI_bvhtree_free(psys->bvhtree); psys->bvhtree = BLI_bvhtree_new(totpart, 0.0, 4, 6); - + LOOP_SHOWN_PARTICLES { if (pa->alive == PARS_ALIVE) { if (pa->state.time == cfra) @@ -1269,9 +1269,9 @@ static void psys_update_particle_bvhtree(ParticleSystem *psys, float cfra) } } BLI_bvhtree_balance(psys->bvhtree); - + psys->bvhtree_frame = cfra; - + BLI_rw_mutex_unlock(&psys_bvhtree_rwlock); } } @@ -1365,7 +1365,7 @@ static void integrate_particle(ParticleSettings *part, ParticleData *pa, float d if (external_acceleration) add_v3_v3(acceleration, external_acceleration); - + /* calculate next state */ add_v3_v3(states[i].vel, impulse); @@ -1498,7 +1498,7 @@ static void sph_springs_modify(ParticleSystem *psys, float dtime) SPHFluidSettings *fluid = psys->part->fluid; ParticleData *pa1, *pa2; ParticleSpring *spring = psys->fluid_springs; - + float h, d, Rij[3], rij, Lij; int i; @@ -1591,9 +1591,9 @@ static void sph_evaluate_func(BVHTree *tree, ParticleSystem **psys, float co[3], } else { BLI_rw_mutex_lock(&psys_bvhtree_rwlock, THREAD_LOCK_READ); - + BLI_bvhtree_range_query(psys[i]->bvhtree, co, interaction_radius, callback, pfr); - + BLI_rw_mutex_unlock(&psys_bvhtree_rwlock); } } @@ -1773,7 +1773,7 @@ static void sph_force_cb(void *sphdata_v, ParticleKey *state, float *force, floa } } } - + /* Artificial buoyancy force in negative gravity direction */ if (fluid->buoyancy > 0.f && gravity) madd_v3_v3fl(force, gravity, fluid->buoyancy * (density-rest_density)); @@ -2061,6 +2061,7 @@ static void basic_force_cb(void *efdata_v, ParticleKey *state, float *force, flo ParticleSettings *part = sim->psys->part; ParticleData *pa = efdata->pa; EffectedPoint epoint; + RNG *rng = sim->rng; /* add effectors */ pd_point_from_particle(efdata->sim, efdata->pa, state, &epoint); @@ -2076,9 +2077,9 @@ static void basic_force_cb(void *efdata_v, ParticleKey *state, float *force, flo /* brownian force */ if (part->brownfac != 0.0f) { - force[0] += (BLI_frand()-0.5f) * part->brownfac; - force[1] += (BLI_frand()-0.5f) * part->brownfac; - force[2] += (BLI_frand()-0.5f) * part->brownfac; + force[0] += (BLI_rng_get_float(rng)-0.5f) * part->brownfac; + force[1] += (BLI_rng_get_float(rng)-0.5f) * part->brownfac; + force[2] += (BLI_rng_get_float(rng)-0.5f) * part->brownfac; } if (part->flag & PART_ROT_DYN && epoint.ave) @@ -2520,7 +2521,7 @@ static int collision_sphere_to_edges(ParticleCollision *col, float radius, Parti result->uv[0] = u; - + hit = cur; *t = ct; } @@ -2545,7 +2546,7 @@ static int collision_sphere_to_verts(ParticleCollision *col, float radius, Parti cur->inside = 0; ct = collision_newton_rhapson(col, radius, cur, nr_distance_to_vert); - + if (ct >= 0.f && ct < *t) { *result = *cur; @@ -2649,16 +2650,17 @@ static int collision_detect(ParticleData *pa, ParticleCollision *col, BVHTreeRay return hit->index >= 0; } -static int collision_response(ParticleData *pa, ParticleCollision *col, BVHTreeRayHit *hit, int kill, int dynamic_rotation) +static int collision_response(ParticleSimulationData *sim, ParticleData *pa, ParticleCollision *col, BVHTreeRayHit *hit, int kill, int dynamic_rotation) { ParticleCollisionElement *pce = &col->pce; PartDeflect *pd = col->hit->pd; + RNG *rng = sim->rng; float co[3]; /* point of collision */ float x = hit->dist/col->original_ray_length; /* location factor of collision between this iteration */ float f = col->f + x * (1.0f - col->f); /* time factor of collision between timestep */ float dt1 = (f - col->f) * col->total_time; /* time since previous collision (in seconds) */ float dt2 = (1.0f - f) * col->total_time; /* time left after collision (in seconds) */ - int through = (BLI_frand() < pd->pdef_perm) ? 1 : 0; /* did particle pass through the collision surface? */ + int through = (BLI_rng_get_float(rng) < pd->pdef_perm) ? 1 : 0; /* did particle pass through the collision surface? */ /* calculate exact collision location */ interp_v3_v3v3(co, col->co1, col->co2, x); @@ -2683,8 +2685,8 @@ static int collision_response(ParticleData *pa, ParticleCollision *col, BVHTreeR float v0_tan[3];/* tangential component of v0 */ float vc_tan[3];/* tangential component of collision surface velocity */ float v0_dot, vc_dot; - float damp = pd->pdef_damp + pd->pdef_rdamp * 2 * (BLI_frand() - 0.5f); - float frict = pd->pdef_frict + pd->pdef_rfrict * 2 * (BLI_frand() - 0.5f); + float damp = pd->pdef_damp + pd->pdef_rdamp * 2 * (BLI_rng_get_float(rng) - 0.5f); + float frict = pd->pdef_frict + pd->pdef_rfrict * 2 * (BLI_rng_get_float(rng) - 0.5f); float distance, nor[3], dot; CLAMP(damp,0.0f, 1.0f); @@ -2692,7 +2694,7 @@ static int collision_response(ParticleData *pa, ParticleCollision *col, BVHTreeR /* get exact velocity right before collision */ madd_v3_v3v3fl(v0, col->ve1, col->acc, dt1); - + /* convert collider velocity from 1/framestep to 1/s TODO: here we assume 1 frame step for collision modifier */ mul_v3_fl(pce->vel, col->inv_timestep); @@ -2709,14 +2711,14 @@ static int collision_response(ParticleData *pa, ParticleCollision *col, BVHTreeR /* angular <-> linear velocity */ if (dynamic_rotation) { float vr_tan[3], v1_tan[3], ave[3]; - + /* linear velocity of particle surface */ cross_v3_v3v3(vr_tan, pce->nor, pa->state.ave); mul_v3_fl(vr_tan, pa->size); /* change to coordinates that move with the collision plane */ sub_v3_v3v3(v1_tan, v0_tan, vc_tan); - + /* The resulting velocity is a weighted average of particle cm & surface * velocity. This weight (related to particle's moment of inertia) could * be made a parameter for angular <-> linear conversion. @@ -2779,7 +2781,7 @@ static int collision_response(ParticleData *pa, ParticleCollision *col, BVHTreeR v0[2] = 0.0f; } } - + /* re-apply acceleration to final location and velocity */ madd_v3_v3v3fl(pa->state.co, co, v0, dt2); madd_v3_v3fl(pa->state.co, col->acc, 0.5f*dt2*dt2); @@ -2788,7 +2790,7 @@ static int collision_response(ParticleData *pa, ParticleCollision *col, BVHTreeR /* make sure particle stays on the right side of the surface */ if (!through) { distance = collision_point_distance_with_normal(co, pce, -1.f, col, nor); - + if (distance < col->radius + COLLISION_MIN_DISTANCE) madd_v3_v3fl(co, nor, col->radius + COLLISION_MIN_DISTANCE - distance); @@ -2889,12 +2891,12 @@ static void collision_check(ParticleSimulationData *sim, int p, float dfra, floa /* 10 iterations to catch multiple collisions */ while (collision_count < PARTICLE_COLLISION_MAX_COLLISIONS) { if (collision_detect(pa, &col, &hit, sim->colliders)) { - + collision_count++; if (collision_count == PARTICLE_COLLISION_MAX_COLLISIONS) collision_fail(pa, &col); - else if (collision_response(pa, &col, &hit, part->flag & PART_DIE_ON_COL, part->flag & PART_ROT_DYN)==0) + else if (collision_response(sim, pa, &col, &hit, part->flag & PART_DIE_ON_COL, part->flag & PART_ROT_DYN)==0) return; } else @@ -2995,19 +2997,19 @@ static bool psys_hair_use_simulation(ParticleData *pa, float max_length) * but this can happen in old files when e.g. cutting hair. */ const float min_length = 0.1f * max_length; - + HairKey *key; int k; - + if (pa->totkey < 2) return false; - + for (k=1, key=pa->hair+1; k<pa->totkey; k++,key++) { float length = len_v3v3(key->co, (key-1)->co); if (length < min_length) return false; } - + return true; } @@ -3018,7 +3020,7 @@ static MDeformVert *hair_set_pinning(MDeformVert *dvert, float weight) dvert->dw = MEM_callocN(sizeof(MDeformWeight), "deformWeight"); dvert->totweight = 1; } - + dvert->dw->weight = weight; dvert++; } @@ -3040,7 +3042,7 @@ static void hair_create_input_mesh(ParticleSimulationData *sim, int totpoint, in float hairmat[4][4]; float max_length; float hair_radius; - + mesh = *r_mesh; if (!mesh) { *r_mesh = mesh = BKE_mesh_new_nomain(totpoint, totedge, 0, 0, 0); @@ -3050,12 +3052,12 @@ static void hair_create_input_mesh(ParticleSimulationData *sim, int totpoint, in mvert = mesh->mvert; medge = mesh->medge; dvert = mesh->dvert; - + hairdata = *r_hairdata; if (!hairdata) { *r_hairdata = hairdata = MEM_mallocN(sizeof(ClothHairData) * totpoint, "hair data"); } - + /* calculate maximum segment length */ max_length = 0.0f; LOOP_PARTICLES { @@ -3067,12 +3069,12 @@ static void hair_create_input_mesh(ParticleSimulationData *sim, int totpoint, in } } } - + psys->clmd->sim_parms->vgroup_mass = 1; - + /* XXX placeholder for more flexible future hair settings */ hair_radius = part->size; - + /* make vgroup for pin roots etc.. */ hair_index = 1; LOOP_PARTICLES { @@ -3160,7 +3162,7 @@ static void do_hair_dynamics(ParticleSimulationData *sim) int totedge; float (*deformedVerts)[3]; bool realloc_roots; - + if (!psys->clmd) { psys->clmd = (ClothModifierData*)modifier_new(eModifierType_Cloth); psys->clmd->sim_parms->goalspring = 0.0f; @@ -3168,7 +3170,7 @@ static void do_hair_dynamics(ParticleSimulationData *sim) psys->clmd->sim_parms->flags |= CLOTH_SIMSETTINGS_FLAG_GOAL|CLOTH_SIMSETTINGS_FLAG_NO_SPRING_COMPRESS; psys->clmd->coll_parms->flags &= ~CLOTH_COLLSETTINGS_FLAG_SELF; } - + /* count simulated points */ totpoint = 0; totedge = 0; @@ -3179,7 +3181,7 @@ static void do_hair_dynamics(ParticleSimulationData *sim) totpoint += pa->totkey + 1; /* +1 for virtual root point */ } } - + realloc_roots = false; /* whether hair root info array has to be reallocated */ if (psys->hair_in_mesh) { Mesh *mesh = psys->hair_in_mesh; @@ -3189,26 +3191,26 @@ static void do_hair_dynamics(ParticleSimulationData *sim) realloc_roots = true; } } - + if (!psys->hair_in_mesh || !psys->clmd->hairdata || realloc_roots) { if (psys->clmd->hairdata) { MEM_freeN(psys->clmd->hairdata); psys->clmd->hairdata = NULL; } } - + hair_create_input_mesh(sim, totpoint, totedge, &psys->hair_in_mesh, &psys->clmd->hairdata); - + if (psys->hair_out_mesh) BKE_id_free(NULL, psys->hair_out_mesh); - + psys->clmd->point_cache = psys->pointcache; /* for hair sim we replace the internal cloth effector weights temporarily * to use the particle settings */ clmd_effweights = psys->clmd->sim_parms->effector_weights; psys->clmd->sim_parms->effector_weights = psys->part->effector_weights; - + BKE_id_copy_ex( NULL, &psys->hair_in_mesh->id, (ID **)&psys->hair_out_mesh, LIB_ID_CREATE_NO_MAIN | @@ -3219,9 +3221,9 @@ static void do_hair_dynamics(ParticleSimulationData *sim) deformedVerts = BKE_mesh_vertexCos_get(psys->hair_out_mesh, NULL); clothModifier_do(psys->clmd, sim->depsgraph, sim->scene, sim->ob, psys->hair_in_mesh, deformedVerts); BKE_mesh_apply_vert_coords(psys->hair_out_mesh, deformedVerts); - + MEM_freeN(deformedVerts); - + /* restore cloth effector weights */ psys->clmd->sim_parms->effector_weights = clmd_effweights; } @@ -3270,11 +3272,11 @@ static void save_hair(ParticleSimulationData *sim, float UNUSED(cfra)) PARTICLE_P; invert_m4_m4(ob->imat, ob->obmat); - + psys->lattice_deform_data= psys_create_lattice_deform_data(sim); if (psys->totpart==0) return; - + /* save new keys for elements if needed */ LOOP_PARTICLES { /* first time alloc */ @@ -3427,7 +3429,7 @@ static void dynamics_step_sph_ddr_task_cb_ex( } static void dynamics_step_sph_classical_basic_integrate_task_cb_ex( - void *__restrict userdata, + void *__restrict userdata, const int p, const ParallelRangeTLS *__restrict UNUSED(tls)) { @@ -3502,7 +3504,6 @@ static void dynamics_step(ParticleSimulationData *sim, float cfra) { ParticleSystem *psys = sim->psys; ParticleSettings *part=psys->part; - RNG *rng; BoidBrainData bbd; ParticleTexture ptex; PARTICLE_P; @@ -3529,9 +3530,8 @@ static void dynamics_step(ParticleSimulationData *sim, float cfra) return; } - BLI_srandom(31415926 + (int)cfra + psys->seed); /* for now do both, boids us 'rng' */ - rng = BLI_rng_new_srandom(31415926 + (int)cfra + psys->seed); + sim->rng = BLI_rng_new_srandom(31415926 + (int)cfra + psys->seed); psys_update_effectors(sim); @@ -3548,7 +3548,7 @@ static void dynamics_step(ParticleSimulationData *sim, float cfra) bbd.cfra = cfra; bbd.dfra = dfra; bbd.timestep = timestep; - bbd.rng = rng; + bbd.rng = sim->rng; psys_update_particle_tree(psys, cfra); @@ -3566,7 +3566,7 @@ static void dynamics_step(ParticleSimulationData *sim, float cfra) { ParticleTarget *pt = psys->targets.first; psys_update_particle_bvhtree(psys, cfra); - + for (; pt; pt=pt->next) { /* Updating others systems particle tree for fluid-fluid interaction */ if (pt->ob) psys_update_particle_bvhtree(BLI_findlink(&pt->ob->particlesystem, pt->psys-1), cfra); @@ -3623,7 +3623,7 @@ static void dynamics_step(ParticleSimulationData *sim, float cfra) LOOP_DYNAMIC_PARTICLES { /* do global forces & effectors */ basic_integrate(sim, p, pa->state.time, cfra); - + /* deflection */ if (sim->colliders) collision_check(sim, p, pa->state.time, cfra); @@ -3637,7 +3637,7 @@ static void dynamics_step(ParticleSimulationData *sim, float cfra) { LOOP_DYNAMIC_PARTICLES { bbd.goal_ob = NULL; - + boid_brain(&bbd, p, pa); if (pa->alive != PARS_DYING) { @@ -3744,8 +3744,10 @@ static void dynamics_step(ParticleSimulationData *sim, float cfra) } free_collider_cache(&sim->colliders); - BLI_rng_free(rng); + BLI_rng_free(sim->rng); + sim->rng = NULL; } + static void update_children(ParticleSimulationData *sim, const bool use_render_params) { if ((sim->psys->part->type == PART_HAIR) && (sim->psys->flag & PSYS_HAIR_DONE)==0) @@ -3771,7 +3773,7 @@ static void cached_step(ParticleSimulationData *sim, float cfra, const bool use_ float disp, dietime; psys_update_effectors(sim); - + disp= psys_get_current_display_percentage(psys, use_render_params); LOOP_PARTICLES { @@ -3821,7 +3823,7 @@ static void particles_fluid_step( #ifdef WITH_MOD_FLUID { FluidsimModifierData *fluidmd = (FluidsimModifierData *)modifiers_findByType(sim->ob, eModifierType_Fluidsim); - + if ( fluidmd && fluidmd->fss) { FluidsimSettings *fss= fluidmd->fss; ParticleSettings *part = psys->part; @@ -3832,7 +3834,7 @@ static void particles_fluid_step( int p, j, totpart; int readMask, activeParts = 0, fileParts = 0; gzFile gzf; - + // XXX if (ob==G.obedit) // off... // return; @@ -3841,7 +3843,7 @@ static void particles_fluid_step( BLI_path_abs(filename, modifier_path_relbase(bmain, sim->ob)); - BLI_path_frame(filename, curFrame, 0); // fixed #frame-no + BLI_path_frame(filename, curFrame, 0); // fixed #frame-no gzf = BLI_gzopen(filename, "rb"); if (!gzf) { @@ -3849,46 +3851,46 @@ static void particles_fluid_step( // XXX bad level call elbeemDebugOut(debugStrBuffer); return; } - + gzread(gzf, &totpart, sizeof(totpart)); totpart = (use_render_params) ? totpart:(part->disp*totpart) / 100; - + part->totpart= totpart; part->sta=part->end = 1.0f; part->lifetime = sim->scene->r.efra + 1; - + /* allocate particles */ realloc_particles(sim, part->totpart); - + // set up reading mask readMask = fss->typeFlags; - + for (p=0, pa=psys->particles; p<totpart; p++, pa++) { int ptype=0; - - gzread(gzf, &ptype, sizeof( ptype )); + + gzread(gzf, &ptype, sizeof( ptype )); if (ptype & readMask) { activeParts++; - + gzread(gzf, &(pa->size), sizeof(float)); - + pa->size /= 10.0f; - + for (j=0; j<3; j++) { float wrf; - gzread(gzf, &wrf, sizeof( wrf )); + gzread(gzf, &wrf, sizeof( wrf )); pa->state.co[j] = wrf; //fprintf(stderr,"Rj%d ",j); } for (j=0; j<3; j++) { float wrf; - gzread(gzf, &wrf, sizeof( wrf )); + gzread(gzf, &wrf, sizeof( wrf )); pa->state.vel[j] = wrf; } - + zero_v3(pa->state.ave); unit_qt(pa->state.rot); - + pa->time = 1.f; pa->dietime = sim->scene->r.efra + 1; pa->lifetime = sim->scene->r.efra; @@ -3898,18 +3900,18 @@ static void particles_fluid_step( else { // skip... for (j=0; j<2*3+1; j++) { - float wrf; gzread(gzf, &wrf, sizeof( wrf )); + float wrf; gzread(gzf, &wrf, sizeof( wrf )); } } fileParts++; } gzclose(gzf); - + totpart = psys->totpart = activeParts; BLI_snprintf(debugStrBuffer,sizeof(debugStrBuffer),"readFsPartData::done - particles:%d, active:%d, file:%d, mask:%d\n", psys->totpart,activeParts,fileParts,readMask); // bad level call // XXX elbeemDebugOut(debugStrBuffer); - + } // fluid sim particles done } #else @@ -3955,7 +3957,7 @@ static void system_step(ParticleSimulationData *sim, float cfra, const bool use_ pid = &ptcacheid; BKE_ptcache_id_from_particles(pid, sim->ob, psys); - + BKE_ptcache_id_time(pid, sim->scene, 0.0f, &startframe, &endframe, NULL); /* clear everything on start frame, or when psys needs full reset! */ @@ -3964,7 +3966,7 @@ static void system_step(ParticleSimulationData *sim, float cfra, const bool use_ BKE_ptcache_validate(cache, startframe); cache->flag &= ~PTCACHE_REDO_NEEDED; } - + CLAMP(cache_cfra, startframe, endframe); } @@ -4073,7 +4075,7 @@ static void system_step(ParticleSimulationData *sim, float cfra, const bool use_ } } } - + /* 4. only write cache starting from second frame */ if (pid) { BKE_ptcache_validate(cache, (int)cache_cfra); @@ -4209,7 +4211,9 @@ void particle_system_update(struct Depsgraph *depsgraph, Scene *scene, Object *o { ParticleSimulationData sim= {0}; ParticleSettings *part = psys->part; + ParticleSystem *psys_orig = psys_orig_get(psys); float cfra; + ParticleSystemModifierData *psmd = psys_get_modifier(ob, psys); /* drawdata is outdated after ANY change */ if (psys->pdd) psys->pdd->flag &= ~PARTICLE_DRAW_DATA_UPDATED; @@ -4217,25 +4221,13 @@ void particle_system_update(struct Depsgraph *depsgraph, Scene *scene, Object *o if (!psys_check_enabled(ob, psys, use_render_params)) return; - if (DEG_is_active(depsgraph)) { - if (psys->orig_psys != NULL && psys->orig_psys->edit != NULL) { - psys_cache_edit_paths( - depsgraph, - (Scene *)DEG_get_original_id(&scene->id), - DEG_get_original_object(ob), - psys->orig_psys->edit, - DEG_get_ctime(depsgraph), - DEG_get_mode(depsgraph) == DAG_EVAL_RENDER); - } - } - cfra = DEG_get_ctime(depsgraph); sim.depsgraph = depsgraph; sim.scene = scene; sim.ob = ob; sim.psys = psys; - sim.psmd = psys_get_modifier(ob, psys); + sim.psmd = psmd; /* system was already updated from modifier stack */ if (sim.psmd->flag & eParticleSystemFlag_psys_updated) { @@ -4280,10 +4272,10 @@ void particle_system_update(struct Depsgraph *depsgraph, Scene *scene, Object *o free_hair(ob, psys, 0); - if (psys->edit && psys->free_edit) { - psys->free_edit(psys->edit); - psys->edit = NULL; - psys->free_edit = NULL; + if (psys_orig->edit && psys_orig->free_edit) { + psys_orig->free_edit(psys_orig->edit); + psys_orig->edit = NULL; + psys_orig->free_edit = NULL; } /* first step is negative so particles get killed and reset */ @@ -4379,6 +4371,22 @@ void particle_system_update(struct Depsgraph *depsgraph, Scene *scene, Object *o psys->flag &= ~PSYS_OB_ANIM_RESTORE; } + if (psys_orig->edit) { + psys_orig->edit->flags |= PT_CACHE_EDIT_UPDATE_PARTICLE_FROM_EVAL; + } + + if (DEG_is_active(depsgraph)) { + if (psys_orig != psys) { + if (psys_orig->edit != NULL && + psys_orig->edit->psys == psys_orig) + { + psys_orig->edit->psys_eval = psys; + psys_orig->edit->psmd_eval = psmd; + } + psys_orig->flag = psys->flag; + } + } + psys->cfra = cfra; psys->recalc = 0; diff --git a/source/blender/blenkernel/intern/pbvh.c b/source/blender/blenkernel/intern/pbvh.c index 8cc8a8510f2..0a4cd3ec3c1 100644 --- a/source/blender/blenkernel/intern/pbvh.c +++ b/source/blender/blenkernel/intern/pbvh.c @@ -134,7 +134,7 @@ static void update_node_vb(PBVH *bvh, PBVHNode *node) BB vb; BB_reset(&vb); - + if (node->flag & PBVH_Leaf) { PBVHVertexIter vd; @@ -185,10 +185,10 @@ static int partition_indices(int *prim_indices, int lo, int hi, int axis, for (;; ) { for (; prim_bbc[prim_indices[i]].bcentroid[axis] < mid; i++) ; for (; mid < prim_bbc[prim_indices[j]].bcentroid[axis]; j--) ; - + if (!(i < j)) return i; - + SWAP(int, prim_indices[i], prim_indices[j]); i++; } @@ -218,7 +218,7 @@ static int partition_indices_material(PBVH *bvh, int lo, int hi) for (; grid_materials_match(first, &flagmats[indices[i]]); i++) ; for (; !grid_materials_match(first, &flagmats[indices[j]]); j--) ; } - + if (!(i < j)) return i; @@ -390,7 +390,7 @@ static void build_leaf(PBVH *bvh, int node_index, BBC *prim_bbc, /* Still need vb for searches */ update_vb(bvh, &bvh->nodes[node_index], prim_bbc, offset, count); - + if (bvh->looptri) build_mesh_leaf_node(bvh, bvh->nodes + node_index); else { @@ -1281,7 +1281,7 @@ void BKE_pbvh_get_grid_updates(PBVH *bvh, bool clear, void ***r_gridfaces, int * } pbvh_iter_end(&iter); - + const int tot = BLI_gset_len(face_set); if (tot == 0) { *r_totface = 0; @@ -1384,7 +1384,7 @@ void BKE_pbvh_node_mark_normals_update(PBVHNode *node) void BKE_pbvh_node_fully_hidden_set(PBVHNode *node, int fully_hidden) { BLI_assert(node->flag & PBVH_Leaf); - + if (fully_hidden) node->flag |= PBVH_FullyHidden; else @@ -1409,7 +1409,7 @@ void BKE_pbvh_node_num_verts( int *r_uniquevert, int *r_totvert) { int tot; - + switch (bvh->type) { case PBVH_GRIDS: tot = node->totprim * bvh->gridkey.grid_area; @@ -2011,7 +2011,7 @@ static PlaneAABBIsect test_planes_aabb(const float bb_min[3], { float vmin[3], vmax[3]; PlaneAABBIsect ret = ISECT_INSIDE; - + for (int i = 0; i < 4; ++i) { for (int axis = 0; axis < 3; ++axis) { if (planes[i][axis] > 0) { @@ -2023,7 +2023,7 @@ static PlaneAABBIsect test_planes_aabb(const float bb_min[3], vmax[axis] = bb_min[axis]; } } - + if (dot_v3v3(planes[i], vmin) + planes[i][3] > 0) return ISECT_OUTSIDE; else if (dot_v3v3(planes[i], vmax) + planes[i][3] >= 0) @@ -2039,7 +2039,7 @@ bool BKE_pbvh_node_planes_contain_AABB(PBVHNode *node, void *data) /* BKE_pbvh_node_get_BB */ bb_min = node->vb.bmin; bb_max = node->vb.bmax; - + return test_planes_aabb(bb_min, bb_max, data) != ISECT_OUTSIDE; } @@ -2049,7 +2049,7 @@ bool BKE_pbvh_node_planes_exclude_AABB(PBVHNode *node, void *data) /* BKE_pbvh_node_get_BB */ bb_min = node->vb.bmin; bb_max = node->vb.bmax; - + return test_planes_aabb(bb_min, bb_max, data) != ISECT_INSIDE; } @@ -2311,22 +2311,22 @@ void pbvh_vertex_iter_init(PBVH *bvh, PBVHNode *node, const int *vert_indices; int *grid_indices; int totgrid, gridsize, uniq_verts, totvert; - + vi->grid = NULL; vi->no = NULL; vi->fno = NULL; vi->mvert = NULL; - + BKE_pbvh_node_get_grids(bvh, node, &grid_indices, &totgrid, NULL, &gridsize, &grids); BKE_pbvh_node_num_verts(bvh, node, &uniq_verts, &totvert); BKE_pbvh_node_get_verts(bvh, node, &vert_indices, &verts); vi->key = &bvh->gridkey; - + vi->grids = grids; vi->grid_indices = grid_indices; vi->totgrid = (grids) ? totgrid : 1; vi->gridsize = gridsize; - + if (mode == PBVH_ITER_ALL) vi->totvert = totvert; else diff --git a/source/blender/blenkernel/intern/pointcache.c b/source/blender/blenkernel/intern/pointcache.c index af13909bf89..3e8e6a69dd8 100644 --- a/source/blender/blenkernel/intern/pointcache.c +++ b/source/blender/blenkernel/intern/pointcache.c @@ -125,7 +125,7 @@ /* could be made into a pointcache option */ #define DURIAN_POINTCACHE_LIB_OK 1 -static int ptcache_data_size[] = { +static int ptcache_data_size[] = { sizeof(unsigned int), // BPHYS_DATA_INDEX 3 * sizeof(float), // BPHYS_DATA_LOCATION 3 * sizeof(float), // BPHYS_DATA_VELOCITY @@ -155,7 +155,7 @@ static int ptcache_basic_header_read(PTCacheFile *pf) /* Custom functions should read these basic elements too! */ if (!error && !fread(&pf->totpoint, sizeof(unsigned int), 1, pf->fp)) error = 1; - + if (!error && !fread(&pf->data_types, sizeof(unsigned int), 1, pf->fp)) error = 1; @@ -166,7 +166,7 @@ static int ptcache_basic_header_write(PTCacheFile *pf) /* Custom functions should write these basic elements too! */ if (!fwrite(&pf->totpoint, sizeof(unsigned int), 1, pf->fp)) return 0; - + if (!fwrite(&pf->data_types, sizeof(unsigned int), 1, pf->fp)) return 0; @@ -244,7 +244,7 @@ void BKE_ptcache_make_particle_key(ParticleKey *key, int index, void **data, flo { PTCACHE_DATA_TO(data, BPHYS_DATA_LOCATION, index, key->co); PTCACHE_DATA_TO(data, BPHYS_DATA_VELOCITY, index, key->vel); - + /* no rotation info, so make something nice up */ if (data[BPHYS_DATA_ROTATION]==NULL) { vec_to_quat(key->rot, key->vel, OB_NEGX, OB_POSZ); @@ -320,7 +320,7 @@ static void ptcache_particle_read(int index, void *psys_v, void **data, float cf if (data[BPHYS_DATA_SIZE]) { PTCACHE_DATA_TO(data, BPHYS_DATA_SIZE, 0, &pa->size); } - + if (data[BPHYS_DATA_TIMES]) { float times[3]; PTCACHE_DATA_TO(data, BPHYS_DATA_TIMES, 0, ×); @@ -498,7 +498,7 @@ static void ptcache_cloth_read(int index, void *cloth_v, void **data, float UNUS ClothModifierData *clmd= cloth_v; Cloth *cloth= clmd->clothObject; ClothVertex *vert = cloth->verts + index; - + if (old_data) { memcpy(vert->x, data, 3 * sizeof(float)); memcpy(vert->xconst, data + 3, 3 * sizeof(float)); @@ -564,7 +564,7 @@ static int ptcache_smoke_totpoint(void *smoke_v, int UNUSED(cfra)) { SmokeModifierData *smd= (SmokeModifierData *)smoke_v; SmokeDomainSettings *sds = smd->domain; - + if (sds->fluid) { return sds->base_res[0]*sds->base_res[1]*sds->base_res[2]; } @@ -581,7 +581,7 @@ static void ptcache_smoke_error(void *smoke_v, const char *message) #define SMOKE_CACHE_VERSION "1.04" static int ptcache_smoke_write(PTCacheFile *pf, void *smoke_v) -{ +{ SmokeModifierData *smd= (SmokeModifierData *)smoke_v; SmokeDomainSettings *sds = smd->domain; int ret = 0; @@ -593,7 +593,7 @@ static int ptcache_smoke_write(PTCacheFile *pf, void *smoke_v) ptcache_file_write(pf, &sds->active_fields, 1, sizeof(int)); ptcache_file_write(pf, &sds->res, 3, sizeof(int)); ptcache_file_write(pf, &sds->dx, 1, sizeof(float)); - + if (sds->fluid) { size_t res = sds->res[0]*sds->res[1]*sds->res[2]; float dt, dx, *dens, *react, *fuel, *flame, *heat, *heatold, *vx, *vy, *vz, *r, *g, *b; @@ -640,7 +640,7 @@ static int ptcache_smoke_write(PTCacheFile *pf, void *smoke_v) ptcache_file_write(pf, &sds->active_color, 3, sizeof(float)); MEM_freeN(out); - + ret = 1; } @@ -683,7 +683,7 @@ static int ptcache_smoke_write(PTCacheFile *pf, void *smoke_v) ptcache_file_compressed_write(pf, (unsigned char *)tcv, in_len, out, mode); ptcache_file_compressed_write(pf, (unsigned char *)tcw, in_len, out, mode); MEM_freeN(out); - + ret = 1; } @@ -695,7 +695,7 @@ static int ptcache_smoke_read_old(PTCacheFile *pf, void *smoke_v) { SmokeModifierData *smd= (SmokeModifierData *)smoke_v; SmokeDomainSettings *sds = smd->domain; - + if (sds->fluid) { const size_t res = sds->res[0] * sds->res[1] * sds->res[2]; const unsigned int out_len = (unsigned int)res * sizeof(float); @@ -709,7 +709,7 @@ static int ptcache_smoke_read_old(PTCacheFile *pf, void *smoke_v) sds->active_color[0] = 0.7f; sds->active_color[1] = 0.7f; sds->active_color[2] = 0.7f; - + smoke_export(sds->fluid, &dt, &dx, &dens, NULL, NULL, NULL, &heat, &heatold, &vx, &vy, &vz, NULL, NULL, NULL, &obstacles); ptcache_file_compressed_read(pf, (unsigned char *)sds->shadow, out_len); @@ -762,7 +762,7 @@ static int ptcache_smoke_read_old(PTCacheFile *pf, void *smoke_v) } } - return 1; + return 1; } static int ptcache_smoke_read(PTCacheFile *pf, void *smoke_v) @@ -818,13 +818,13 @@ static int ptcache_smoke_read(PTCacheFile *pf, void *smoke_v) smoke_reallocate_highres_fluid(sds, ch_dx, ch_res, 1); } } - + if (sds->fluid) { size_t res = sds->res[0]*sds->res[1]*sds->res[2]; float dt, dx, *dens, *react, *fuel, *flame, *heat, *heatold, *vx, *vy, *vz, *r, *g, *b; unsigned char *obstacles; unsigned int out_len = (unsigned int)res * sizeof(float); - + smoke_export(sds->fluid, &dt, &dx, &dens, &react, &flame, &fuel, &heat, &heatold, &vx, &vy, &vz, &r, &g, &b, &obstacles); ptcache_file_compressed_read(pf, (unsigned char *)sds->shadow, out_len); @@ -1199,7 +1199,7 @@ static void ptcache_dynamicpaint_error(void *UNUSED(sd), const char *UNUSED(mess #define DPAINT_CACHE_VERSION "1.01" static int ptcache_dynamicpaint_write(PTCacheFile *pf, void *dp_v) -{ +{ DynamicPaintSurface *surface = (DynamicPaintSurface*)dp_v; int cache_compress = 1; @@ -1241,7 +1241,7 @@ static int ptcache_dynamicpaint_read(PTCacheFile *pf, void *dp_v) { DynamicPaintSurface *surface = (DynamicPaintSurface*)dp_v; char version[4]; - + /* version header */ ptcache_file_read(pf, version, 1, sizeof(char) * 4); if (!STREQLEN(version, DPAINT_CACHE_VERSION, 4)) { @@ -1286,13 +1286,13 @@ static int ptcache_rigidbody_write(int index, void *rb_v, void **data, int UNUS { RigidBodyWorld *rbw = rb_v; Object *ob = NULL; - + if (rbw->objects) ob = rbw->objects[index]; - + if (ob && ob->rigidbody_object) { RigidBodyOb *rbo = ob->rigidbody_object; - + if (rbo->type == RBO_TYPE_ACTIVE) { #ifdef WITH_BULLET RB_body_get_position(rbo->physics_object, rbo->pos); @@ -1309,15 +1309,15 @@ static void ptcache_rigidbody_read(int index, void *rb_v, void **data, float UNU { RigidBodyWorld *rbw = rb_v; Object *ob = NULL; - + if (rbw->objects) ob = rbw->objects[index]; - + if (ob && ob->rigidbody_object) { RigidBodyOb *rbo = ob->rigidbody_object; - + if (rbo->type == RBO_TYPE_ACTIVE) { - + if (old_data) { memcpy(rbo->pos, data, 3 * sizeof(float)); memcpy(rbo->orn, data + 3, 4 * sizeof(float)); @@ -1333,23 +1333,23 @@ static void ptcache_rigidbody_interpolate(int index, void *rb_v, void **data, fl { RigidBodyWorld *rbw = rb_v; Object *ob = NULL; - + if (rbw->objects) ob = rbw->objects[index]; - + if (ob && ob->rigidbody_object) { RigidBodyOb *rbo = ob->rigidbody_object; - + if (rbo->type == RBO_TYPE_ACTIVE) { ParticleKey keys[4]; ParticleKey result; float dfra; - + memset(keys, 0, sizeof(keys)); - + copy_v3_v3(keys[1].co, rbo->pos); copy_qt_qt(keys[1].rot, rbo->orn); - + if (old_data) { memcpy(keys[2].co, data, 3 * sizeof(float)); memcpy(keys[2].rot, data + 3, 4 * sizeof(float)); @@ -1357,13 +1357,13 @@ static void ptcache_rigidbody_interpolate(int index, void *rb_v, void **data, fl else { BKE_ptcache_make_particle_key(&keys[2], 0, data, cfra2); } - + dfra = cfra2 - cfra1; - + /* note: keys[0] and keys[3] unused for type < 1 (crappy) */ psys_interpolate_particle(-1, keys, (cfra - cfra1) / dfra, &result, true); interp_qt_qtqt(result.rot, keys[1].rot, keys[2].rot, (cfra - cfra1) / dfra); - + copy_v3_v3(rbo->pos, result.co); copy_qt_qt(rbo->orn, result.rot); } @@ -1372,7 +1372,7 @@ static void ptcache_rigidbody_interpolate(int index, void *rb_v, void **data, fl static int ptcache_rigidbody_totpoint(void *rb_v, int UNUSED(cfra)) { RigidBodyWorld *rbw = rb_v; - + return rbw->numbodies; } @@ -1529,7 +1529,7 @@ void BKE_ptcache_id_from_smoke(PTCacheID *pid, struct Object *ob, struct SmokeMo pid->ob= ob; pid->calldata= smd; - + pid->type= PTCACHE_TYPE_SMOKE_DOMAIN; pid->stack_index= sds->point_cache[0]->index; @@ -1613,9 +1613,9 @@ void BKE_ptcache_id_from_dynamicpaint(PTCacheID *pid, Object *ob, DynamicPaintSu void BKE_ptcache_id_from_rigidbody(PTCacheID *pid, Object *ob, RigidBodyWorld *rbw) { - + memset(pid, 0, sizeof(PTCacheID)); - + pid->ob= ob; pid->calldata= rbw; pid->type= PTCACHE_TYPE_RIGIDBODY; @@ -1624,29 +1624,29 @@ void BKE_ptcache_id_from_rigidbody(PTCacheID *pid, Object *ob, RigidBodyWorld *r pid->ptcaches= &rbw->ptcaches; pid->totpoint= pid->totwrite= ptcache_rigidbody_totpoint; pid->error = ptcache_rigidbody_error; - + pid->write_point = ptcache_rigidbody_write; pid->read_point = ptcache_rigidbody_read; pid->interpolate_point = ptcache_rigidbody_interpolate; - + pid->write_stream = NULL; pid->read_stream = NULL; pid->write_openvdb_stream = NULL; pid->read_openvdb_stream = NULL; - + pid->write_extra_data = NULL; pid->read_extra_data = NULL; pid->interpolate_extra_data = NULL; - + pid->write_header = ptcache_basic_header_write; pid->read_header = ptcache_basic_header_read; - + pid->data_types= (1<<BPHYS_DATA_LOCATION) | (1<<BPHYS_DATA_ROTATION); pid->info_types= 0; - + pid->stack_index = pid->cache->index; - + pid->default_step = 1; pid->max_step = 1; pid->file_type = PTCACHE_FILE_PTCACHE; @@ -1688,7 +1688,7 @@ void BKE_ptcache_ids_from_object(ListBase *lb, Object *ob, Scene *scene, int dup for (psys=ob->particlesystem.first; psys; psys=psys->next) { if (psys->part==NULL) continue; - + /* check to make sure point cache is actually used by the particles */ if (ELEM(psys->part->phystype, PART_PHYS_NO, PART_PHYS_KEYED)) continue; @@ -1696,7 +1696,7 @@ void BKE_ptcache_ids_from_object(ListBase *lb, Object *ob, Scene *scene, int dup /* hair needs to be included in id-list for cache edit mode to work */ /* if (psys->part->type == PART_HAIR && (psys->flag & PSYS_HAIR_DYNAMICS)==0) */ /* continue; */ - + if (psys->part->type == PART_FLUID) continue; @@ -1732,7 +1732,7 @@ void BKE_ptcache_ids_from_object(ListBase *lb, Object *ob, Scene *scene, int dup } } } - + if (scene && ob->rigidbody_object && scene->rigidbody_world) { pid = MEM_callocN(sizeof(PTCacheID), "PTCacheID"); BKE_ptcache_id_from_rigidbody(pid, ob, scene->rigidbody_world); @@ -1743,16 +1743,15 @@ void BKE_ptcache_ids_from_object(ListBase *lb, Object *ob, Scene *scene, int dup * for baking with linking dupligroups. Once we have better overrides * this can be revisited so users select the local objects directly. */ if (scene && (duplis-- > 0) && (ob->dup_group)) { - Collection *collection = ob->dup_group; - Base *base = BKE_collection_object_cache_get(collection).first; - - for (; base; base = base->next) { - if (base->object != ob) { + FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(ob->dup_group, object) + { + if (object != ob) { ListBase lb_dupli_pid; - BKE_ptcache_ids_from_object(&lb_dupli_pid, base->object, scene, duplis); + BKE_ptcache_ids_from_object(&lb_dupli_pid, object, scene, duplis); BLI_movelisttolist(lb, &lb_dupli_pid); } } + FOREACH_COLLECTION_OBJECT_RECURSIVE_END; } } @@ -1819,20 +1818,20 @@ static int ptcache_path(PTCacheID *pid, char *filename) BLI_split_file_part(blendfilename, file, sizeof(file)); i = strlen(file); - + /* remove .blend */ if (i > 6) file[i-6] = '\0'; - + BLI_snprintf(filename, MAX_PTCACHE_PATH, "//"PTCACHE_PATH"%s", file); /* add blend file name to pointcache dir */ BLI_path_abs(filename, blendfilename); return BLI_add_slash(filename); /* new strlen() */ } - + /* use the temp path. this is weak but better then not using point cache at all */ /* temporary directory is assumed to exist and ALWAYS has a trailing slash */ BLI_snprintf(filename, MAX_PTCACHE_PATH, "%s"PTCACHE_PATH, BKE_tempdir_session()); - + return BLI_add_slash(filename); /* new strlen() */ } @@ -1843,9 +1842,9 @@ static int ptcache_filename(PTCacheID *pid, char *filename, int cfra, short do_p char *newname; filename[0] = '\0'; newname = filename; - + if (!G.relbase_valid && (pid->cache->flag & PTCACHE_EXTERNAL)==0) return 0; /* save blend file before using disk pointcache */ - + /* start with temp dir */ if (do_path) { len = ptcache_path(pid, filename); @@ -1861,8 +1860,8 @@ static int ptcache_filename(PTCacheID *pid, char *filename, int cfra, short do_p } } else { - int temp = (int)strlen(pid->cache->name); - strcpy(newname, pid->cache->name); + int temp = (int)strlen(pid->cache->name); + strcpy(newname, pid->cache->name); newname+=temp; len += temp; } @@ -1884,7 +1883,7 @@ static int ptcache_filename(PTCacheID *pid, char *filename, int cfra, short do_p } len += 16; } - + return len; /* make sure the above string is always 16 chars */ } @@ -1901,7 +1900,7 @@ static PTCacheFile *ptcache_file_open(PTCacheID *pid, int mode, int cfra) return NULL; #endif if (!G.relbase_valid && (pid->cache->flag & PTCACHE_EXTERNAL)==0) return NULL; /* save blend file before using disk pointcache */ - + ptcache_filename(pid, filename, cfra, 1, 1); if (mode==PTCACHE_FILE_READ) { @@ -1995,7 +1994,7 @@ static int ptcache_file_compressed_write(PTCacheFile *pf, unsigned char *in, uns out_len= LZO_OUT_LEN(in_len); if (mode == 1) { LZO_HEAP_ALLOC(wrkmem, LZO1X_MEM_COMPRESS); - + r = lzo1x_1_compress(in, (lzo_uint)in_len, out, (lzo_uint *)&out_len, wrkmem); if (!(r == LZO_E_OK) || (out_len >= in_len)) compressed = 0; @@ -2005,7 +2004,7 @@ static int ptcache_file_compressed_write(PTCacheFile *pf, unsigned char *in, uns #endif #ifdef WITH_LZMA if (mode == 2) { - + r = LzmaCompress(out, &out_len, in, in_len, //assume sizeof(char)==1.... props, &sizeOfIt, 5, 1 << 24, 3, 0, 2, 32, 2); @@ -2015,7 +2014,7 @@ static int ptcache_file_compressed_write(PTCacheFile *pf, unsigned char *in, uns compressed = 2; } #endif - + ptcache_file_write(pf, &compressed, 1, sizeof(unsigned char)); if (compressed) { unsigned int size = out_len; @@ -2051,18 +2050,18 @@ static int ptcache_file_data_read(PTCacheFile *pf) if ((pf->data_types & (1<<i)) && !ptcache_file_read(pf, pf->cur[i], 1, ptcache_data_size[i])) return 0; } - + return 1; } static int ptcache_file_data_write(PTCacheFile *pf) -{ +{ int i; for (i=0; i<BPHYS_TOT_DATA; i++) { if ((pf->data_types & (1<<i)) && !ptcache_file_write(pf, pf->cur[i], 1, ptcache_data_size[i])) return 0; } - + return 1; } static int ptcache_file_header_begin_read(PTCacheFile *pf) @@ -2070,12 +2069,12 @@ static int ptcache_file_header_begin_read(PTCacheFile *pf) unsigned int typeflag=0; int error=0; char bphysics[8]; - + pf->data_types = 0; - + if (fread(bphysics, sizeof(char), 8, pf->fp) != 8) error = 1; - + if (!error && !STREQLEN(bphysics, "BPHYSICS", 8)) error = 1; @@ -2084,7 +2083,7 @@ static int ptcache_file_header_begin_read(PTCacheFile *pf) pf->type = (typeflag & PTCACHE_TYPEFLAG_TYPEMASK); pf->flag = (typeflag & PTCACHE_TYPEFLAG_FLAGMASK); - + /* if there was an error set file as it was */ if (error) fseek(pf->fp, 0, SEEK_SET); @@ -2095,13 +2094,13 @@ static int ptcache_file_header_begin_write(PTCacheFile *pf) { const char *bphysics = "BPHYSICS"; unsigned int typeflag = pf->type + pf->flag; - + if (fwrite(bphysics, sizeof(char), 8, pf->fp) != 8) return 0; if (!fwrite(&typeflag, sizeof(unsigned int), 1, pf->fp)) return 0; - + return 1; } @@ -2382,14 +2381,14 @@ static PTCacheMem *ptcache_disk_frame_to_mem(PTCacheID *pid, int cfra) if (error && G.debug & G_DEBUG) printf("Error reading from disk cache\n"); - + return pm; } static int ptcache_mem_frame_to_disk(PTCacheID *pid, PTCacheMem *pm) { PTCacheFile *pf = NULL; unsigned int i, error = 0; - + BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_FRAME, pm->frame); pf = ptcache_file_open(pid, PTCACHE_FILE_WRITE, pm->frame); @@ -2404,10 +2403,10 @@ static int ptcache_mem_frame_to_disk(PTCacheID *pid, PTCacheMem *pm) pf->totpoint = pm->totpoint; pf->type = pid->type; pf->flag = 0; - + if (pm->extradata.first) pf->flag |= PTCACHE_TYPEFLAG_EXTRADATA; - + if (pid->cache->compression) pf->flag |= PTCACHE_TYPEFLAG_COMPRESS; @@ -2463,7 +2462,7 @@ static int ptcache_mem_frame_to_disk(PTCacheID *pid, PTCacheMem *pm) } ptcache_file_close(pf); - + if (error && G.debug & G_DEBUG) printf("Error writing to disk cache\n"); @@ -2512,7 +2511,7 @@ static int ptcache_read_stream(PTCacheID *pid, int cfra) } ptcache_file_close(pf); - + return error == 0; } @@ -2557,7 +2556,7 @@ static int ptcache_read(PTCacheID *pid, int cfra) } else { pm = pid->cache->mem_cache.first; - + while (pm && pm->frame != cfra) pm = pm->next; } @@ -2582,7 +2581,7 @@ static int ptcache_read(PTCacheID *pid, int cfra) index = pm->cur[BPHYS_DATA_INDEX]; pid->read_point(*index, pid->calldata, pm->cur, (float)pm->frame, NULL); - + BKE_ptcache_mem_pointers_incr(pm); } @@ -2611,7 +2610,7 @@ static int ptcache_interpolate(PTCacheID *pid, float cfra, int cfra1, int cfra2) } else { pm = pid->cache->mem_cache.first; - + while (pm && pm->frame != cfra2) pm = pm->next; } @@ -2749,7 +2748,7 @@ static int ptcache_write_stream(PTCacheID *pid, int cfra, int totpoint) { PTCacheFile *pf = NULL; int error = 0; - + BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_FRAME, cfra); pf = ptcache_file_open(pid, PTCACHE_FILE_WRITE, cfra); @@ -2821,7 +2820,7 @@ static int ptcache_write(PTCacheID *pid, int cfra, int overwrite) while (fra >= cache->startframe && !BKE_ptcache_id_exist(pid, fra)) fra--; - + pm2 = ptcache_disk_frame_to_mem(pid, fra); } else @@ -2969,7 +2968,7 @@ void BKE_ptcache_id_clear(PTCacheID *pid, int mode, unsigned int cfra) unsigned int sta, end; /* mode is same as fopen's modes */ - DIR *dir; + DIR *dir; struct dirent *de; char path[MAX_PTCACHE_PATH]; char filename[MAX_PTCACHE_FILE]; @@ -3002,11 +3001,11 @@ void BKE_ptcache_id_clear(PTCacheID *pid, int mode, unsigned int cfra) case PTCACHE_CLEAR_AFTER: if (pid->cache->flag & PTCACHE_DISK_CACHE) { ptcache_path(pid, path); - + dir = opendir(path); if (dir==NULL) return; - + len = ptcache_filename(pid, filename, cfra, 0, 0); /* no path */ /* append underscore terminator to ensure we don't match similar names * from objects whose names start with the same prefix @@ -3015,9 +3014,9 @@ void BKE_ptcache_id_clear(PTCacheID *pid, int mode, unsigned int cfra) BLI_strncpy(filename + len, "_", sizeof(filename) - 2 - len); len += 1; } - + BLI_snprintf(ext, sizeof(ext), "_%02u%s", pid->stack_index, fext); - + while ((de = readdir(dir)) != NULL) { if (strstr(de->d_name, ext)) { /* do we have the right extension?*/ if (STREQLEN(filename, de->d_name, len)) { /* do we have the right prefix */ @@ -3034,7 +3033,7 @@ void BKE_ptcache_id_clear(PTCacheID *pid, int mode, unsigned int cfra) if ((mode == PTCACHE_CLEAR_BEFORE && frame < cfra) || (mode == PTCACHE_CLEAR_AFTER && frame > cfra)) { - + BLI_join_dirfile(path_full, sizeof(path_full), path, de->d_name); BLI_delete(path_full, false, false); if (pid->cache->cached_frames && frame >=sta && frame <= end) @@ -3063,7 +3062,7 @@ void BKE_ptcache_id_clear(PTCacheID *pid, int mode, unsigned int cfra) } BLI_freelistN(&pid->cache->mem_cache); - if (pid->cache->cached_frames) + if (pid->cache->cached_frames) memset(pid->cache->cached_frames, 0, MEM_allocN_len(pid->cache->cached_frames)); } else { @@ -3085,7 +3084,7 @@ void BKE_ptcache_id_clear(PTCacheID *pid, int mode, unsigned int cfra) } } break; - + case PTCACHE_CLEAR_FRAME: if (pid->cache->flag & PTCACHE_DISK_CACHE) { if (BKE_ptcache_id_exist(pid, cfra)) { @@ -3122,10 +3121,10 @@ int BKE_ptcache_id_exist(PTCacheID *pid, int cfra) if (pid->cache->cached_frames && pid->cache->cached_frames[cfra-pid->cache->startframe]==0) return 0; - + if (pid->cache->flag & PTCACHE_DISK_CACHE) { char filename[MAX_PTCACHE_FILE]; - + ptcache_filename(pid, filename, cfra, 1, 1); return BLI_exists(filename); @@ -3165,7 +3164,7 @@ void BKE_ptcache_id_time(PTCacheID *pid, Scene *scene, float cfra, int *startfra if (timescale) { time= BKE_scene_frame_get(scene); nexttime = BKE_scene_frame_get_from_ctime(scene, CFRA + 1.0f); - + *timescale= MAX2(nexttime - time, 0.0f); } @@ -3203,7 +3202,7 @@ void BKE_ptcache_id_time(PTCacheID *pid, Scene *scene, float cfra, int *startfra if (pid->cache->flag & PTCACHE_DISK_CACHE) { /* mode is same as fopen's modes */ - DIR *dir; + DIR *dir; struct dirent *de; char path[MAX_PTCACHE_PATH]; char filename[MAX_PTCACHE_FILE]; @@ -3211,9 +3210,9 @@ void BKE_ptcache_id_time(PTCacheID *pid, Scene *scene, float cfra, int *startfra unsigned int len; /* store the length of the string */ ptcache_path(pid, path); - + len = ptcache_filename(pid, filename, (int)cfra, 0, 0); /* no path */ - + dir = opendir(path); if (dir==NULL) return; @@ -3221,7 +3220,7 @@ void BKE_ptcache_id_time(PTCacheID *pid, Scene *scene, float cfra, int *startfra const char *fext = ptcache_file_extension(pid); BLI_snprintf(ext, sizeof(ext), "_%02u%s", pid->stack_index, fext); - + while ((de = readdir(dir)) != NULL) { if (strstr(de->d_name, ext)) { /* do we have the right extension?*/ if (STREQLEN(filename, de->d_name, len)) { /* do we have the right prefix */ @@ -3329,7 +3328,7 @@ int BKE_ptcache_object_reset(Scene *scene, Object *ob, int mode) /* particles or cloth in that case -jahka */ else if (psys->clmd) { BKE_ptcache_id_from_cloth(&pid, ob, psys->clmd); - if (mode == PSYS_RESET_ALL || !(psys->part->type == PART_HAIR && (pid.cache->flag & PTCACHE_BAKED))) + if (mode == PSYS_RESET_ALL || !(psys->part->type == PART_HAIR && (pid.cache->flag & PTCACHE_BAKED))) reset |= BKE_ptcache_id_reset(scene, &pid, mode); else skip = 1; @@ -3387,19 +3386,19 @@ void BKE_ptcache_remove(void) char path[MAX_PTCACHE_PATH]; char path_full[MAX_PTCACHE_PATH]; int rmdir = 1; - + ptcache_path(NULL, path); if (BLI_exists(path)) { /* The pointcache dir exists? - remove all pointcache */ - DIR *dir; + DIR *dir; struct dirent *de; dir = opendir(path); if (dir==NULL) return; - + while ((de = readdir(dir)) != NULL) { if (FILENAME_IS_CURRPAR(de->d_name)) { /* do nothing */ @@ -3418,7 +3417,7 @@ void BKE_ptcache_remove(void) else { rmdir = 0; /* path dosnt exist */ } - + if (rmdir) { BLI_delete(path, true, false); } @@ -3528,7 +3527,7 @@ PointCache *BKE_ptcache_copy_list(ListBase *ptcaches_new, const ListBase *ptcach return ptcaches_new->first; } -/* Disabled this code; this is being called on scene_update_tagged, and that in turn gets called on +/* Disabled this code; this is being called on scene_update_tagged, and that in turn gets called on * every user action changing stuff, and then it runs a complete bake??? (ton) */ /* Baking */ @@ -3537,7 +3536,7 @@ void BKE_ptcache_quick_cache_all(Main *bmain, Scene *scene, ViewLayer *view_laye PTCacheBaker baker; memset(&baker, 0, sizeof(baker)); - baker.main = bmain; + baker.bmain = bmain; baker.scene = scene; baker.view_layer = view_layer; baker.bake = 0; @@ -3563,7 +3562,7 @@ static void ptcache_dt_to_str(char *str, double dtime) /* if bake is not given run simulations to current frame */ void BKE_ptcache_bake(PTCacheBaker *baker) { - Main *bmain = baker->main; + Main *bmain = baker->bmain; Scene *scene = baker->scene; ViewLayer *view_layer = baker->view_layer; struct Depsgraph *depsgraph = baker->depsgraph; @@ -3577,7 +3576,7 @@ void BKE_ptcache_bake(PTCacheBaker *baker) int startframe = MAXFRAME, endframe = baker->anim_init ? scene->r.sfra : CFRA; int bake = baker->bake; int render = baker->render; - + G.is_break = false; /* set caches to baking mode and figure out start frame */ @@ -3769,7 +3768,7 @@ void BKE_ptcache_bake(PTCacheBaker *baker) scene->r.framelen = frameleno; CFRA = cfrao; - + if (bake) { /* already on cfra unless baking */ BKE_scene_graph_update_for_newframe(depsgraph, bmain); } @@ -3851,7 +3850,7 @@ void BKE_ptcache_toggle_disk_cache(PTCacheID *pid) cache->flag ^= PTCACHE_DISK_CACHE; BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_ALL, 0); cache->flag ^= PTCACHE_DISK_CACHE; - + cache->last_exact = last_exact; BKE_ptcache_id_time(pid, NULL, 0.0f, NULL, NULL, NULL); @@ -3871,7 +3870,7 @@ void BKE_ptcache_disk_cache_rename(PTCacheID *pid, const char *name_src, const c char old_name[80]; int len; /* store the length of the string */ /* mode is same as fopen's modes */ - DIR *dir; + DIR *dir; struct dirent *de; char path[MAX_PTCACHE_PATH]; char old_filename[MAX_PTCACHE_FILE]; @@ -3930,7 +3929,7 @@ void BKE_ptcache_load_external(PTCacheID *pid) int end = -1; /* mode is same as fopen's modes */ - DIR *dir; + DIR *dir; struct dirent *de; char path[MAX_PTCACHE_PATH]; char filename[MAX_PTCACHE_FILE]; @@ -3940,9 +3939,9 @@ void BKE_ptcache_load_external(PTCacheID *pid) return; ptcache_path(pid, path); - + len = ptcache_filename(pid, filename, 1, 0, 0); /* no path */ - + dir = opendir(path); if (dir==NULL) return; @@ -3953,7 +3952,7 @@ void BKE_ptcache_load_external(PTCacheID *pid) BLI_snprintf(ext, sizeof(ext), "_%02d%s", cache->index, fext); else BLI_strncpy(ext, fext, sizeof(ext)); - + while ((de = readdir(dir)) != NULL) { if (strstr(de->d_name, ext)) { /* do we have the right extension?*/ if (STREQLEN(filename, de->d_name, len)) { /* do we have the right prefix */ @@ -4009,7 +4008,7 @@ void BKE_ptcache_load_external(PTCacheID *pid) if (pf) { while (ptcache_file_read(pf, old_data, 1, elemsize)) cache->totpoint++; - + ptcache_file_close(pf); } } @@ -4087,7 +4086,7 @@ void BKE_ptcache_update_info(PTCacheID *pid) } bytes += sizeof(PTCacheMem); - + totframes++; } diff --git a/source/blender/blenkernel/intern/report.c b/source/blender/blenkernel/intern/report.c index 67b076c0153..a9b36a85602 100644 --- a/source/blender/blenkernel/intern/report.c +++ b/source/blender/blenkernel/intern/report.c @@ -270,10 +270,10 @@ char *BKE_reports_string(ReportList *reports, ReportType level) void BKE_reports_print(ReportList *reports, ReportType level) { char *cstring = BKE_reports_string(reports, level); - + if (cstring == NULL) return; - + puts(cstring); fflush(stdout); MEM_freeN(cstring); @@ -282,12 +282,12 @@ void BKE_reports_print(ReportList *reports, ReportType level) Report *BKE_reports_last_displayable(ReportList *reports) { Report *report; - + for (report = reports->list.last; report; report = report->prev) { if (ELEM(report->type, RPT_ERROR, RPT_WARNING, RPT_INFO)) return report; } - + return NULL; } diff --git a/source/blender/blenkernel/intern/rigidbody.c b/source/blender/blenkernel/intern/rigidbody.c index f7628d081a6..2374670b212 100644 --- a/source/blender/blenkernel/intern/rigidbody.c +++ b/source/blender/blenkernel/intern/rigidbody.c @@ -48,13 +48,13 @@ #include "DNA_ID.h" #include "DNA_group_types.h" +#include "DNA_mesh_types.h" #include "DNA_meshdata_types.h" #include "DNA_object_types.h" #include "DNA_object_force_types.h" #include "DNA_rigidbody_types.h" #include "DNA_scene_types.h" -#include "BKE_cdderivedmesh.h" #include "BKE_collection.h" #include "BKE_effect.h" #include "BKE_global.h" @@ -62,6 +62,7 @@ #include "BKE_library.h" #include "BKE_library_query.h" #include "BKE_mesh.h" +#include "BKE_mesh_runtime.h" #include "BKE_object.h" #include "BKE_pointcache.h" #include "BKE_rigidbody.h" @@ -235,16 +236,18 @@ RigidBodyCon *BKE_rigidbody_copy_constraint(const Object *ob, const int UNUSED(f /* Setup Utilities - Validate Sim Instances */ /* get the appropriate DerivedMesh based on rigid body mesh source */ -static DerivedMesh *rigidbody_get_mesh(Object *ob) +static Mesh *rigidbody_get_mesh(Object *ob) { + /* TODO(Sybren): turn this into a switch statement */ if (ob->rigidbody_object->mesh_source == RBO_MESH_DEFORM) { - return ob->derivedDeform; + return ob->runtime.mesh_deform_eval; } else if (ob->rigidbody_object->mesh_source == RBO_MESH_FINAL) { - return ob->derivedFinal; + return ob->runtime.mesh_eval; } else { - return CDDM_from_mesh(ob->data); + BLI_assert(ob->rigidbody_object->mesh_source == RBO_MESH_BASE); + return ob->data; } } @@ -252,14 +255,14 @@ static DerivedMesh *rigidbody_get_mesh(Object *ob) static rbCollisionShape *rigidbody_get_shape_convexhull_from_mesh(Object *ob, float margin, bool *can_embed) { rbCollisionShape *shape = NULL; - DerivedMesh *dm = NULL; + Mesh *mesh = NULL; MVert *mvert = NULL; int totvert = 0; if (ob->type == OB_MESH && ob->data) { - dm = rigidbody_get_mesh(ob); - mvert = (dm) ? dm->getVertArray(dm) : NULL; - totvert = (dm) ? dm->getNumVerts(dm) : 0; + mesh = rigidbody_get_mesh(ob); + mvert = (mesh) ? mesh->mvert : NULL; + totvert = (mesh) ? mesh->totvert : 0; } else { printf("ERROR: cannot make Convex Hull collision shape for non-Mesh object\n"); @@ -272,9 +275,6 @@ static rbCollisionShape *rigidbody_get_shape_convexhull_from_mesh(Object *ob, fl printf("ERROR: no vertices to define Convex Hull collision shape with\n"); } - if (dm && ob->rigidbody_object->mesh_source == RBO_MESH_BASE) - dm->release(dm); - return shape; } @@ -286,24 +286,24 @@ static rbCollisionShape *rigidbody_get_shape_trimesh_from_mesh(Object *ob) rbCollisionShape *shape = NULL; if (ob->type == OB_MESH) { - DerivedMesh *dm = NULL; + Mesh *mesh = NULL; MVert *mvert; const MLoopTri *looptri; int totvert; int tottri; const MLoop *mloop; - - dm = rigidbody_get_mesh(ob); + + mesh = rigidbody_get_mesh(ob); /* ensure mesh validity, then grab data */ - if (dm == NULL) + if (mesh == NULL) return NULL; - mvert = dm->getVertArray(dm); - totvert = dm->getNumVerts(dm); - looptri = dm->getLoopTriArray(dm); - tottri = dm->getNumLoopTri(dm); - mloop = dm->getLoopArray(dm); + mvert = mesh->mvert; + totvert = mesh->totvert; + looptri = BKE_mesh_runtime_looptri_ensure(mesh); + tottri = mesh->runtime.looptris.len; + mloop = mesh->mloop; /* sanity checking - potential case when no data will be present */ if ((totvert == 0) || (tottri == 0)) { @@ -315,7 +315,7 @@ static rbCollisionShape *rigidbody_get_shape_trimesh_from_mesh(Object *ob) /* init mesh data for collision shape */ mdata = RB_trimesh_data_new(tottri, totvert); - + RB_trimesh_add_vertices(mdata, (float *)mvert, totvert, sizeof(MVert)); /* loop over all faces, adding them as triangles to the collision shape @@ -334,7 +334,7 @@ static rbCollisionShape *rigidbody_get_shape_trimesh_from_mesh(Object *ob) RB_trimesh_add_triangle_indices(mdata, i, UNPACK3(vtri)); } } - + RB_trimesh_finish(mdata); /* construct collision shape @@ -353,11 +353,6 @@ static rbCollisionShape *rigidbody_get_shape_trimesh_from_mesh(Object *ob) shape = RB_shape_new_gimpact_mesh(mdata); } } - - /* cleanup temp data */ - if (ob->rigidbody_object->mesh_source == RBO_MESH_BASE) { - dm->release(dm); - } } else { printf("ERROR: cannot make Triangular Mesh collision shape for non-Mesh object\n"); @@ -520,30 +515,25 @@ void BKE_rigidbody_calc_volume(Object *ob, float *r_vol) case RB_SHAPE_TRIMESH: { if (ob->type == OB_MESH) { - DerivedMesh *dm = rigidbody_get_mesh(ob); + Mesh *mesh = rigidbody_get_mesh(ob); MVert *mvert; const MLoopTri *lt = NULL; int totvert, tottri = 0; const MLoop *mloop = NULL; - + /* ensure mesh validity, then grab data */ - if (dm == NULL) + if (mesh == NULL) return; - - mvert = dm->getVertArray(dm); - totvert = dm->getNumVerts(dm); - lt = dm->getLoopTriArray(dm); - tottri = dm->getNumLoopTri(dm); - mloop = dm->getLoopArray(dm); - + + mvert = mesh->mvert; + totvert = mesh->totvert; + lt = BKE_mesh_runtime_looptri_ensure(mesh); + tottri = mesh->runtime.looptris.len; + mloop = mesh->mloop; + if (totvert > 0 && tottri > 0) { BKE_mesh_calc_volume(mvert, totvert, lt, tottri, mloop, &volume, NULL); } - - /* cleanup temp data */ - if (ob->rigidbody_object->mesh_source == RBO_MESH_BASE) { - dm->release(dm); - } } else { /* rough estimate from boundbox as fallback */ @@ -603,30 +593,25 @@ void BKE_rigidbody_calc_center_of_mass(Object *ob, float r_center[3]) case RB_SHAPE_TRIMESH: { if (ob->type == OB_MESH) { - DerivedMesh *dm = rigidbody_get_mesh(ob); + Mesh *mesh = rigidbody_get_mesh(ob); MVert *mvert; const MLoopTri *looptri; int totvert, tottri; const MLoop *mloop; - + /* ensure mesh validity, then grab data */ - if (dm == NULL) + if (mesh == NULL) return; - - mvert = dm->getVertArray(dm); - totvert = dm->getNumVerts(dm); - looptri = dm->getLoopTriArray(dm); - tottri = dm->getNumLoopTri(dm); - mloop = dm->getLoopArray(dm); - + + mvert = mesh->mvert; + totvert = mesh->totvert; + looptri = BKE_mesh_runtime_looptri_ensure(mesh); + tottri = mesh->runtime.looptris.len; + mloop = mesh->mloop; + if (totvert > 0 && tottri > 0) { BKE_mesh_calc_volume(mvert, totvert, looptri, tottri, mloop, NULL, r_center); } - - /* cleanup temp data */ - if (ob->rigidbody_object->mesh_source == RBO_MESH_BASE) { - dm->release(dm); - } } break; } @@ -1135,7 +1120,7 @@ RigidBodyWorld *BKE_rigidbody_get_world(Scene *scene) return scene->rigidbody_world; } -void BKE_rigidbody_remove_object(Scene *scene, Object *ob) +void BKE_rigidbody_remove_object(struct Main *bmain, Scene *scene, Object *ob) { RigidBodyWorld *rbw = scene->rigidbody_world; RigidBodyOb *rbo = ob->rigidbody_object; @@ -1170,6 +1155,7 @@ void BKE_rigidbody_remove_object(Scene *scene, Object *ob) } FOREACH_COLLECTION_OBJECT_RECURSIVE_END; } + BKE_collection_object_remove(bmain, rbw->group, ob, false); } /* remove object's settings */ @@ -1202,17 +1188,20 @@ void BKE_rigidbody_remove_constraint(Scene *scene, Object *ob) /* Update object array and rigid body count so they're in sync with the rigid body group */ static void rigidbody_update_ob_array(RigidBodyWorld *rbw) { - const ListBase objects = BKE_collection_object_cache_get(rbw->group); - int i, n; - - n = BLI_listbase_count(&objects); + int n = 0; + FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(rbw->group, object) + { + (void)object; + n++; + } + FOREACH_COLLECTION_OBJECT_RECURSIVE_END; if (rbw->numbodies != n) { rbw->numbodies = n; rbw->objects = realloc(rbw->objects, sizeof(Object *) * rbw->numbodies); } - i = 0; + int i = 0; FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(rbw->group, object) { rbw->objects[i] = object; @@ -1241,7 +1230,7 @@ static void rigidbody_update_sim_world(Scene *scene, RigidBodyWorld *rbw) rigidbody_update_ob_array(rbw); } -static void rigidbody_update_sim_ob(struct Depsgraph *depsgraph, Scene *scene, RigidBodyWorld *rbw, Object *ob, RigidBodyOb *rbo) +static void rigidbody_update_sim_ob(Depsgraph *depsgraph, Scene *scene, RigidBodyWorld *rbw, Object *ob, RigidBodyOb *rbo) { float loc[3]; float rot[4]; @@ -1252,10 +1241,10 @@ static void rigidbody_update_sim_ob(struct Depsgraph *depsgraph, Scene *scene, R return; if (rbo->shape == RB_SHAPE_TRIMESH && rbo->flag & RBO_FLAG_USE_DEFORM) { - DerivedMesh *dm = ob->derivedDeform; - if (dm) { - MVert *mvert = dm->getVertArray(dm); - int totvert = dm->getNumVerts(dm); + Mesh *mesh = ob->runtime.mesh_deform_eval; + if (mesh) { + MVert *mvert = mesh->mvert; + int totvert = mesh->totvert; BoundBox *bb = BKE_object_boundbox_get(ob); RB_shape_trimesh_update(rbo->physics_shape, (float *)mvert, totvert, sizeof(MVert), bb->vec[0], bb->vec[6]); @@ -1330,7 +1319,7 @@ static void rigidbody_update_sim_ob(struct Depsgraph *depsgraph, Scene *scene, R * * \param rebuild Rebuild entire simulation */ -static void rigidbody_update_simulation(struct Depsgraph *depsgraph, Scene *scene, RigidBodyWorld *rbw, bool rebuild) +static void rigidbody_update_simulation(Depsgraph *depsgraph, Scene *scene, RigidBodyWorld *rbw, bool rebuild) { /* update world */ if (rebuild) @@ -1340,7 +1329,7 @@ static void rigidbody_update_simulation(struct Depsgraph *depsgraph, Scene *scen /* XXX TODO For rebuild: remove all constraints first. * Otherwise we can end up deleting objects that are still * referenced by constraints, corrupting bullet's internal list. - * + * * Memory management needs redesign here, this is just a dirty workaround. */ if (rebuild && rbw->constraints) { @@ -1401,7 +1390,7 @@ static void rigidbody_update_simulation(struct Depsgraph *depsgraph, Scene *scen } } FOREACH_COLLECTION_OBJECT_RECURSIVE_END; - + /* update constraints */ if (rbw->constraints == NULL) /* no constraints, move on */ return; @@ -1437,8 +1426,10 @@ static void rigidbody_update_simulation(struct Depsgraph *depsgraph, Scene *scen FOREACH_COLLECTION_OBJECT_RECURSIVE_END; } -static void rigidbody_update_simulation_post_step(ViewLayer *view_layer, RigidBodyWorld *rbw) +static void rigidbody_update_simulation_post_step(Depsgraph *depsgraph, RigidBodyWorld *rbw) { + ViewLayer *view_layer = DEG_get_input_view_layer(depsgraph); + FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(rbw->group, ob) { Base *base = BKE_view_layer_base_find(view_layer, ob); @@ -1567,7 +1558,7 @@ void BKE_rigidbody_cache_reset(RigidBodyWorld *rbw) /* Rebuild rigid body world */ /* NOTE: this needs to be called before frame update to work correctly */ -void BKE_rigidbody_rebuild_world(struct Depsgraph *depsgraph, Scene *scene, float ctime) +void BKE_rigidbody_rebuild_world(Depsgraph *depsgraph, Scene *scene, float ctime) { RigidBodyWorld *rbw = scene->rigidbody_world; PointCache *cache; @@ -1579,8 +1570,15 @@ void BKE_rigidbody_rebuild_world(struct Depsgraph *depsgraph, Scene *scene, floa cache = rbw->pointcache; /* flag cache as outdated if we don't have a world or number of objects in the simulation has changed */ - const ListBase objects = BKE_collection_object_cache_get(rbw->group); - if (rbw->physics_world == NULL || rbw->numbodies != BLI_listbase_count(&objects)) { + int n = 0; + FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(rbw->group, object) + { + (void)object; + n++; + } + FOREACH_COLLECTION_OBJECT_RECURSIVE_END; + + if (rbw->physics_world == NULL || rbw->numbodies != n) { cache->flag |= PTCACHE_OUTDATED; } @@ -1596,7 +1594,7 @@ void BKE_rigidbody_rebuild_world(struct Depsgraph *depsgraph, Scene *scene, floa } /* Run RigidBody simulation for the specified physics world */ -void BKE_rigidbody_do_simulation(struct Depsgraph *depsgraph, Scene *scene, float ctime) +void BKE_rigidbody_do_simulation(Depsgraph *depsgraph, Scene *scene, float ctime) { float timestep; RigidBodyWorld *rbw = scene->rigidbody_world; @@ -1634,7 +1632,7 @@ void BKE_rigidbody_do_simulation(struct Depsgraph *depsgraph, Scene *scene, floa } /* advance simulation, we can only step one frame forward */ - if (ctime == rbw->ltime + 1) { + if (compare_ff_relative(ctime, rbw->ltime + 1, FLT_EPSILON, 64)) { /* write cache for first frame when on second frame */ if (rbw->ltime == startframe && (cache->flag & PTCACHE_OUTDATED || cache->last_exact == 0)) { BKE_ptcache_write(&pid, startframe); @@ -1648,8 +1646,7 @@ void BKE_rigidbody_do_simulation(struct Depsgraph *depsgraph, Scene *scene, floa /* step simulation by the requested timestep, steps per second are adjusted to take time scale into account */ RB_dworld_step_simulation(rbw->physics_world, timestep, INT_MAX, 1.0f / (float)rbw->steps_per_second * min_ff(rbw->time_scale, 1.0f)); - ViewLayer *view_layer = DEG_get_input_view_layer(depsgraph); - rigidbody_update_simulation_post_step(view_layer, rbw); + rigidbody_update_simulation_post_step(depsgraph, rbw); /* write cache for current frame */ BKE_ptcache_validate(cache, (int)ctime); @@ -1680,14 +1677,14 @@ void BKE_rigidbody_world_id_loop(struct RigidBodyWorld *rbw, RigidbodyWorldIDFun struct RigidBodyOb *BKE_rigidbody_create_object(Scene *scene, Object *ob, short type) { return NULL; } struct RigidBodyCon *BKE_rigidbody_create_constraint(Scene *scene, Object *ob, short type) { return NULL; } struct RigidBodyWorld *BKE_rigidbody_get_world(Scene *scene) { return NULL; } -void BKE_rigidbody_remove_object(Scene *scene, Object *ob) {} +void BKE_rigidbody_remove_object(struct Main *bmain, Scene *scene, Object *ob) {} void BKE_rigidbody_remove_constraint(Scene *scene, Object *ob) {} void BKE_rigidbody_sync_transforms(RigidBodyWorld *rbw, Object *ob, float ctime) {} void BKE_rigidbody_aftertrans_update(Object *ob, float loc[3], float rot[3], float quat[4], float rotAxis[3], float rotAngle) {} bool BKE_rigidbody_check_sim_running(RigidBodyWorld *rbw, float ctime) { return false; } void BKE_rigidbody_cache_reset(RigidBodyWorld *rbw) {} -void BKE_rigidbody_rebuild_world(struct Depsgraph *depsgraph, Scene *scene, float ctime) {} -void BKE_rigidbody_do_simulation(struct Depsgraph *depsgraph, Scene *scene, float ctime) {} +void BKE_rigidbody_rebuild_world(Depsgraph *depsgraph, Scene *scene, float ctime) {} +void BKE_rigidbody_do_simulation(Depsgraph *depsgraph, Scene *scene, float ctime) {} #if defined(__GNUC__) || defined(__clang__) # pragma GCC diagnostic pop @@ -1695,10 +1692,31 @@ void BKE_rigidbody_do_simulation(struct Depsgraph *depsgraph, Scene *scene, floa #endif /* WITH_BULLET */ + +/* Copy the pointcache from the evaluated to the original scene. + * This allows the re-evaluation of the original scene to use the + * physics cache. + */ +static void rigidbody_copy_cache_to_orig(Scene *scene_eval) +{ + if ((scene_eval->id.tag & LIB_TAG_COPIED_ON_WRITE) == 0) { + /* Scene is already an original, this function is a no-op. */ + return; + } + + Scene *scene_orig = (Scene *)DEG_get_original_id(&scene_eval->id); + RigidBodyWorld *rbw_orig = scene_orig->rigidbody_world; + RigidBodyWorld *rbw_eval = scene_eval->rigidbody_world; + + BKE_ptcache_free_list(&rbw_orig->ptcaches); + rbw_orig->pointcache = BKE_ptcache_copy_list(&rbw_orig->ptcaches, &rbw_eval->ptcaches, LIB_ID_COPY_CACHES); +} + + /* -------------------- */ /* Depsgraph evaluation */ -void BKE_rigidbody_rebuild_sim(struct Depsgraph *depsgraph, +void BKE_rigidbody_rebuild_sim(Depsgraph *depsgraph, Scene *scene) { float ctime = DEG_get_ctime(depsgraph); @@ -1709,18 +1727,26 @@ void BKE_rigidbody_rebuild_sim(struct Depsgraph *depsgraph, } } -void BKE_rigidbody_eval_simulation(struct Depsgraph *depsgraph, +void BKE_rigidbody_eval_simulation(Depsgraph *depsgraph, Scene *scene) { float ctime = DEG_get_ctime(depsgraph); DEG_debug_print_eval_time(depsgraph, __func__, scene->id.name, scene, ctime); + /* evaluate rigidbody sim */ - if (BKE_scene_check_rigidbody_active(scene)) { - BKE_rigidbody_do_simulation(depsgraph, scene, ctime); + if (!BKE_scene_check_rigidbody_active(scene)) { + return; + } + BKE_rigidbody_do_simulation(depsgraph, scene, ctime); + + /* Make sure re-evaluation can use the cache from this simulation */ + if (!DEG_is_active(depsgraph)) { + return; } + rigidbody_copy_cache_to_orig(scene); } -void BKE_rigidbody_object_sync_transforms(struct Depsgraph *depsgraph, +void BKE_rigidbody_object_sync_transforms(Depsgraph *depsgraph, Scene *scene, Object *ob) { diff --git a/source/blender/blenkernel/intern/scene.c b/source/blender/blenkernel/intern/scene.c index 63d7942c623..4c81cb057f0 100644 --- a/source/blender/blenkernel/intern/scene.c +++ b/source/blender/blenkernel/intern/scene.c @@ -110,7 +110,6 @@ #include "bmesh.h" -const char *RE_engine_id_BLENDER_CLAY = "BLENDER_CLAY"; const char *RE_engine_id_BLENDER_EEVEE = "BLENDER_EEVEE"; const char *RE_engine_id_BLENDER_WORKBENCH = "BLENDER_WORKBENCH"; const char *RE_engine_id_CYCLES = "CYCLES"; @@ -137,10 +136,10 @@ static void remove_sequencer_fcurves(Scene *sce) if (adt && adt->action) { FCurve *fcu, *nextfcu; - + for (fcu = adt->action->curves.first; fcu; fcu = nextfcu) { nextfcu = fcu->next; - + if ((fcu->rna_path) && strstr(fcu->rna_path, "sequences_all")) { action_groups_remove_channel(adt->action, fcu); free_fcurve(fcu); @@ -450,9 +449,6 @@ void BKE_scene_free_ex(Scene *sce, const bool do_id_user) { BKE_animdata_free((ID *)sce, false); - /* check all sequences */ - BKE_sequencer_clear_scene_in_allseqs(G.main, sce); - BKE_sequencer_editing_free(sce, do_id_user); BKE_keyingsets_free(&sce->keyingsets); @@ -483,10 +479,10 @@ void BKE_scene_free_ex(Scene *sce, const bool do_id_user) BLI_freelistN(&sce->markers); BLI_freelistN(&sce->transform_spaces); BLI_freelistN(&sce->r.views); - + BKE_toolsettings_free(sce->toolsettings); sce->toolsettings = NULL; - + BKE_scene_free_depsgraph_hash(sce); MEM_SAFE_FREE(sce->fps_info); @@ -536,7 +532,7 @@ void BKE_scene_init(Scene *sce) BLI_assert(MEMCMP_STRUCT_OFS_IS_ZERO(sce, id)); sce->lay = sce->layact = 1; - + sce->r.mode = R_OSA; sce->r.cfra = 1; sce->r.sfra = 1; @@ -619,7 +615,7 @@ void BKE_scene_init(Scene *sce) sce->r.border.ymax = 1.0f; sce->r.preview_start_resolution = 64; - + sce->r.line_thickness_mode = R_LINE_THICKNESS_ABSOLUTE; sce->r.unit_line_thickness = 1.0f; @@ -632,6 +628,8 @@ void BKE_scene_init(Scene *sce) CURVEMAP_SLOPE_POS_NEG); sce->toolsettings = MEM_callocN(sizeof(struct ToolSettings), "Tool Settings Struct"); + + sce->toolsettings->object_flag |= SCE_OBJECT_MODE_LOCK; sce->toolsettings->doublimit = 0.001; sce->toolsettings->vgroup_weight = 1.0f; sce->toolsettings->uvcalc_margin = 0.001f; @@ -643,7 +641,7 @@ void BKE_scene_init(Scene *sce) sce->toolsettings->uv_selectmode = UV_SELECT_VERTEX; sce->toolsettings->autokey_mode = U.autokey_mode; - + sce->toolsettings->transform_pivot_point = V3D_AROUND_CENTER_MEAN; sce->toolsettings->snap_mode = SCE_SNAP_MODE_INCREMENT; sce->toolsettings->snap_node_mode = SCE_SNAP_MODE_GRID; @@ -744,22 +742,22 @@ void BKE_scene_init(Scene *sce) copy_v2_fl2(sce->safe_areas.action_center, 15.0f / 100.0f, 5.0f / 100.0f); sce->preview = NULL; - + /* GP Sculpt brushes */ { GP_BrushEdit_Settings *gset = &sce->toolsettings->gp_sculpt; GP_EditBrush_Data *gp_brush; - + gp_brush = &gset->brush[GP_EDITBRUSH_TYPE_SMOOTH]; gp_brush->size = 25; gp_brush->strength = 0.3f; gp_brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF | GP_EDITBRUSH_FLAG_SMOOTH_PRESSURE; - + gp_brush = &gset->brush[GP_EDITBRUSH_TYPE_THICKNESS]; gp_brush->size = 25; gp_brush->strength = 0.5f; gp_brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF; - + gp_brush = &gset->brush[GP_EDITBRUSH_TYPE_STRENGTH]; gp_brush->size = 25; gp_brush->strength = 0.5f; @@ -769,28 +767,28 @@ void BKE_scene_init(Scene *sce) gp_brush->size = 50; gp_brush->strength = 0.3f; gp_brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF; - + gp_brush = &gset->brush[GP_EDITBRUSH_TYPE_PUSH]; gp_brush->size = 25; gp_brush->strength = 0.3f; gp_brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF; - + gp_brush = &gset->brush[GP_EDITBRUSH_TYPE_TWIST]; gp_brush->size = 50; gp_brush->strength = 0.3f; // XXX? gp_brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF; - + gp_brush = &gset->brush[GP_EDITBRUSH_TYPE_PINCH]; gp_brush->size = 50; gp_brush->strength = 0.5f; // XXX? gp_brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF; - + gp_brush = &gset->brush[GP_EDITBRUSH_TYPE_RANDOMIZE]; gp_brush->size = 25; gp_brush->strength = 0.5f; gp_brush->flag = GP_EDITBRUSH_FLAG_USE_FALLOFF; } - + /* GP Stroke Placement */ sce->toolsettings->gpencil_v3d_align = GP_PROJECT_VIEWSPACE; sce->toolsettings->gpencil_v2d_align = GP_PROJECT_VIEWSPACE; @@ -808,15 +806,8 @@ void BKE_scene_init(Scene *sce) copy_v3_v3(sce->display.light_direction, (float[3]){-M_SQRT1_3, -M_SQRT1_3, M_SQRT1_3}); sce->display.shadow_shift = 0.1; - sce->display.matcap_icon = 1; - sce->display.matcap_type = CLAY_MATCAP_NONE; - sce->display.matcap_hue = 0.5f; - sce->display.matcap_saturation = 0.5f; - sce->display.matcap_value = 0.5f; sce->display.matcap_ssao_distance = 0.2f; sce->display.matcap_ssao_attenuation = 1.0f; - sce->display.matcap_ssao_factor_cavity = 1.0f; - sce->display.matcap_ssao_factor_edge = 1.0f; sce->display.matcap_ssao_samples = 16; /* SceneEEVEE */ @@ -920,10 +911,10 @@ Object *BKE_scene_object_find_by_name(Scene *scene, const char *name) void BKE_scene_set_background(Main *bmain, Scene *scene) { Object *ob; - + /* check for cyclic sets, for reading old files but also for definite security (py?) */ BKE_scene_validate_setscene(bmain, scene); - + /* deselect objects (for dataselect) */ for (ob = bmain->object.first; ob; ob = ob->id.next) ob->flag &= ~SELECT; @@ -958,7 +949,7 @@ int BKE_scene_base_iter_next(Depsgraph *depsgraph, SceneBaseIter *iter, Scene **scene, int val, Base **base, Object **ob) { bool run_again = true; - + /* init */ if (val == 0) { iter->phase = F_START; @@ -1017,19 +1008,19 @@ int BKE_scene_base_iter_next(Depsgraph *depsgraph, SceneBaseIter *iter, } } } - + if (*base == NULL) { iter->phase = F_START; } else { if (iter->phase != F_DUPLI) { if (depsgraph && (*base)->object->transflag & OB_DUPLI) { - /* collections cannot be duplicated for mballs yet, - * this enters eternal loop because of + /* collections cannot be duplicated for mballs yet, + * this enters eternal loop because of * makeDispListMBall getting called inside of collection_duplilist */ if ((*base)->object->dup_group == NULL) { iter->duplilist = object_duplilist(depsgraph, (*scene), (*base)->object); - + iter->dupob = iter->duplilist->first; if (!iter->dupob) { @@ -1062,13 +1053,13 @@ int BKE_scene_base_iter_next(Depsgraph *depsgraph, SceneBaseIter *iter, else if (iter->phase == F_DUPLI) { iter->phase = F_SCENE; (*base)->flag_legacy &= ~OB_FROMDUPLI; - + if (iter->dupli_refob) { /* Restore last object's real matrix. */ copy_m4_m4(iter->dupli_refob->obmat, iter->omat); iter->dupli_refob = NULL; } - + free_object_duplilist(iter->duplilist); iter->duplilist = NULL; run_again = true; @@ -1196,14 +1187,14 @@ char *BKE_scene_find_last_marker_name(Scene *scene, int frame) return best_marker ? best_marker->name : NULL; } -void BKE_scene_remove_rigidbody_object(Scene *scene, Object *ob) +void BKE_scene_remove_rigidbody_object(struct Main *bmain, Scene *scene, Object *ob) { /* remove rigid body constraint from world before removing object */ if (ob->rigidbody_constraint) BKE_rigidbody_remove_constraint(scene, ob); /* remove rigid body object from world before removing object */ if (ob->rigidbody_object) - BKE_rigidbody_remove_object(scene, ob); + BKE_rigidbody_remove_object(bmain, scene, ob); } /* checks for cycle, returns 1 if it's all OK */ @@ -1214,7 +1205,7 @@ bool BKE_scene_validate_setscene(Main *bmain, Scene *sce) if (sce->set == NULL) return true; totscene = BLI_listbase_count(&bmain->scene); - + for (a = 0, sce_iter = sce; sce_iter->set; sce_iter = sce_iter->set, a++) { /* more iterations than scenes means we have a cycle */ if (a > totscene) { @@ -1241,7 +1232,7 @@ float BKE_scene_frame_get_from_ctime(const Scene *scene, const float frame) float ctime = frame; ctime += scene->r.subframe; ctime *= scene->r.framelen; - + return ctime; } @@ -1333,7 +1324,7 @@ static void prepare_mesh_for_viewport_render( if (check_rendered_viewport_visible(bmain)) { BMesh *bm = mesh->edit_btmesh->bm; BM_mesh_bm_to_me( - bm, mesh, + bmain, bm, mesh, (&(struct BMeshToMeshParams){ .calc_object_remap = true, })); @@ -1621,7 +1612,7 @@ int BKE_render_num_threads(const RenderData *rd) threads = rd->threads; else threads = BLI_system_thread_count(); - + return max_ii(threads, 1); } diff --git a/source/blender/blenkernel/intern/screen.c b/source/blender/blenkernel/intern/screen.c index 8cff10902ef..5a6c55a9fcc 100644 --- a/source/blender/blenkernel/intern/screen.c +++ b/source/blender/blenkernel/intern/screen.c @@ -65,7 +65,7 @@ static void spacetype_free(SpaceType *st) ARegionType *art; PanelType *pt; HeaderType *ht; - + for (art = st->regiontypes.first; art; art = art->next) { BLI_freelistN(&art->drawcalls); @@ -86,7 +86,7 @@ static void spacetype_free(SpaceType *st) BLI_freelistN(&art->paneltypes); BLI_freelistN(&art->headertypes); } - + BLI_freelistN(&st->regiontypes); BLI_freelistN(&st->toolshelf); @@ -95,18 +95,18 @@ static void spacetype_free(SpaceType *st) void BKE_spacetypes_free(void) { SpaceType *st; - + for (st = spacetypes.first; st; st = st->next) { spacetype_free(st); } - + BLI_freelistN(&spacetypes); } SpaceType *BKE_spacetype_from_id(int spaceid) { SpaceType *st; - + for (st = spacetypes.first; st; st = st->next) { if (st->spaceid == spaceid) return st; @@ -114,18 +114,30 @@ SpaceType *BKE_spacetype_from_id(int spaceid) return NULL; } -ARegionType *BKE_regiontype_from_id(SpaceType *st, int regionid) +ARegionType *BKE_regiontype_from_id_or_first(SpaceType *st, int regionid) { ARegionType *art; - + for (art = st->regiontypes.first; art; art = art->next) if (art->regionid == regionid) return art; - + printf("Error, region type %d missing in - name:\"%s\", id:%d\n", regionid, st->name, st->spaceid); return st->regiontypes.first; } +ARegionType *BKE_regiontype_from_id(SpaceType *st, int regionid) +{ + ARegionType *art; + + for (art = st->regiontypes.first; art; art = art->next) { + if (art->regionid == regionid) { + return art; + } + } + return NULL; +} + const ListBase *BKE_spacetypes_list(void) { @@ -135,7 +147,7 @@ const ListBase *BKE_spacetypes_list(void) void BKE_spacetype_register(SpaceType *st) { SpaceType *stype; - + /* sanity check */ stype = BKE_spacetype_from_id(st->spaceid); if (stype) { @@ -143,7 +155,7 @@ void BKE_spacetype_register(SpaceType *st) spacetype_free(stype); MEM_freeN(stype); } - + BLI_addtail(&spacetypes, st); } @@ -158,20 +170,20 @@ void BKE_spacedata_freelist(ListBase *lb) { SpaceLink *sl; ARegion *ar; - + for (sl = lb->first; sl; sl = sl->next) { SpaceType *st = BKE_spacetype_from_id(sl->spacetype); - + /* free regions for pushed spaces */ for (ar = sl->regionbase.first; ar; ar = ar->next) BKE_area_region_free(st, ar); BLI_freelistN(&sl->regionbase); - - if (st && st->free) + + if (st && st->free) st->free(sl); } - + BLI_freelistN(lb); } @@ -204,7 +216,7 @@ static void panel_list_copy(ListBase *newlb, const ListBase *lb) ARegion *BKE_area_region_copy(SpaceType *st, ARegion *ar) { ARegion *newar = MEM_dupallocN(ar); - + newar->prev = newar->next = NULL; BLI_listbase_clear(&newar->handlers); BLI_listbase_clear(&newar->uiblocks); @@ -216,25 +228,30 @@ ARegion *BKE_area_region_copy(SpaceType *st, ARegion *ar) newar->regiontimer = NULL; newar->headerstr = NULL; newar->draw_buffer = NULL; - + /* use optional regiondata callback */ if (ar->regiondata) { ARegionType *art = BKE_regiontype_from_id(st, ar->regiontype); - if (art && art->duplicate) + if (art && art->duplicate) { newar->regiondata = art->duplicate(ar->regiondata); - else + } + else if (ar->flag & RGN_FLAG_TEMP_REGIONDATA) { + newar->regiondata = NULL; + } + else { newar->regiondata = MEM_dupallocN(ar->regiondata); + } } if (ar->v2d.tab_offset) newar->v2d.tab_offset = MEM_dupallocN(ar->v2d.tab_offset); - + panel_list_copy(&newar->panels, &ar->panels); BLI_listbase_clear(&newar->ui_previews); BLI_duplicatelist(&newar->ui_previews, &ar->ui_previews); - + return newar; } @@ -243,10 +260,10 @@ ARegion *BKE_area_region_copy(SpaceType *st, ARegion *ar) static void region_copylist(SpaceType *st, ListBase *lb1, ListBase *lb2) { ARegion *ar; - + /* to be sure */ BLI_listbase_clear(lb1); - + for (ar = lb2->first; ar; ar = ar->next) { ARegion *arnew = BKE_area_region_copy(st, ar); BLI_addtail(lb1, arnew); @@ -258,17 +275,17 @@ static void region_copylist(SpaceType *st, ListBase *lb1, ListBase *lb2) void BKE_spacedata_copylist(ListBase *lb1, ListBase *lb2) { SpaceLink *sl; - + BLI_listbase_clear(lb1); /* to be sure */ - + for (sl = lb2->first; sl; sl = sl->next) { SpaceType *st = BKE_spacetype_from_id(sl->spacetype); - + if (st && st->duplicate) { SpaceLink *slnew = st->duplicate(sl); - + BLI_addtail(lb1, slnew); - + region_copylist(st, &slnew->regionbase, &sl->regionbase); } } @@ -280,14 +297,14 @@ void BKE_spacedata_copylist(ListBase *lb1, ListBase *lb2) void BKE_spacedata_draw_locks(int set) { SpaceType *st; - + for (st = spacetypes.first; st; st = st->next) { ARegionType *art; - + for (art = st->regiontypes.first; art; art = art->next) { - if (set) + if (set) art->do_lock = art->lock; - else + else art->do_lock = false; } } @@ -365,16 +382,16 @@ void BKE_area_region_free(SpaceType *st, ARegion *ar) if (st) { ARegionType *art = BKE_regiontype_from_id(st, ar->regiontype); - + if (art && art->free) art->free(ar); - + if (ar->regiondata) printf("regiondata free error\n"); } else if (ar->type && ar->type->free) ar->type->free(ar); - + if (ar->v2d.tab_offset) { MEM_freeN(ar->v2d.tab_offset); ar->v2d.tab_offset = NULL; @@ -414,15 +431,15 @@ void BKE_screen_area_free(ScrArea *sa) { SpaceType *st = BKE_spacetype_from_id(sa->spacetype); ARegion *ar; - + for (ar = sa->regionbase.first; ar; ar = ar->next) BKE_area_region_free(st, ar); MEM_SAFE_FREE(sa->global); BLI_freelistN(&sa->regionbase); - + BKE_spacedata_freelist(&sa->spacedata); - + BLI_freelistN(&sa->actionzones); } @@ -444,7 +461,7 @@ void BKE_screen_free(bScreen *sc) ARegion *ar; /* No animdata here. */ - + for (ar = sc->regionbase.first; ar; ar = ar->next) BKE_area_region_free(NULL, ar); @@ -652,7 +669,7 @@ ARegion *BKE_area_find_region_type(ScrArea *sa, int type) { if (sa) { ARegion *ar; - + for (ar = sa->regionbase.first; ar; ar = ar->next) { if (ar->regiontype == type) return ar; diff --git a/source/blender/blenkernel/intern/seqeffects.c b/source/blender/blenkernel/intern/seqeffects.c index 00af9721f07..9105961a3ae 100644 --- a/source/blender/blenkernel/intern/seqeffects.c +++ b/source/blender/blenkernel/intern/seqeffects.c @@ -127,7 +127,7 @@ static ImBuf *prepare_effect_imbufs(const SeqRenderData *context, ImBuf *ibuf1, else { out = IMB_allocImBuf(x, y, 32, IB_rect); } - + if (out->rect_float) { if (ibuf1 && !ibuf1->rect_float) { BKE_sequencer_imbuf_to_sequencer_space(scene, ibuf1, true); @@ -140,7 +140,7 @@ static ImBuf *prepare_effect_imbufs(const SeqRenderData *context, ImBuf *ibuf1, if (ibuf3 && !ibuf3->rect_float) { BKE_sequencer_imbuf_to_sequencer_space(scene, ibuf3, true); } - + IMB_colormanagement_assign_float_colorspace(out, scene->sequencer_colorspace_settings.name); } else { @@ -369,7 +369,7 @@ static void do_alphaunder_effect_byte( tempc[1] = (fac * rt1[1] + rt2[1]); tempc[2] = (fac * rt1[2] + rt2[2]); tempc[3] = (fac * rt1[3] + rt2[3]); - + premul_float_to_straight_uchar(rt, tempc); } } @@ -384,10 +384,10 @@ static void do_alphaunder_effect_byte( while (x--) { straight_uchar_to_premul_float(rt1, cp1); straight_uchar_to_premul_float(rt2, cp2); - + if (rt2[3] <= 0.0f && fac4 >= 1.0f) *((unsigned int *) rt) = *((unsigned int *) cp1); else if (rt2[3] >= 1.0f) *((unsigned int *) rt) = *((unsigned int *) cp2); - else { + else { fac = (fac4 * (1.0f - rt2[3])); if (fac <= 0) *((unsigned int *)rt) = *((unsigned int *)cp2); @@ -396,7 +396,7 @@ static void do_alphaunder_effect_byte( tempc[1] = (fac * rt1[1] + rt2[1]); tempc[2] = (fac * rt1[2] + rt2[2]); tempc[3] = (fac * rt1[3] + rt2[3]); - + premul_float_to_straight_uchar(rt, tempc); } } @@ -628,7 +628,7 @@ static float gamma_range_table[RE_GAMMA_TABLE_SIZE + 1]; static float gamfactor_table[RE_GAMMA_TABLE_SIZE]; static float inv_gamma_range_table[RE_GAMMA_TABLE_SIZE + 1]; static float inv_gamfactor_table[RE_GAMMA_TABLE_SIZE]; -static float color_domain_table[RE_GAMMA_TABLE_SIZE + 1]; +static float color_domain_table[RE_GAMMA_TABLE_SIZE + 1]; static float color_step; static float inv_color_step; static float valid_gamma; @@ -642,7 +642,7 @@ static void makeGammaTables(float gamma) valid_gamma = gamma; valid_inv_gamma = 1.0f / gamma; color_step = 1.0f / RE_GAMMA_TABLE_SIZE; - inv_color_step = (float) RE_GAMMA_TABLE_SIZE; + inv_color_step = (float) RE_GAMMA_TABLE_SIZE; /* We could squeeze out the two range tables to gain some memory */ for (i = 0; i < RE_GAMMA_TABLE_SIZE; i++) { @@ -674,7 +674,7 @@ static float gammaCorrect(float c) { int i; float res; - + i = floorf(c * inv_color_step); /* Clip to range [0, 1]: outside, just do the complete calculation. * We may have some performance problems here. Stretching up the LUT @@ -685,7 +685,7 @@ static float gammaCorrect(float c) else if (i >= RE_GAMMA_TABLE_SIZE) res = powf(c, valid_gamma); else res = gamma_range_table[i] + ((c - color_domain_table[i]) * gamfactor_table[i]); - + return res; } @@ -710,17 +710,17 @@ static void gamtabs(float gamma) { float val, igamma = 1.0f / gamma; int a; - + /* gamtab: in short, out short */ for (a = 0; a < 65536; a++) { val = a; val /= 65535.0f; - + if (gamma == 2.0f) val = sqrtf(val); else if (gamma != 1.0f) val = powf(val, igamma); - + gamtab[a] = (65535.99f * val); } /* inverse gamtab1 : in byte, out short */ @@ -1317,7 +1317,7 @@ BLI_INLINE void apply_blend_function_byte( rt1 = rect1; rt2 = rect2; rt = out; - while (y--) { + while (y--) { for (x = xo; x > 0; x--) { achannel = rt2[3]; rt2[3] = (unsigned int) achannel * facf0; @@ -1331,7 +1331,7 @@ BLI_INLINE void apply_blend_function_byte( if (y == 0) { break; } - y--; + y--; for (x = xo; x > 0; x--) { achannel = rt2[3]; rt2[3] = (unsigned int) achannel * facf1; @@ -1356,7 +1356,7 @@ BLI_INLINE void apply_blend_function_float( rt1 = rect1; rt2 = rect2; rt = out; - while (y--) { + while (y--) { for (x = xo; x > 0; x--) { achannel = rt2[3]; rt2[3] = achannel * facf0; @@ -1370,7 +1370,7 @@ BLI_INLINE void apply_blend_function_float( if (y == 0) { break; } - y--; + y--; for (x = xo; x > 0; x--) { achannel = rt2[3]; rt2[3] = achannel * facf1; @@ -1853,7 +1853,7 @@ static float check_zone(WipeZone *wipezone, int x, int y, Sequence *seq, float f else output = in_band(hwidth, fabsf(temp2 - pointdist), 1, 1); if (!wipe->forward) output = 1 - output; - + break; } if (output < 0) output = 0; @@ -2054,7 +2054,7 @@ static void init_transform_effect(Sequence *seq) transform->yIni = 0.0f; transform->rotIni = 0.0f; - + transform->interpolation = 1; transform->percent = 1; transform->uniform_scale = 0; @@ -2086,7 +2086,7 @@ static void transform_image( xo = x; yo = y; - + /* Rotate */ s = sinf(rotate); c = cosf(rotate); @@ -2129,7 +2129,7 @@ static void do_transform(Scene *scene, Sequence *seq, float UNUSED(facf0), int x { TransformVars *transform = (TransformVars *) seq->effectdata; float scale_x, scale_y, translate_x, translate_y, rotate_radians; - + /* Scale */ if (transform->uniform_scale) { scale_x = scale_y = transform->ScalexIni; @@ -2293,7 +2293,7 @@ static void RVBlurBitmap2_float(float *map, int width, int height, float blur, i index = (x + (height - 1 - y) * width) * 4; copy_v4_v4(temp + index, curColor2); } - + /* Do the main body */ for (y = halfWidth; y < height - halfWidth; y++) { fy = 0; @@ -2462,12 +2462,12 @@ static ImBuf *do_glow_effect( static void init_solid_color(Sequence *seq) { SolidColorVars *cv; - + if (seq->effectdata) MEM_freeN(seq->effectdata); seq->effectdata = MEM_callocN(sizeof(SolidColorVars), "solidcolor"); - + cv = (SolidColorVars *)seq->effectdata; cv->col[0] = cv->col[1] = cv->col[2] = 0.5; } @@ -2521,7 +2521,7 @@ static ImBuf *do_solid_color( col1[2] = facf1 * cv->col[2] * 255; rect = (unsigned char *)out->rect; - + for (y = 0; y < out->y; y++) { for (x = 0; x < out->x; x++, rect += 4) { rect[0] = col0[0]; @@ -2554,7 +2554,7 @@ static ImBuf *do_solid_color( col1[2] = facf1 * cv->col[2]; rect_float = out->rect_float; - + for (y = 0; y < out->y; y++) { for (x = 0; x < out->x; x++, rect_float += 4) { rect_float[0] = col0[0]; @@ -2623,7 +2623,7 @@ static ImBuf *do_multicam( else { out = i; } - + return out; } @@ -2698,7 +2698,7 @@ static ImBuf *do_adjustment( else { out = i; } - + return out; } @@ -2877,7 +2877,7 @@ void BKE_sequence_effect_speed_rebuild_map(Scene *scene, Sequence *seq, bool for facf *= seq->seq1->len; } facf *= v->globalSpeed; - + if (facf >= seq->seq1->len) { facf = seq->seq1->len - 1; } diff --git a/source/blender/blenkernel/intern/sequencer.c b/source/blender/blenkernel/intern/sequencer.c index ecd0335fc4e..d857db7e276 100644 --- a/source/blender/blenkernel/intern/sequencer.c +++ b/source/blender/blenkernel/intern/sequencer.c @@ -751,10 +751,10 @@ void BKE_sequence_calc_disp(Scene *scene, Sequence *seq) seq->startstill = 0; if (seq->endofs && seq->endstill) seq->endstill = 0; - + seq->startdisp = seq->start + seq->startofs - seq->startstill; seq->enddisp = seq->start + seq->len - seq->endofs + seq->endstill; - + seq->handsize = 10.0; /* 10 frames */ if (seq->enddisp - seq->startdisp < 10) { seq->handsize = (float)(0.5 * (seq->enddisp - seq->startdisp)); @@ -1016,7 +1016,7 @@ void BKE_sequence_reload_new_file(Scene *scene, Sequence *seq, const bool lock_r BKE_sequence_tx_set_final_right(seq, prev_enddisp); BKE_sequence_single_fix(seq); } - + BKE_sequence_calc(scene, seq); } @@ -1280,7 +1280,7 @@ static void multibuf(ImBuf *ibuf, const float fmul) rt_float[1] *= fmul; rt_float[2] *= fmul; rt_float[3] *= fmul; - + rt_float += 4; } } @@ -1311,9 +1311,9 @@ static float give_stripelem_index(Sequence *seq, float cfra) else if (cfra >= end) nr = end - sta; else nr = cfra - sta; } - + if (seq->strobe < 1.0f) seq->strobe = 1.0f; - + if (seq->strobe > 1.0f) { nr -= fmodf((double)nr, (double)seq->strobe); } @@ -1334,7 +1334,7 @@ StripElem *BKE_sequencer_give_stripelem(Sequence *seq, int cfra) if (nr == -1 || se == NULL) return NULL; - + se += nr + seq->anim_startofs; } return se; @@ -1431,7 +1431,7 @@ static int get_shown_sequences(ListBase *seqbasep, int cfra, int chanshown, Sequ } } } - + chanshown = b; for (; b > 0; b--) { @@ -1662,7 +1662,7 @@ static bool seq_proxy_get_fname(Editing *ed, Sequence *seq, int cfra, int render return false; } - /* MOVIE tracks (only exception: custom files) are now handled + /* MOVIE tracks (only exception: custom files) are now handled * internally by ImBuf module for various reasons: proper time code * support, quicker index build, using one file instead * of a full directory of jpeg files, etc. Trying to support old @@ -2107,7 +2107,7 @@ void BKE_sequencer_proxy_set(struct Sequence *seq, bool value) } else { seq->flag &= ~SEQ_USE_PROXY; - } + } } /*********************** color balance *************************/ @@ -2207,7 +2207,7 @@ static void color_balance_byte_byte(StripColorBalance *cb_, unsigned char *rect, else p[c] = t; } - + premul_float_to_straight_uchar(cp, p); cp += 4; @@ -2559,7 +2559,7 @@ static ImBuf *input_preprocess(const SeqRenderData *context, Sequence *seq, floa if (seq->flag & SEQ_FLIPX) { IMB_flipx(ibuf); } - + if (seq->flag & SEQ_FLIPY) { IMB_flipy(ibuf); } @@ -3077,7 +3077,7 @@ static ImBuf *seq_render_movieclip_strip(const SeqRenderData *context, Sequence } memset(&user, 0, sizeof(MovieClipUser)); - + BKE_movieclip_user_set_frame(&user, nr + seq->anim_startofs + seq->clip->start_frame); user.render_size = MCLIP_PROXY_RENDER_SIZE_FULL; @@ -3294,7 +3294,7 @@ static ImBuf *seq_render_scene_strip(const SeqRenderData *context, Sequence *seq BKE_scene_camera_switch_update(scene); camera = scene->camera; } - + if (have_comp == false && camera == NULL) { goto finally; } @@ -3679,13 +3679,13 @@ static bool seq_must_swap_input_in_blend_mode(Sequence *seq) { bool swap_input = false; - /* bad hack, to fix crazy input ordering of + /* bad hack, to fix crazy input ordering of * those two effects */ if (ELEM(seq->blend_mode, SEQ_TYPE_ALPHAOVER, SEQ_TYPE_ALPHAUNDER, SEQ_TYPE_OVERDROP)) { swap_input = true; } - + return swap_input; } @@ -3762,7 +3762,7 @@ static ImBuf *seq_render_strip_stack( if (out) { return out; } - + if (count == 1) { Sequence *seq = seq_arr[0]; @@ -3887,7 +3887,7 @@ ImBuf *BKE_sequencer_give_ibuf(const SeqRenderData *context, float cfra, int cha { Editing *ed = BKE_sequencer_editing_get(context->scene, false); ListBase *seqbasep; - + if (ed == NULL) return NULL; if ((chanshown < 0) && !BLI_listbase_is_empty(&ed->metastack)) { @@ -3938,23 +3938,23 @@ static pthread_cond_t wakeup_cond = PTHREAD_COND_INITIALIZER; static pthread_mutex_t frame_done_lock = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t frame_done_cond = PTHREAD_COND_INITIALIZER; -static volatile bool seq_thread_shutdown = true; +static volatile bool seq_thread_shutdown = true; static volatile int seq_last_given_monoton_cfra = 0; static int monoton_cfra = 0; typedef struct PrefetchThread { struct PrefetchThread *next, *prev; - + Scene *scene; struct PrefetchQueueElem *current; pthread_t pthread; int running; - + } PrefetchThread; typedef struct PrefetchQueueElem { struct PrefetchQueueElem *next, *prev; - + int rectx; int recty; float cfra; @@ -3984,7 +3984,7 @@ void BKE_sequencer_give_ibuf_prefetch_request(const SeqRenderData *context, floa pthread_mutex_lock(&queue_lock); BLI_addtail(&prefetch_wait, e); pthread_mutex_unlock(&queue_lock); - + pthread_mutex_lock(&wakeup_lock); pthread_cond_signal(&wakeup_cond); pthread_mutex_unlock(&wakeup_lock); @@ -4070,7 +4070,7 @@ ImBuf *BKE_sequencer_give_ibuf_threaded(const SeqRenderData *context, float cfra pthread_mutex_unlock(&frame_done_lock); } } - + return e ? e->ibuf : NULL; } @@ -4186,30 +4186,30 @@ void BKE_sequencer_free_imbuf(Scene *scene, ListBase *seqbase, bool for_render) BKE_sequencer_free_imbuf(scene, &seq->seqbase, for_render); } if (seq->type == SEQ_TYPE_SCENE) { - /* FIXME: recurs downwards, + /* FIXME: recurs downwards, * but do recurs protection somehow! */ } } - + } static bool update_changed_seq_recurs(Scene *scene, Sequence *seq, Sequence *changed_seq, int len_change, int ibuf_change) { Sequence *subseq; bool free_imbuf = false; - + /* recurs downwards to see if this seq depends on the changed seq */ - + if (seq == NULL) return false; - + if (seq == changed_seq) free_imbuf = true; - + for (subseq = seq->seqbase.first; subseq; subseq = subseq->next) if (update_changed_seq_recurs(scene, subseq, changed_seq, len_change, ibuf_change)) free_imbuf = true; - + if (seq->seq1) if (update_changed_seq_recurs(scene, seq->seq1, changed_seq, len_change, ibuf_change)) free_imbuf = true; @@ -4219,7 +4219,7 @@ static bool update_changed_seq_recurs(Scene *scene, Sequence *seq, Sequence *cha if (seq->seq3 && (seq->seq3 != seq->seq1) && (seq->seq3 != seq->seq2)) if (update_changed_seq_recurs(scene, seq->seq3, changed_seq, len_change, ibuf_change)) free_imbuf = true; - + if (free_imbuf) { if (ibuf_change) { if (seq->type == SEQ_TYPE_MOVIE) { @@ -4229,11 +4229,11 @@ static bool update_changed_seq_recurs(Scene *scene, Sequence *seq, Sequence *cha BKE_sequence_effect_speed_rebuild_map(scene, seq, true); } } - + if (len_change) BKE_sequence_calc(scene, seq); } - + return free_imbuf; } @@ -4241,9 +4241,9 @@ void BKE_sequencer_update_changed_seq_and_deps(Scene *scene, Sequence *changed_s { Editing *ed = BKE_sequencer_editing_get(scene, false); Sequence *seq; - + if (ed == NULL) return; - + for (seq = ed->seqbase.first; seq; seq = seq->next) update_changed_seq_recurs(scene, seq, changed_seq, len_change, ibuf_change); } @@ -4500,9 +4500,9 @@ Sequence *BKE_sequencer_foreground_frame_get(Scene *scene, int frame) Editing *ed = BKE_sequencer_editing_get(scene, false); Sequence *seq, *best_seq = NULL; int best_machine = -1; - + if (!ed) return NULL; - + for (seq = ed->seqbasep->first; seq; seq = seq->next) { if (seq->flag & SEQ_MUTE || seq->startdisp > frame || seq->enddisp <= frame) continue; @@ -4961,7 +4961,7 @@ static void seq_free_animdata(Scene *scene, Sequence *seq) while (fcu) { if (STREQLEN(fcu->rna_path, str, str_len)) { FCurve *next_fcu = fcu->next; - + BLI_remlink(&scene->adt->action->curves, fcu); free_fcurve(fcu); @@ -5215,7 +5215,7 @@ Sequence *BKE_sequencer_add_image_strip(bContext *C, ListBase *seqbasep, SeqLoad seq = BKE_sequence_alloc(seqbasep, seq_load->start_frame, seq_load->channel); seq->type = SEQ_TYPE_IMAGE; seq->blend_mode = SEQ_TYPE_CROSS; /* so alpha adjustment fade to the strip below */ - + /* basic defaults */ seq->strip = strip = MEM_callocN(sizeof(Strip), "strip"); @@ -5403,7 +5403,7 @@ Sequence *BKE_sequencer_add_movie_strip(bContext *C, ListBase *seqbasep, SeqLoad seq->anim_preseek = IMB_anim_get_preseek(anim_arr[0]); BLI_strncpy(seq->name + 2, "Movie", SEQ_NAME_MAXSTR - 2); BKE_sequence_base_unique_name_recursive(&scene->ed->seqbase, seq); - + /* adjust scene's frame rate settings to match */ if (seq_load->flag & SEQ_LOAD_SYNC_FPS) { IMB_anim_get_fps(anim_arr[0], &scene->r.frs_sec, &scene->r.frs_sec_base, true); @@ -5724,10 +5724,10 @@ static void sequencer_all_free_anim_ibufs(ListBase *seqbase, int cfra) } } -void BKE_sequencer_all_free_anim_ibufs(int cfra) +void BKE_sequencer_all_free_anim_ibufs(Main *bmain, int cfra) { BKE_sequencer_cache_cleanup(); - for (Scene *scene = G.main->scene.first; + for (Scene *scene = bmain->scene.first; scene != NULL; scene = scene->id.next) { diff --git a/source/blender/blenkernel/intern/shrinkwrap.c b/source/blender/blenkernel/intern/shrinkwrap.c index a7b233bc042..f8615671384 100644 --- a/source/blender/blenkernel/intern/shrinkwrap.c +++ b/source/blender/blenkernel/intern/shrinkwrap.c @@ -166,7 +166,7 @@ static void shrinkwrap_calc_nearest_vertex(ShrinkwrapCalcData *calc) OUT_OF_MEMORY(); return; } - + /* Setup nearest */ nearest.index = -1; nearest.dist_sq = FLT_MAX; diff --git a/source/blender/blenkernel/intern/smoke.c b/source/blender/blenkernel/intern/smoke.c index 738be9ded54..6bdce647bd9 100644 --- a/source/blender/blenkernel/intern/smoke.c +++ b/source/blender/blenkernel/intern/smoke.c @@ -1812,7 +1812,7 @@ static void adjustDomainResolution(SmokeDomainSettings *sds, int new_shift[3], E int zn = z - new_shift[2]; int index; float max_den; - + /* skip if cell already belongs to new area */ if (xn >= min[0] && xn <= max[0] && yn >= min[1] && yn <= max[1] && zn >= min[2] && zn <= max[2]) continue; diff --git a/source/blender/blenkernel/intern/softbody.c b/source/blender/blenkernel/intern/softbody.c index 9aa6c172a90..31644cc2392 100644 --- a/source/blender/blenkernel/intern/softbody.c +++ b/source/blender/blenkernel/intern/softbody.c @@ -75,6 +75,7 @@ variables on the UI for now #include "BKE_curve.h" #include "BKE_effect.h" #include "BKE_global.h" +#include "BKE_layer.h" #include "BKE_modifier.h" #include "BKE_softbody.h" #include "BKE_pointcache.h" @@ -516,19 +517,17 @@ static void ccd_build_deflector_hash_single(GHash *hash, Object *ob) /** * \note collection overrides scene when not NULL. */ -static void ccd_build_deflector_hash(ViewLayer *view_layer, Collection *collection, Object *vertexowner, GHash *hash) +static void ccd_build_deflector_hash(Depsgraph *depsgraph, Collection *collection, Object *vertexowner, GHash *hash) { - Object *ob; - if (!hash) return; /* Explicit collision collection. */ - Base *base = BKE_collection_or_layer_objects(NULL, NULL, view_layer, collection); + Base *base = BKE_collection_or_layer_objects(depsgraph, NULL, NULL, collection); for (; base; base = base->next) { /* Only proceed for mesh object in same layer. */ if (base->object->type == OB_MESH) { - ob = base->object; + Object *ob = base->object; if (ob == vertexowner) { /* If vertexowner is given we don't want to check collision with owner object. */ continue; @@ -551,19 +550,17 @@ static void ccd_update_deflector_hash_single(GHash *hash, Object *ob) /** * \note collection overrides scene when not NULL. */ -static void ccd_update_deflector_hash(ViewLayer *view_layer, Collection *collection, Object *vertexowner, GHash *hash) +static void ccd_update_deflector_hash(Depsgraph *depsgraph, Collection *collection, Object *vertexowner, GHash *hash) { - Object *ob; - if ((!hash) || (!vertexowner)) return; /* Explicit collision collection. */ - Base *base = BKE_collection_or_layer_objects(NULL, NULL, view_layer, collection); + Base *base = BKE_collection_or_layer_objects(depsgraph, NULL, NULL, collection); for (; base; base = base->next) { /* Only proceed for mesh object in same layer. */ if (base->object->type == OB_MESH) { - ob = base->object; + Object *ob = base->object; if (ob == vertexowner) { /* If vertexowner is given we don't want to check collision with owner object. */ continue; @@ -974,9 +971,9 @@ static bool are_there_deflectors(Base *first_base) return 0; } -static int query_external_colliders(ViewLayer *view_layer, Collection *collection) +static int query_external_colliders(Depsgraph *depsgraph, Collection *collection) { - return(are_there_deflectors(BKE_collection_or_layer_objects(NULL, NULL, view_layer, collection))); + return(are_there_deflectors(BKE_collection_or_layer_objects(depsgraph, NULL, NULL, collection))); } /* --- dependency information functions*/ @@ -2220,7 +2217,7 @@ static void softbody_calc_forcesEx(struct Depsgraph *depsgraph, Scene *scene, Ob /* gravity = sb->grav * sb_grav_force_scale(ob); */ /* UNUSED */ /* check conditions for various options */ - do_deflector= query_external_colliders(DEG_get_evaluated_view_layer(depsgraph), sb->collision_group); + do_deflector= query_external_colliders(depsgraph, sb->collision_group); /* do_selfcollision=((ob->softflag & OB_SB_EDGES) && (sb->bspring)&& (ob->softflag & OB_SB_SELF)); */ /* UNUSED */ do_springcollision=do_deflector && (ob->softflag & OB_SB_EDGES) &&(ob->softflag & OB_SB_EDGECOLL); do_aero=((sb->aeroedge)&& (ob->softflag & OB_SB_EDGES)); @@ -2284,7 +2281,7 @@ static void softbody_calc_forces(struct Depsgraph *depsgraph, Scene *scene, Obje } /* check conditions for various options */ - do_deflector= query_external_colliders(DEG_get_evaluated_view_layer(depsgraph), sb->collision_group); + do_deflector= query_external_colliders(depsgraph, sb->collision_group); do_selfcollision=((ob->softflag & OB_SB_EDGES) && (sb->bspring)&& (ob->softflag & OB_SB_SELF)); do_springcollision=do_deflector && (ob->softflag & OB_SB_EDGES) &&(ob->softflag & OB_SB_EDGECOLL); do_aero=((sb->aeroedge)&& (ob->softflag & OB_SB_EDGES)); @@ -2839,7 +2836,7 @@ static void mesh_to_softbody(Scene *scene, Object *ob) BodySpring *bs; int a, totedge; int defgroup_index, defgroup_index_mass, defgroup_index_spring; - + if (ob->softflag & OB_SB_EDGES) totedge= me->totedge; else totedge= 0; @@ -3495,13 +3492,11 @@ static void softbody_step(struct Depsgraph *depsgraph, Scene *scene, Object *ob, */ if (dtime < 0 || dtime > 10.5f) return; - ViewLayer *view_layer = DEG_get_evaluated_view_layer(depsgraph); - - ccd_update_deflector_hash(view_layer, sb->collision_group, ob, sb->scratch->colliderhash); + ccd_update_deflector_hash(depsgraph, sb->collision_group, ob, sb->scratch->colliderhash); if (sb->scratch->needstobuildcollider) { - if (query_external_colliders(view_layer, sb->collision_group)) { - ccd_build_deflector_hash(view_layer, sb->collision_group, ob, sb->scratch->colliderhash); + if (query_external_colliders(depsgraph, sb->collision_group)) { + ccd_build_deflector_hash(depsgraph, sb->collision_group, ob, sb->scratch->colliderhash); } sb->scratch->needstobuildcollider=0; } diff --git a/source/blender/blenkernel/intern/sound.c b/source/blender/blenkernel/intern/sound.c index a7f3fc1df9e..ebb23f8d5c6 100644 --- a/source/blender/blenkernel/intern/sound.c +++ b/source/blender/blenkernel/intern/sound.c @@ -144,7 +144,7 @@ void BKE_sound_free(bSound *sound) } BKE_sound_free_waveform(sound); - + #endif /* WITH_AUDASPACE */ if (sound->spinlock) { BLI_spin_end(sound->spinlock); @@ -774,7 +774,7 @@ void BKE_sound_read_waveform(bSound *sound, short *stop) if (info.length > 0) { int length = info.length * SOUND_WAVE_SAMPLES_PER_SECOND; - + waveform->data = MEM_mallocN(length * sizeof(float) * 3, "SoundWaveform.samples"); waveform->length = AUD_readSound(sound->playback_handle, waveform->data, length, SOUND_WAVE_SAMPLES_PER_SECOND, stop); } @@ -797,9 +797,9 @@ void BKE_sound_read_waveform(bSound *sound, short *stop) BLI_spin_unlock(sound->spinlock); return; } - + BKE_sound_free_waveform(sound); - + BLI_spin_lock(sound->spinlock); sound->waveform = waveform; sound->flags &= ~SOUND_FLAGS_WAVEFORM_LOADING; diff --git a/source/blender/blenkernel/intern/studiolight.c b/source/blender/blenkernel/intern/studiolight.c index e4b49656907..62361917f2f 100644 --- a/source/blender/blenkernel/intern/studiolight.c +++ b/source/blender/blenkernel/intern/studiolight.c @@ -42,6 +42,7 @@ #include "BLI_path_util.h" #include "BLI_rand.h" #include "BLI_string.h" +#include "BLI_string_utils.h" #include "DNA_listBase.h" @@ -55,59 +56,88 @@ /* Statics */ static ListBase studiolights; -#define STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE 8 +#define STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE 128 #define STUDIOLIGHT_IRRADIANCE_EQUIRECTANGULAR_HEIGHT 32 #define STUDIOLIGHT_IRRADIANCE_EQUIRECTANGULAR_WIDTH (STUDIOLIGHT_IRRADIANCE_EQUIRECTANGULAR_HEIGHT * 2) +/* + Disable this option so caches are not loaded from disk + Do not checkin with this commented out +*/ +#define STUDIOLIGHT_LOAD_CACHED_FILES + static const char *STUDIOLIGHT_CAMERA_FOLDER = "studiolights/camera/"; static const char *STUDIOLIGHT_WORLD_FOLDER = "studiolights/world/"; static const char *STUDIOLIGHT_MATCAP_FOLDER = "studiolights/matcap/"; /* FUNCTIONS */ +#define IMB_SAFE_FREE(p) do { \ +if (p) { \ + IMB_freeImBuf(p); \ + p = NULL; \ +} \ +} while (0) + +#define GPU_TEXTURE_SAFE_FREE(p) do { \ +if (p) { \ + GPU_texture_free(p); \ + p = NULL; \ +} \ +} while (0) + static void studiolight_free(struct StudioLight *sl) { - for (int index = 0 ; index < 6 ; index ++) { - if (sl->radiance_cubemap_buffers[index] != NULL) { - IMB_freeImBuf(sl->radiance_cubemap_buffers[index]); - sl->radiance_cubemap_buffers[index] = NULL; - } - - if (sl->equirectangular_radiance_gputexture) { - GPU_texture_free(sl->equirectangular_radiance_gputexture); - sl->equirectangular_radiance_gputexture = NULL; - } - - if (sl->equirectangular_irradiance_gputexture) { - GPU_texture_free(sl->equirectangular_irradiance_gputexture); - sl->equirectangular_irradiance_gputexture = NULL; - } - - if (sl->equirectangular_radiance_buffer) { - IMB_freeImBuf(sl->equirectangular_radiance_buffer); - sl->equirectangular_radiance_buffer = NULL; - } +#define STUDIOLIGHT_DELETE_ICON(s) { \ + if (s != 0) { \ + BKE_icon_delete(s); \ + s = 0; \ + } \ +} + if (sl->free_function) { + sl->free_function(sl, sl->free_function_data); + } + STUDIOLIGHT_DELETE_ICON(sl->icon_id_radiance); + STUDIOLIGHT_DELETE_ICON(sl->icon_id_irradiance); + STUDIOLIGHT_DELETE_ICON(sl->icon_id_matcap); + STUDIOLIGHT_DELETE_ICON(sl->icon_id_matcap_flipped); +#undef STUDIOLIGHT_DELETE_ICON - if (sl->equirectangular_irradiance_buffer) { - IMB_freeImBuf(sl->equirectangular_irradiance_buffer); - sl->equirectangular_irradiance_buffer = NULL; - } + for (int index = 0 ; index < 6 ; index ++) { + IMB_SAFE_FREE(sl->radiance_cubemap_buffers[index]); } - MEM_freeN(sl); + GPU_TEXTURE_SAFE_FREE(sl->equirectangular_radiance_gputexture); + GPU_TEXTURE_SAFE_FREE(sl->equirectangular_irradiance_gputexture); + IMB_SAFE_FREE(sl->equirectangular_radiance_buffer); + IMB_SAFE_FREE(sl->equirectangular_irradiance_buffer); + MEM_SAFE_FREE(sl->path_irr_cache); + MEM_SAFE_FREE(sl->path_sh_cache); + MEM_SAFE_FREE(sl->gpu_matcap_3components); + MEM_SAFE_FREE(sl); } -static struct StudioLight *studiolight_create(void) +static struct StudioLight *studiolight_create(int flag) { struct StudioLight *sl = MEM_callocN(sizeof(*sl), __func__); sl->path[0] = 0x00; sl->name[0] = 0x00; - sl->flag = 0; + sl->path_irr_cache = NULL; + sl->path_sh_cache = NULL; + sl->free_function = NULL; + sl->flag = flag; sl->index = BLI_listbase_count(&studiolights); - sl->radiance_icon_id = BKE_icon_ensure_studio_light(sl, STUDIOLIGHT_ICON_ID_TYPE_RADIANCE); - sl->irradiance_icon_id = BKE_icon_ensure_studio_light(sl, STUDIOLIGHT_ICON_ID_TYPE_IRRADIANCE); + if (flag & STUDIOLIGHT_ORIENTATION_VIEWNORMAL) { + sl->icon_id_matcap = BKE_icon_ensure_studio_light(sl, STUDIOLIGHT_ICON_ID_TYPE_MATCAP); + sl->icon_id_matcap_flipped = BKE_icon_ensure_studio_light(sl, STUDIOLIGHT_ICON_ID_TYPE_MATCAP_FLIPPED); + } + else { + sl->icon_id_radiance = BKE_icon_ensure_studio_light(sl, STUDIOLIGHT_ICON_ID_TYPE_RADIANCE); + sl->icon_id_irradiance = BKE_icon_ensure_studio_light(sl, STUDIOLIGHT_ICON_ID_TYPE_IRRADIANCE); + } for (int index = 0 ; index < 6 ; index ++) { sl->radiance_cubemap_buffers[index] = NULL; } + return sl; } @@ -158,7 +188,7 @@ static void studiolight_calculate_radiance_buffer( } } -static void studiolight_load_equierectangular_image(StudioLight *sl) +static void studiolight_load_equirectangular_image(StudioLight *sl) { if (sl->flag & STUDIOLIGHT_EXTERNAL_FILE) { ImBuf *ibuf = NULL; @@ -171,29 +201,47 @@ static void studiolight_load_equierectangular_image(StudioLight *sl) sl->flag |= STUDIOLIGHT_EXTERNAL_IMAGE_LOADED; } -static void studiolight_create_equierectangular_radiance_gputexture(StudioLight *sl) +static void studiolight_create_equirectangular_radiance_gputexture(StudioLight *sl) { if (sl->flag & STUDIOLIGHT_EXTERNAL_FILE) { char error[256]; BKE_studiolight_ensure_flag(sl, STUDIOLIGHT_EXTERNAL_IMAGE_LOADED); ImBuf *ibuf = sl->equirectangular_radiance_buffer; - sl->equirectangular_radiance_gputexture = GPU_texture_create_2D(ibuf->x, ibuf->y, GPU_RGBA8, ibuf->rect_float, error); - GPUTexture *tex = sl->equirectangular_radiance_gputexture; - GPU_texture_bind(tex, 0); - GPU_texture_filter_mode(tex, true); - GPU_texture_wrap_mode(tex, true); - GPU_texture_unbind(tex); + + if (sl->flag & STUDIOLIGHT_ORIENTATION_VIEWNORMAL) { + sl->gpu_matcap_3components = MEM_callocN(sizeof(float[3]) * ibuf->x * ibuf->y, __func__); + + float *offset4 = ibuf->rect_float; + float *offset3 = sl->gpu_matcap_3components; + for (int i = 0 ; i < ibuf->x * ibuf->y; i++) { + copy_v3_v3(offset3, offset4); + offset3 += 3; + offset4 += 4; + } + sl->equirectangular_radiance_gputexture = GPU_texture_create_2D( + ibuf->x, ibuf->y, GPU_R11F_G11F_B10F, sl->gpu_matcap_3components, error); + } + else { + sl->equirectangular_radiance_gputexture = GPU_texture_create_2D( + ibuf->x, ibuf->y, GPU_RGBA16F, ibuf->rect_float, error); + GPUTexture *tex = sl->equirectangular_radiance_gputexture; + GPU_texture_bind(tex, 0); + GPU_texture_filter_mode(tex, true); + GPU_texture_wrap_mode(tex, true); + GPU_texture_unbind(tex); + } } sl->flag |= STUDIOLIGHT_EQUIRECTANGULAR_RADIANCE_GPUTEXTURE; } -static void studiolight_create_equierectangular_irradiance_gputexture(StudioLight *sl) +static void studiolight_create_equirectangular_irradiance_gputexture(StudioLight *sl) { if (sl->flag & STUDIOLIGHT_EXTERNAL_FILE) { char error[256]; BKE_studiolight_ensure_flag(sl, STUDIOLIGHT_EQUIRECTANGULAR_IRRADIANCE_IMAGE_CALCULATED); ImBuf *ibuf = sl->equirectangular_irradiance_buffer; - sl->equirectangular_irradiance_gputexture = GPU_texture_create_2D(ibuf->x, ibuf->y, GPU_RGBA16F, ibuf->rect_float, error); + sl->equirectangular_irradiance_gputexture = GPU_texture_create_2D( + ibuf->x, ibuf->y, GPU_RGBA16F, ibuf->rect_float, error); GPUTexture *tex = sl->equirectangular_irradiance_gputexture; GPU_texture_bind(tex, 0); GPU_texture_filter_mode(tex, true); @@ -283,67 +331,191 @@ BLI_INLINE void studiolight_evaluate_radiance_buffer( } -static void studiolight_calculate_irradiance(StudioLight *sl, float color[3], const float normal[3]) +BLI_INLINE float studiolight_area_element(float x, float y) { - int hits = 0; - copy_v3_fl(color, 0.0f); + return atan2(x * y, sqrtf(x * x + y * y + 1)); +} - /* back */ - studiolight_evaluate_radiance_buffer(sl->radiance_cubemap_buffers[STUDIOLIGHT_Y_POS], normal, color, &hits, 0, 2, 1, 0.5); - /* front */ - studiolight_evaluate_radiance_buffer(sl->radiance_cubemap_buffers[STUDIOLIGHT_Y_NEG], normal, color, &hits, 0, 2, 1, -0.5); +BLI_INLINE float studiolight_texel_solid_angle(float x, float y, float halfpix) +{ + float v1x = (x - halfpix) * 2.0f - 1.0f; + float v1y = (y - halfpix) * 2.0f - 1.0f; + float v2x = (x + halfpix) * 2.0f - 1.0f; + float v2y = (y + halfpix) * 2.0f - 1.0f; - /* left */ - studiolight_evaluate_radiance_buffer(sl->radiance_cubemap_buffers[STUDIOLIGHT_X_POS], normal, color, &hits, 1, 2, 0, 0.5); - /* right */ - studiolight_evaluate_radiance_buffer(sl->radiance_cubemap_buffers[STUDIOLIGHT_X_NEG], normal, color, &hits, 1, 2, 0, -0.5); + return studiolight_area_element(v1x, v1y) - studiolight_area_element(v1x, v2y) - studiolight_area_element(v2x, v1y) + studiolight_area_element(v2x, v2y); +} - /* top */ - studiolight_evaluate_radiance_buffer(sl->radiance_cubemap_buffers[STUDIOLIGHT_Z_POS], normal, color, &hits, 0, 1, 2, 0.5); - /* bottom */ - studiolight_evaluate_radiance_buffer(sl->radiance_cubemap_buffers[STUDIOLIGHT_Z_NEG], normal, color, &hits, 0, 1, 2, -0.5); +static void studiolight_calculate_cubemap_vector_weight(float normal[3], float *weight, int face, float x, float y) +{ + copy_v3_fl3(normal, x * 2.0f - 1.0f, y * 2.0f - 1.0f, 1.0f); + const float conversion_matrices[6][3][3] = { + { + {0.0f, 0.0f, 1.0f}, + {0.0f, -1.0f, 0.0f}, + {1.0f, 0.0f, 0.0f}, + }, + { + {0.0f, 0.0f, -1.0f}, + {0.0f, -1.0f, 0.0f}, + {-1.0f, 0.0f, 0.0f}, + }, + { + {1.0f, 0.0f, 0.0f}, + {0.0f, 0.0f, -1.0f}, + {0.0f, 1.0f, 0.0f}, + }, + { + {1.0f, 0.0f, 0.0f}, + {0.0f, 0.0f, 1.0f}, + {0.0f, -1.0f, 0.0f}, + }, + { + {1.0f, 0.0f, 0.0f}, + {0.0f, -1.0f, 0.0f}, + {0.0f, 0.0f, -1.0f}, + }, + { + {-1.0f, 0.0f, 0.0f}, + {0.0f, -1.0f, 0.0f}, + {0.0f, 0.0f, 1.0f}, + } + }; - if (hits) { - mul_v3_fl(color, 3.0 / hits); - } - else { - copy_v3_fl3(color, 1.0, 0.0, 1.0); + mul_m3_v3(conversion_matrices[face], normal); + normalize_v3(normal); + const float halfpix = 1.0f / (2.0f * STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE); + *weight = studiolight_texel_solid_angle(x + halfpix, y + halfpix, halfpix); +} + +static void studiolight_calculate_spherical_harmonics_coefficient(StudioLight *sl, int sh_component) +{ + const float M_4PI = M_PI * 4.0f; + + float weight_accum = 0.0f; + float sh[3] = {0.0f, 0.0f, 0.0f}; + for (int face = 0; face < 6; face++) { + float *color; + color = sl->radiance_cubemap_buffers[face]->rect_float; + for (int y = 0; y < STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE; y++) { + float yf = y / (float)STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE; + for (int x = 0; x < STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE; x++) { + float xf = x / (float)STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE; + float weight, coef; + float cubevec[3]; + studiolight_calculate_cubemap_vector_weight(cubevec, &weight, face, xf, yf); + + switch (sh_component) { + case 0: + { + coef = 0.2822095f; + break; + } + + case 1: + { + coef = -0.488603f * cubevec[2] * 2.0f / 3.0f; + break; + } + case 2: + { + coef = 0.488603f * cubevec[1] * 2.0f / 3.0f; + break; + } + case 3: + { + coef = -0.488603f * cubevec[0] * 2.0f / 3.0f; + break; + } + + case 4: + { + coef = 1.092548f * cubevec[0] * cubevec[2] * 1.0f / 4.0f; + break; + } + case 5: + { + coef = -1.092548f * cubevec[2] * cubevec[1] * 1.0f / 4.0f; + break; + } + case 6: + { + coef = 0.315392f * (3.0f * cubevec[2] * cubevec[2] - 1.0f) * 1.0f / 4.0f; + break; + } + case 7: + { + coef = 1.092548f * cubevec[0] * cubevec[1] * 1.0f / 4.0f; + break; + } + case 8: + { + coef = 0.546274f * (cubevec[0] * cubevec[0] - cubevec[2] * cubevec[2]) * 1.0f / 4.0f; + break; + } + + default: + { + coef = 0.0f; + } + } + + madd_v3_v3fl(sh, color, coef * weight); + weight_accum += weight; + color += 4; + } + } } + + mul_v3_fl(sh, M_4PI / weight_accum); + copy_v3_v3(sl->spherical_harmonics_coefs[sh_component], sh); } static void studiolight_calculate_diffuse_light(StudioLight *sl) { /* init light to black */ - copy_v3_fl(sl->diffuse_light[STUDIOLIGHT_X_POS], 0.0f); - copy_v3_fl(sl->diffuse_light[STUDIOLIGHT_X_NEG], 0.0f); - copy_v3_fl(sl->diffuse_light[STUDIOLIGHT_Y_POS], 0.0f); - copy_v3_fl(sl->diffuse_light[STUDIOLIGHT_Y_NEG], 0.0f); - copy_v3_fl(sl->diffuse_light[STUDIOLIGHT_Z_POS], 0.0f); - copy_v3_fl(sl->diffuse_light[STUDIOLIGHT_Z_NEG], 0.0f); - if (sl->flag & STUDIOLIGHT_EXTERNAL_FILE) { - const float normal_x_neg[3] = {-1.0f, 0.0f, 0.0f}; - const float normal_x_pos[3] = { 1.0f, 0.0f, 0.0f}; - const float normal_y_neg[3] = { 0.0f, 1.0f, 0.0f}; - const float normal_y_pos[3] = { 0.0f, -1.0f, 0.0f}; - const float normal_z_neg[3] = { 0.0f, 0.0f, -1.0f}; - const float normal_z_pos[3] = { 0.0f, 0.0f, 1.0f}; - BKE_studiolight_ensure_flag(sl, STUDIOLIGHT_RADIANCE_BUFFERS_CALCULATED); - studiolight_calculate_irradiance(sl, sl->diffuse_light[STUDIOLIGHT_X_POS], normal_x_pos); - studiolight_calculate_irradiance(sl, sl->diffuse_light[STUDIOLIGHT_X_NEG], normal_x_neg); - studiolight_calculate_irradiance(sl, sl->diffuse_light[STUDIOLIGHT_Y_POS], normal_y_pos); - studiolight_calculate_irradiance(sl, sl->diffuse_light[STUDIOLIGHT_Y_NEG], normal_y_neg); - studiolight_calculate_irradiance(sl, sl->diffuse_light[STUDIOLIGHT_Z_POS], normal_z_pos); - studiolight_calculate_irradiance(sl, sl->diffuse_light[STUDIOLIGHT_Z_NEG], normal_z_neg); + for (int comp = 0; comp < STUDIOLIGHT_SPHERICAL_HARMONICS_COMPONENTS; comp ++) { + studiolight_calculate_spherical_harmonics_coefficient(sl, comp); + } + if (sl->flag & STUDIOLIGHT_USER_DEFINED) { + FILE *fp = BLI_fopen(sl->path_sh_cache, "wb"); + if (fp) { + fwrite(sl->spherical_harmonics_coefs, sizeof(sl->spherical_harmonics_coefs), 1, fp); + fclose(fp); + } + } } - sl->flag |= STUDIOLIGHT_DIFFUSE_LIGHT_CALCULATED; + sl->flag |= STUDIOLIGHT_SPHERICAL_HARMONICS_COEFFICIENTS_CALCULATED; +} + +static float area_element(float x, float y ) +{ + return atan2f(x * y, sqrt(x * x + y * y + 1)); +} + +static float texel_coord_solid_angle(float a_U, float a_V, int a_Size) +{ + //scale up to [-1, 1] range (inclusive), offset by 0.5 to point to texel center. + float u = (2.0f * ((float)a_U + 0.5f) / (float)a_Size ) - 1.0f; + float v = (2.0f * ((float)a_V + 0.5f) / (float)a_Size ) - 1.0f; + + float resolution_inv = 1.0f / a_Size; + + // U and V are the -1..1 texture coordinate on the current face. + // Get projected area for this texel + float x0 = u - resolution_inv; + float y0 = v - resolution_inv; + float x1 = u + resolution_inv; + float y1 = v + resolution_inv; + return area_element(x0, y0) - area_element(x0, y1) - area_element(x1, y0) + area_element(x1, y1); } BLI_INLINE void studiolight_evaluate_specular_radiance_buffer( - ImBuf *radiance_buffer, const float specular, const float normal[3], float color[3], int *hits, + ImBuf *radiance_buffer, const float normal[3], float color[3], int xoffset, int yoffset, int zoffset, float zvalue) { if (radiance_buffer == NULL) { @@ -355,13 +527,14 @@ BLI_INLINE void studiolight_evaluate_specular_radiance_buffer( for (int y = 0; y < STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE; y ++) { for (int x = 0; x < STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE; x ++) { // calculate light direction; + float u = (x / (float)STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE) - 0.5f; + float v = (y / (float)STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE) - 0.5f; direction[zoffset] = zvalue; - direction[xoffset] = (x / (float)STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE) - 0.5f; - direction[yoffset] = (y / (float)STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE) - 0.5f; + direction[xoffset] = u; + direction[yoffset] = v; normalize_v3(direction); - angle = pow(fmax(0.0f, dot_v3v3(direction, normal)), specular); + angle = fmax(0.0f, dot_v3v3(direction, normal)) * texel_coord_solid_angle(x, y, STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE); madd_v3_v3fl(color, radiance_color, angle); - (*hits) ++; radiance_color += 4; } } @@ -370,42 +543,73 @@ BLI_INLINE void studiolight_evaluate_specular_radiance_buffer( static void studiolight_calculate_specular_irradiance(StudioLight *sl, float color[3], const float normal[3]) { - const float specular = 4.0f; - int hits = 0; copy_v3_fl(color, 0.0f); /* back */ studiolight_evaluate_specular_radiance_buffer( - sl->radiance_cubemap_buffers[STUDIOLIGHT_Y_POS], specular, normal, color, &hits, 0, 2, 1, 0.5); + sl->radiance_cubemap_buffers[STUDIOLIGHT_Y_POS], normal, color, 0, 2, 1, 0.5); /* front */ studiolight_evaluate_specular_radiance_buffer( - sl->radiance_cubemap_buffers[STUDIOLIGHT_Y_NEG], specular, normal, color, &hits, 0, 2, 1, -0.5); + sl->radiance_cubemap_buffers[STUDIOLIGHT_Y_NEG], normal, color, 0, 2, 1, -0.5); /* left */ studiolight_evaluate_specular_radiance_buffer( - sl->radiance_cubemap_buffers[STUDIOLIGHT_X_POS], specular, normal, color, &hits, 1, 2, 0, 0.5); + sl->radiance_cubemap_buffers[STUDIOLIGHT_X_POS], normal, color, 1, 2, 0, 0.5); /* right */ studiolight_evaluate_specular_radiance_buffer( - sl->radiance_cubemap_buffers[STUDIOLIGHT_X_NEG], specular, normal, color, &hits, 1, 2, 0, -0.5); + sl->radiance_cubemap_buffers[STUDIOLIGHT_X_NEG], normal, color, 1, 2, 0, -0.5); /* top */ studiolight_evaluate_specular_radiance_buffer( - sl->radiance_cubemap_buffers[STUDIOLIGHT_Z_POS], specular, normal, color, &hits, 0, 1, 2, 0.5); + sl->radiance_cubemap_buffers[STUDIOLIGHT_Z_POS], normal, color, 0, 1, 2, 0.5); /* bottom */ studiolight_evaluate_specular_radiance_buffer( - sl->radiance_cubemap_buffers[STUDIOLIGHT_Z_NEG], specular, normal, color, &hits, 0, 1, 2, -0.5); + sl->radiance_cubemap_buffers[STUDIOLIGHT_Z_NEG], normal, color, 0, 1, 2, -0.5); - if (hits) { - mul_v3_fl(color, specular / hits); + mul_v3_fl(color, 1.0 / M_PI); +} + +static bool studiolight_load_irradiance_equirectangular_image(StudioLight *sl) +{ +#ifdef STUDIOLIGHT_LOAD_CACHED_FILES + if (sl->flag & STUDIOLIGHT_EXTERNAL_FILE) { + ImBuf *ibuf = NULL; + ibuf = IMB_loadiffname(sl->path_irr_cache, 0, NULL); + if (ibuf) { + IMB_float_from_rect(ibuf); + sl->equirectangular_irradiance_buffer = ibuf; + sl->flag |= STUDIOLIGHT_EQUIRECTANGULAR_IRRADIANCE_IMAGE_CALCULATED; + return true; + } } - else { - copy_v3_fl3(color, 1.0, 0.0, 1.0); +#endif + return false; +} + +static bool studiolight_load_spherical_harmonics_coefficients(StudioLight *sl) +{ +#ifdef STUDIOLIGHT_LOAD_CACHED_FILES + if (sl->flag & STUDIOLIGHT_EXTERNAL_FILE) { + FILE *fp = BLI_fopen(sl->path_sh_cache, "rb"); + if (fp) { + if (fread((void*)(sl->spherical_harmonics_coefs), sizeof(sl->spherical_harmonics_coefs), 1, fp)) + { + sl->flag |= STUDIOLIGHT_SPHERICAL_HARMONICS_COEFFICIENTS_CALCULATED; + fclose(fp); + return true; + } + fclose(fp); + } } +#endif + return false; } static void studiolight_calculate_irradiance_equirectangular_image(StudioLight *sl) { if (sl->flag & STUDIOLIGHT_EXTERNAL_FILE) { + /* check for cached irr file */ + BKE_studiolight_ensure_flag(sl, STUDIOLIGHT_RADIANCE_BUFFERS_CALCULATED); float *colbuf = MEM_mallocN(STUDIOLIGHT_IRRADIANCE_EQUIRECTANGULAR_WIDTH * STUDIOLIGHT_IRRADIANCE_EQUIRECTANGULAR_HEIGHT * sizeof(float[4]), __func__); @@ -427,10 +631,10 @@ static void studiolight_calculate_irradiance_equirectangular_image(StudioLight * STUDIOLIGHT_IRRADIANCE_EQUIRECTANGULAR_WIDTH, STUDIOLIGHT_IRRADIANCE_EQUIRECTANGULAR_HEIGHT); MEM_freeN(colbuf); -#if 0 - IMB_saveiff(sl->equirectangular_irradiance_buffer, "/tmp/studiolight_specular_irradiance.png", IB_rectfloat); -#endif + if (sl->flag & STUDIOLIGHT_USER_DEFINED) { + IMB_saveiff(sl->equirectangular_irradiance_buffer, sl->path_irr_cache, IB_rectfloat); + } } sl->flag |= STUDIOLIGHT_EQUIRECTANGULAR_IRRADIANCE_IMAGE_CALCULATED; } @@ -481,11 +685,12 @@ static void studiolight_add_files_from_datafolder(const int folder_id, const cha if ((dir[i].type & S_IFREG)) { const char *filename = dir[i].relname; const char *path = dir[i].path; - if (BLI_testextensie_array(filename, imb_ext_image)) { - sl = studiolight_create(); - sl->flag = STUDIOLIGHT_EXTERNAL_FILE | flag; + if (BLI_path_extension_check_array(filename, imb_ext_image)) { + sl = studiolight_create(STUDIOLIGHT_EXTERNAL_FILE | flag); BLI_strncpy(sl->name, filename, FILE_MAXFILE); BLI_strncpy(sl->path, path, FILE_MAXFILE); + sl->path_irr_cache = BLI_string_joinN(path, ".irr"); + sl->path_sh_cache = BLI_string_joinN(path, ".sh2"); BLI_addtail(&studiolights, sl); } } @@ -493,7 +698,6 @@ static void studiolight_add_files_from_datafolder(const int folder_id, const cha BLI_filelist_free(dir, totfile); dir = NULL; } - } static int studiolight_flag_cmp_order(const StudioLight *sl) @@ -525,187 +729,149 @@ static int studiolight_cmp(const void *a, const void *b) } /* icons */ -static uint *studiolight_radiance_preview(StudioLight *sl, int icon_size) + +/* Takes normalized uvs as parameter (range from 0 to 1). + * inner_edge and outer_edge are distances (from the center) + * in uv space for the alpha mask falloff. */ +static uint alpha_circle_mask(float u, float v, float inner_edge, float outer_edge) +{ + /* Coords from center. */ + float co[2] = {u - 0.5f, v - 0.5f}; + float dist = len_v2(co); + float alpha = 1.0f + (inner_edge - dist) / (outer_edge - inner_edge); + uint mask = (uint)floorf(255.0f * min_ff(max_ff(alpha, 0.0f), 1.0f)); + return mask << 24; +} + +#define STUDIOLIGHT_DIAMETER 0.95f + +static void studiolight_radiance_preview(uint* icon_buffer, StudioLight *sl) { BKE_studiolight_ensure_flag(sl, STUDIOLIGHT_EXTERNAL_IMAGE_LOADED); - uint *rect = MEM_mallocN(icon_size * icon_size * sizeof(uint), __func__); - int icon_center = icon_size / 2; - float sphere_radius = icon_center * 0.9; + float pixel_size = 1.0f / (float)STUDIOLIGHT_ICON_SIZE; int offset = 0; - for (int y = 0; y < icon_size; y++) { - float dy = y - icon_center; - for (int x = 0; x < icon_size; x++) { - float dx = x - icon_center; - /* calculate aliasing */ - float alias = 0; - const float alias_step = 0.333; - for (float ay = dy - 0.5; ay < dy + 0.5; ay += alias_step) { - for (float ax = dx - 0.5; ax < dx + 0.5; ax += alias_step) { - if (sqrt(ay * ay + ax * ax) < sphere_radius) { - alias += alias_step * alias_step; - } - } - } + for (int y = 0; y < STUDIOLIGHT_ICON_SIZE; y++) { + float dy = (y + 0.5f) / (float)STUDIOLIGHT_ICON_SIZE; + dy = dy / STUDIOLIGHT_DIAMETER - (1.0f - STUDIOLIGHT_DIAMETER) / 2.0f; + for (int x = 0; x < STUDIOLIGHT_ICON_SIZE; x++) { + float dx = (x + 0.5f) / (float)STUDIOLIGHT_ICON_SIZE; + dx = dx / STUDIOLIGHT_DIAMETER - (1.0f - STUDIOLIGHT_DIAMETER) / 2.0f; + uint pixelresult = 0x0; - uint alias_i = clamp_i(alias * 256, 0, 255); - if (alias_i != 0) { - /* calculate normal */ - uint alias_mask = alias_i << 24; - float incoming[3]; - copy_v3_fl3(incoming, 0.0, 1.0, 0.0); + uint alphamask = alpha_circle_mask(dx, dy, 0.5f - pixel_size, 0.5f); + if (alphamask != 0) { + float incoming[3] = {0.0f, 0.0f, -1.0f}; float normal[3]; - normal[0] = dx / sphere_radius; - normal[2] = dy / sphere_radius; - normal[1] = -sqrt(-(normal[0] * normal[0]) - (normal[2] * normal[2]) + 1); - normalize_v3(normal); + normal[0] = dx * 2.0f - 1.0f; + normal[1] = dy * 2.0f - 1.0f; + float dist = len_v2(normal); + normal[2] = sqrtf(1.0f - SQUARE(dist)); float direction[3]; reflect_v3_v3v3(direction, incoming, normal); + /* We want to see horizon not poles. */ + SWAP(float, direction[1], direction[2]); + direction[1] = -direction[1]; + float color[4]; studiolight_calculate_radiance(sl->equirectangular_radiance_buffer, color, direction); pixelresult = rgb_to_cpack( linearrgb_to_srgb(color[0]), linearrgb_to_srgb(color[1]), - linearrgb_to_srgb(color[2])) | alias_mask; + linearrgb_to_srgb(color[2])) | alphamask; } - rect[offset++] = pixelresult; + icon_buffer[offset++] = pixelresult; } } - return rect; } -static uint *studiolight_matcap_preview(StudioLight *sl, int icon_size) +static void studiolight_matcap_preview(uint* icon_buffer, StudioLight *sl, bool flipped) { BKE_studiolight_ensure_flag(sl, STUDIOLIGHT_EXTERNAL_IMAGE_LOADED); - uint *rect = MEM_mallocN(icon_size * icon_size * sizeof(uint), __func__); - const uint alphamask = 0xff000000; float color[4]; float fx, fy; + float pixel_size = 1.0f / (float)STUDIOLIGHT_ICON_SIZE; int offset = 0; ImBuf *ibuf = sl->equirectangular_radiance_buffer; - for (int y = 0; y < icon_size; y++) { - for (int x = 0; x < icon_size; x++) { - fx = x * ibuf->x / icon_size; - fy = y * ibuf->y / icon_size; - nearest_interpolation_color(ibuf, NULL, color, fx, fy); - rect[offset++] = rgb_to_cpack(linearrgb_to_srgb(color[0]), - linearrgb_to_srgb(color[1]), - linearrgb_to_srgb(color[2])) | alphamask; + + for (int y = 0; y < STUDIOLIGHT_ICON_SIZE; y++) { + fy = (y + 0.5f) / (float)STUDIOLIGHT_ICON_SIZE; + fy = fy / STUDIOLIGHT_DIAMETER - (1.0f - STUDIOLIGHT_DIAMETER) / 2.0f; + for (int x = 0; x < STUDIOLIGHT_ICON_SIZE; x++) { + fx = (x + 0.5f) / (float)STUDIOLIGHT_ICON_SIZE; + fx = fx / STUDIOLIGHT_DIAMETER - (1.0f - STUDIOLIGHT_DIAMETER) / 2.0f; + if (flipped) { + fx = 1.0f - fx; + } + nearest_interpolation_color(ibuf, NULL, color, fx * ibuf->x, fy * ibuf->y); + + uint alphamask = alpha_circle_mask(fx, fy, 0.5f - pixel_size, 0.5f); + + icon_buffer[offset++] = rgb_to_cpack( + linearrgb_to_srgb(color[0]), + linearrgb_to_srgb(color[1]), + linearrgb_to_srgb(color[2])) | alphamask; } } - return rect; } -static uint *studiolight_irradiance_preview(StudioLight *sl, int icon_size) +static void studiolight_irradiance_preview(uint* icon_buffer, StudioLight *sl) { - if (/*!(sl->flag & STUDIOLIGHT_EXTERNAL_FILE)*/ 1) { + BKE_studiolight_ensure_flag(sl, STUDIOLIGHT_SPHERICAL_HARMONICS_COEFFICIENTS_CALCULATED); - BKE_studiolight_ensure_flag(sl, STUDIOLIGHT_DIFFUSE_LIGHT_CALCULATED); + float pixel_size = 1.0f / (float)STUDIOLIGHT_ICON_SIZE; - uint *rect = MEM_mallocN(icon_size * icon_size * sizeof(uint), __func__); - int icon_center = icon_size / 2; - float sphere_radius = icon_center * 0.9; + int offset = 0; + for (int y = 0; y < STUDIOLIGHT_ICON_SIZE; y++) { + float dy = (y + 0.5f) / (float)STUDIOLIGHT_ICON_SIZE; + dy = dy / STUDIOLIGHT_DIAMETER - (1.0f - STUDIOLIGHT_DIAMETER) / 2.0f; + for (int x = 0; x < STUDIOLIGHT_ICON_SIZE; x++) { + float dx = (x + 0.5f) / (float)STUDIOLIGHT_ICON_SIZE; + dx = dx / STUDIOLIGHT_DIAMETER - (1.0f - STUDIOLIGHT_DIAMETER) / 2.0f; - int offset = 0; - for (int y = 0; y < icon_size; y++) { - float dy = y - icon_center; - for (int x = 0; x < icon_size; x++) { - float dx = x - icon_center; - /* calculate aliasing */ - float alias = 0; - const float alias_step = 0.333; - for (float ay = dy - 0.5; ay < dy + 0.5; ay += alias_step) { - for (float ax = dx - 0.5; ax < dx + 0.5; ax += alias_step) { - if (sqrt(ay * ay + ax * ax) < sphere_radius) { - alias += alias_step * alias_step; - } - } - } - uint pixelresult = 0x0; - uint alias_i = clamp_i(alias * 256, 0, 255); - if (alias_i != 0) { - /* calculate normal */ - uint alias_mask = alias_i << 24; - float normal[3]; - normal[0] = dx / sphere_radius; - normal[1] = dy / sphere_radius; - normal[2] = sqrt(-(normal[0] * normal[0]) - (normal[1] * normal[1]) + 1); - normalize_v3(normal); - - float color[3]; - mul_v3_v3fl(color, sl->diffuse_light[STUDIOLIGHT_X_POS], clamp_f(normal[0], 0.0, 1.0)); - interp_v3_v3v3(color, color, sl->diffuse_light[STUDIOLIGHT_X_NEG], clamp_f(-normal[0], 0.0, 1.0)); - interp_v3_v3v3(color, color, sl->diffuse_light[STUDIOLIGHT_Z_POS], clamp_f(normal[1], 0.0, 1.0)); - interp_v3_v3v3(color, color, sl->diffuse_light[STUDIOLIGHT_Z_NEG], clamp_f(-normal[1], 0.0, 1.0)); - interp_v3_v3v3(color, color, sl->diffuse_light[STUDIOLIGHT_Y_POS], clamp_f(normal[2], 0.0, 1.0)); - - pixelresult = rgb_to_cpack( - linearrgb_to_srgb(color[0]), - linearrgb_to_srgb(color[1]), - linearrgb_to_srgb(color[2])) | alias_mask; - } - rect[offset++] = pixelresult; - } - } - return rect; - } - else { - BKE_studiolight_ensure_flag(sl, STUDIOLIGHT_EQUIRECTANGULAR_IRRADIANCE_IMAGE_CALCULATED); + uint pixelresult = 0x0; + uint alphamask = alpha_circle_mask(dx, dy, 0.5f - pixel_size, 0.5f); + if (alphamask != 0) { + /* calculate normal */ + float normal[3]; + normal[0] = dx * 2.0f - 1.0f; + normal[1] = -(dy * 2.0f - 1.0f); + float dist = len_v2(normal); + normal[2] = -sqrtf(1.0f - SQUARE(dist)); + SWAP(float, normal[1], normal[2]); + + float color[3] = {0.0f, 0.0f, 0.0f}; + /* Spherical Harmonics L0 */ + madd_v3_v3fl(color, sl->spherical_harmonics_coefs[0], 0.282095f); + +#if STUDIOLIGHT_SPHERICAL_HARMONICS_LEVEL > 0 + /* Spherical Harmonics L1 */ + madd_v3_v3fl(color, sl->spherical_harmonics_coefs[1], -0.488603f * normal[2]); + madd_v3_v3fl(color, sl->spherical_harmonics_coefs[2], 0.488603f * normal[1]); + madd_v3_v3fl(color, sl->spherical_harmonics_coefs[3], -0.488603f * normal[0]); +#endif - uint *rect = MEM_mallocN(icon_size * icon_size * sizeof(uint), __func__); - int icon_center = icon_size / 2; - float sphere_radius = icon_center * 0.9; - - int offset = 0; - for (int y = 0; y < icon_size; y++) { - float dy = y - icon_center; - for (int x = 0; x < icon_size; x++) { - float dx = x - icon_center; - /* calculate aliasing */ - float alias = 0; - const float alias_step = 0.333; - for (float ay = dy - 0.5; ay < dy + 0.5; ay += alias_step) { - for (float ax = dx - 0.5; ax < dx + 0.5; ax += alias_step) { - if (sqrt(ay * ay + ax * ax) < sphere_radius) { - alias += alias_step * alias_step; - } - } - } - uint pixelresult = 0x0; - uint alias_i = clamp_i(alias * 256, 0, 255); - if (alias_i != 0) { - /* calculate normal */ - uint alias_mask = alias_i << 24; - float incoming[3]; - copy_v3_fl3(incoming, 0.0, 1.0, 0.0); - - float normal[3]; - normal[0] = dx / sphere_radius; - normal[2] = dy / sphere_radius; - normal[1] = -sqrt(-(normal[0] * normal[0]) - (normal[2] * normal[2]) + 1); - normalize_v3(normal); - - float direction[3]; - reflect_v3_v3v3(direction, incoming, normal); - - float color[4]; - studiolight_calculate_radiance(sl->equirectangular_irradiance_buffer, color, direction); - - pixelresult = rgb_to_cpack( - linearrgb_to_srgb(color[0]), - linearrgb_to_srgb(color[1]), - linearrgb_to_srgb(color[2])) | alias_mask; - } - rect[offset++] = pixelresult; +#if STUDIOLIGHT_SPHERICAL_HARMONICS_LEVEL > 1 + /* Spherical Harmonics L1 */ + madd_v3_v3fl(color, sl->spherical_harmonics_coefs[4], 1.092548f * normal[0] * normal[2]); + madd_v3_v3fl(color, sl->spherical_harmonics_coefs[5], -1.092548f * normal[2] * normal[1]); + madd_v3_v3fl(color, sl->spherical_harmonics_coefs[6], 0.315392f * (3.0f * normal[1] * normal[1] - 1.0f)); + madd_v3_v3fl(color, sl->spherical_harmonics_coefs[7], -1.092548 * normal[0] * normal[1]); + madd_v3_v3fl(color, sl->spherical_harmonics_coefs[8], 0.546274 * (normal[0] * normal[0] - normal[2] * normal[2])); +#endif + pixelresult = rgb_to_cpack( + linearrgb_to_srgb(color[0]), + linearrgb_to_srgb(color[1]), + linearrgb_to_srgb(color[2])) | alphamask; } + icon_buffer[offset++] = pixelresult; } - return rect; } } @@ -717,15 +883,24 @@ void BKE_studiolight_init(void) /* order studio lights by name */ /* Also reserve icon space for it. */ /* Add default studio light */ - sl = studiolight_create(); - BLI_strncpy(sl->name, "INTERNAL_01", FILE_MAXFILE); - sl->flag = STUDIOLIGHT_INTERNAL | STUDIOLIGHT_DIFFUSE_LIGHT_CALCULATED | STUDIOLIGHT_ORIENTATION_CAMERA; - copy_v3_fl(sl->diffuse_light[STUDIOLIGHT_X_POS], 0.0f); - copy_v3_fl(sl->diffuse_light[STUDIOLIGHT_X_NEG], 0.0f); - copy_v3_fl(sl->diffuse_light[STUDIOLIGHT_Y_POS], 0.8f); - copy_v3_fl(sl->diffuse_light[STUDIOLIGHT_Y_NEG], 0.05f); - copy_v3_fl(sl->diffuse_light[STUDIOLIGHT_Z_POS], 0.2f); - copy_v3_fl(sl->diffuse_light[STUDIOLIGHT_Z_NEG], 0.1f); + sl = studiolight_create(STUDIOLIGHT_INTERNAL | STUDIOLIGHT_SPHERICAL_HARMONICS_COEFFICIENTS_CALCULATED | STUDIOLIGHT_ORIENTATION_CAMERA); + BLI_strncpy(sl->name, "Default", FILE_MAXFILE); + + + copy_v3_fl3(sl->spherical_harmonics_coefs[0], 1.03271556f, 1.07163882f, 1.11193657f); +#if STUDIOLIGHT_SPHERICAL_HARMONICS_LEVEL > 0 + copy_v3_fl3(sl->spherical_harmonics_coefs[1], -0.00480952f, 0.05290511f, 0.16394117f); + copy_v3_fl3(sl->spherical_harmonics_coefs[2], -0.29686999f, -0.27378261f, -0.24797194f); + copy_v3_fl3(sl->spherical_harmonics_coefs[3], 0.47932500f, 0.48242140f, 0.47190312f); +#endif +#if STUDIOLIGHT_SPHERICAL_HARMONICS_LEVEL > 1 + copy_v3_fl3(sl->spherical_harmonics_coefs[4], -0.00576984f, 0.00504886f, 0.01640534f); + copy_v3_fl3(sl->spherical_harmonics_coefs[5], 0.15500379f, 0.15415503f, 0.16244425f); + copy_v3_fl3(sl->spherical_harmonics_coefs[6], -0.02483751f, -0.02245096f, -0.00536885f); + copy_v3_fl3(sl->spherical_harmonics_coefs[7], 0.11155496f, 0.11005443f, 0.10839636f); + copy_v3_fl3(sl->spherical_harmonics_coefs[8], 0.01363425f, 0.01278363f, -0.00159006f); +#endif + BLI_addtail(&studiolights, sl); studiolight_add_files_from_datafolder(BLENDER_SYSTEM_DATAFILES, STUDIOLIGHT_CAMERA_FOLDER, STUDIOLIGHT_ORIENTATION_CAMERA); @@ -790,21 +965,34 @@ struct ListBase *BKE_studiolight_listbase(void) return &studiolights; } -uint *BKE_studiolight_preview(StudioLight *sl, int icon_size, int icon_id_type) +void BKE_studiolight_preview(uint* icon_buffer, StudioLight *sl, int icon_id_type) { - if (icon_id_type == STUDIOLIGHT_ICON_ID_TYPE_IRRADIANCE) { - if (sl->flag & STUDIOLIGHT_ORIENTATION_VIEWNORMAL) { - return studiolight_matcap_preview(sl, icon_size); + switch (icon_id_type) { + case STUDIOLIGHT_ICON_ID_TYPE_RADIANCE: + default: + { + studiolight_radiance_preview(icon_buffer, sl); + break; } - else { - return studiolight_irradiance_preview(sl, icon_size); + case STUDIOLIGHT_ICON_ID_TYPE_IRRADIANCE: + { + studiolight_irradiance_preview(icon_buffer, sl); + break; + } + case STUDIOLIGHT_ICON_ID_TYPE_MATCAP: + { + studiolight_matcap_preview(icon_buffer, sl, false); + break; + } + case STUDIOLIGHT_ICON_ID_TYPE_MATCAP_FLIPPED: + { + studiolight_matcap_preview(icon_buffer, sl, true); + break; } - } - else { - return studiolight_radiance_preview(sl, icon_size); } } +/* Ensure state of Studiolights */ void BKE_studiolight_ensure_flag(StudioLight *sl, int flag) { if ((sl->flag & flag) == flag) { @@ -812,25 +1000,29 @@ void BKE_studiolight_ensure_flag(StudioLight *sl, int flag) } if ((flag & STUDIOLIGHT_EXTERNAL_IMAGE_LOADED)) { - studiolight_load_equierectangular_image(sl); + studiolight_load_equirectangular_image(sl); } if ((flag & STUDIOLIGHT_RADIANCE_BUFFERS_CALCULATED)) { studiolight_calculate_radiance_cubemap_buffers(sl); } - if ((flag & STUDIOLIGHT_DIFFUSE_LIGHT_CALCULATED)) { - studiolight_calculate_diffuse_light(sl); + if ((flag & STUDIOLIGHT_SPHERICAL_HARMONICS_COEFFICIENTS_CALCULATED)) { + if (!studiolight_load_spherical_harmonics_coefficients(sl)) { + studiolight_calculate_diffuse_light(sl); + } } if ((flag & STUDIOLIGHT_EQUIRECTANGULAR_RADIANCE_GPUTEXTURE)) { - studiolight_create_equierectangular_radiance_gputexture(sl); + studiolight_create_equirectangular_radiance_gputexture(sl); } if ((flag & STUDIOLIGHT_LIGHT_DIRECTION_CALCULATED)) { studiolight_calculate_light_direction(sl); } if ((flag & STUDIOLIGHT_EQUIRECTANGULAR_IRRADIANCE_GPUTEXTURE)) { - studiolight_create_equierectangular_irradiance_gputexture(sl); + studiolight_create_equirectangular_irradiance_gputexture(sl); } if ((flag & STUDIOLIGHT_EQUIRECTANGULAR_IRRADIANCE_IMAGE_CALCULATED)) { - studiolight_calculate_irradiance_equirectangular_image(sl); + if (!studiolight_load_irradiance_equirectangular_image(sl)) { + studiolight_calculate_irradiance_equirectangular_image(sl); + } } } @@ -839,3 +1031,26 @@ void BKE_studiolight_refresh(void) BKE_studiolight_free(); BKE_studiolight_init(); } + +void BKE_studiolight_set_free_function(StudioLight *sl, StudioLightFreeFunction *free_function, void *data) +{ + sl->free_function = free_function; + sl->free_function_data = data; +} + +void BKE_studiolight_unset_icon_id(StudioLight *sl, int icon_id) +{ + BLI_assert(sl != NULL); + if (sl->icon_id_radiance == icon_id) { + sl->icon_id_radiance = 0; + } + if (sl->icon_id_irradiance == icon_id) { + sl->icon_id_irradiance = 0; + } + if (sl->icon_id_matcap == icon_id) { + sl->icon_id_matcap = 0; + } + if (sl->icon_id_matcap_flipped == icon_id) { + sl->icon_id_matcap_flipped = 0; + } +} diff --git a/source/blender/blenkernel/intern/subsurf_ccg.c b/source/blender/blenkernel/intern/subsurf_ccg.c index d735944c93d..e4f08703dfc 100644 --- a/source/blender/blenkernel/intern/subsurf_ccg.c +++ b/source/blender/blenkernel/intern/subsurf_ccg.c @@ -197,7 +197,7 @@ static CCGSubSurf *_getSubSurf(CCGSubSurf *prevSS, int subdivLevels, /* mask is allocated after regular layers */ ccgSubSurf_setAllocMask(ccgSS, 1, sizeof(float) * numLayers); } - + if (flags & CCG_CALC_NORMALS) ccgSubSurf_setCalcVertexNormals(ccgSS, 1, normalOffset); else @@ -315,7 +315,7 @@ static int ss_sync_from_uv(CCGSubSurf *ss, CCGSubSurf *origss, DerivedMesh *dm, vmap = BKE_mesh_uv_vert_map_create(mpoly, mloop, mloopuv, totface, totvert, limit, false, true); if (!vmap) return 0; - + ccgSubSurf_initFullSync(ss); /* create vertices */ @@ -613,12 +613,12 @@ static float *get_ss_weights(WeightTable *wtable, int gridCuts, int faceLen) if (wtable->len <= faceLen) { void *tmp = MEM_callocN(sizeof(FaceVertWeightEntry) * (faceLen + 1), "weight table alloc 2"); - + if (wtable->len) { memcpy(tmp, wtable->weight_table, sizeof(FaceVertWeightEntry) * wtable->len); MEM_freeN(wtable->weight_table); } - + wtable->weight_table = tmp; wtable->len = faceLen + 1; } @@ -633,7 +633,7 @@ static float *get_ss_weights(WeightTable *wtable, int gridCuts, int faceLen) for (y = 0; y < gridCuts + 2; y++) { fx = 0.5f - (float)x / (float)(gridCuts + 1) / 2.0f; fy = 0.5f - (float)y / (float)(gridCuts + 1) / 2.0f; - + fac2 = faceLen - 4; w1 = (1.0f - fx) * (1.0f - fy) + (-fac2 * fx * fy * fac); w2 = (1.0f - fx + fac2 * fx * -fac) * (fy); @@ -647,7 +647,7 @@ static float *get_ss_weights(WeightTable *wtable, int gridCuts, int faceLen) w[j] = fac2; } } - + w[i] = w1; w[(i - 1 + faceLen) % faceLen] = w2; w[(i + 1) % faceLen] = w4; @@ -669,7 +669,7 @@ static void free_ss_weights(WeightTable *wtable) if (wtable->weight_table[i].valid) MEM_freeN(wtable->weight_table[i].w); } - + if (wtable->weight_table) MEM_freeN(wtable->weight_table); } @@ -1100,7 +1100,7 @@ static void ccgDM_getFinalEdge(DerivedMesh *dm, int edgeNum, MEdge *med) /* numVerts = ccgSubSurf_getFaceNumVerts(f); */ /*UNUSED*/ gridSideEdges = gridSize - 1; - gridInternalEdges = (gridSideEdges - 1) * gridSideEdges * 2; + gridInternalEdges = (gridSideEdges - 1) * gridSideEdges * 2; offset = edgeNum - ccgdm->faceMap[i].startEdge; grid = offset / (gridSideEdges + gridInternalEdges); @@ -1214,7 +1214,7 @@ void subsurf_copy_grid_hidden(DerivedMesh *dm, const MPoly *mpoly, int edgeSize = ccgSubSurf_getEdgeSize(ss); int totface = ccgSubSurf_getNumFaces(ss); int i, j, x, y; - + for (i = 0; i < totface; i++) { CCGFace *f = ccgdm->faceMap[i].face; @@ -1223,14 +1223,14 @@ void subsurf_copy_grid_hidden(DerivedMesh *dm, const MPoly *mpoly, int hidden_gridsize = BKE_ccg_gridsize(md->level); int factor = BKE_ccg_factor(level, md->level); BLI_bitmap *hidden = md->hidden; - + if (!hidden) continue; - + for (y = 0; y < gridSize; y++) { for (x = 0; x < gridSize; x++) { int vndx, offset; - + vndx = getFaceIndex(ss, f, j, x, y, edgeSize, gridSize); offset = (y * factor) * hidden_gridsize + (x * factor); if (BLI_BITMAP_TEST(hidden, offset)) @@ -1254,11 +1254,11 @@ void subsurf_copy_grid_paint_mask(DerivedMesh *dm, const MPoly *mpoly, int edgeSize = ccgSubSurf_getEdgeSize(ss); int totface = ccgSubSurf_getNumFaces(ss); int i, j, x, y, factor, gpm_gridsize; - + for (i = 0; i < totface; i++) { CCGFace *f = ccgdm->faceMap[i].face; const MPoly *p = &mpoly[i]; - + for (j = 0; j < p->totloop; j++) { const GridPaintMask *gpm = &grid_paint_mask[p->loopstart + j]; if (!gpm->data) @@ -1266,11 +1266,11 @@ void subsurf_copy_grid_paint_mask(DerivedMesh *dm, const MPoly *mpoly, factor = BKE_ccg_factor(level, gpm->level); gpm_gridsize = BKE_ccg_gridsize(gpm->level); - + for (y = 0; y < gridSize; y++) { for (x = 0; x < gridSize; x++) { int vndx, offset; - + vndx = getFaceIndex(ss, f, j, x, y, edgeSize, gridSize); offset = y * factor * gpm_gridsize + x * factor; paint_mask[vndx] = gpm->data[offset]; @@ -1309,7 +1309,7 @@ static void ccgDM_copyFinalVertArray(DerivedMesh *dm, MVert *mvert) vd = ccgSubSurf_getFaceCenterData(f); ccgDM_to_MVert(&mvert[i++], &key, vd); - + for (S = 0; S < numVerts; S++) { for (x = 1; x < gridSize - 1; x++) { vd = ccgSubSurf_getFaceGridEdgeData(ss, f, S, x); @@ -1626,7 +1626,7 @@ static void ccgdm_getVertCos(DerivedMesh *dm, float (*cos)[3]) CCGEdge **edgeMap2; CCGVert **vertMap2; int index, totvert, totedge, totface; - + totvert = ccgSubSurf_getNumVerts(ss); vertMap2 = MEM_mallocN(totvert * sizeof(*vertMap2), "vertmap"); for (ccgSubSurf_initVertIterator(ss, &vi); !ccgVertIterator_isStopped(&vi); ccgVertIterator_next(&vi)) { @@ -1657,7 +1657,7 @@ static void ccgdm_getVertCos(DerivedMesh *dm, float (*cos)[3]) int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(f); copy_v3_v3(cos[i++], ccgSubSurf_getFaceCenterData(f)); - + for (S = 0; S < numVerts; S++) { for (x = 1; x < gridSize - 1; x++) { copy_v3_v3(cos[i++], ccgSubSurf_getFaceGridEdgeData(ss, f, S, x)); @@ -1824,7 +1824,7 @@ static void ccgDM_release(DerivedMesh *dm) { ccgdm->multires.mmd = NULL; } - + if (ccgdm->multires.mmd) { if (ccgdm->multires.modified_flags & MULTIRES_COORDS_MODIFIED) multires_modifier_update_mdisps(dm); @@ -2117,7 +2117,7 @@ static void ccgdm_create_grids(DerivedMesh *dm) if (ccgdm->gridData) return; - + numGrids = ccgDM_getNumGrids(dm); numFaces = ccgSubSurf_getNumFaces(ss); /*gridSize = ccgDM_getGridSize(dm);*/ /*UNUSED*/ @@ -2183,7 +2183,7 @@ static void ccgDM_getGridKey(DerivedMesh *dm, CCGKey *key) static DMFlagMat *ccgDM_getGridFlagMats(DerivedMesh *dm) { CCGDerivedMesh *ccgdm = (CCGDerivedMesh *)dm; - + ccgdm_create_grids(dm); return ccgdm->gridFlagMats; } @@ -2191,7 +2191,7 @@ static DMFlagMat *ccgDM_getGridFlagMats(DerivedMesh *dm) static BLI_bitmap **ccgDM_getGridHidden(DerivedMesh *dm) { CCGDerivedMesh *ccgdm = (CCGDerivedMesh *)dm; - + ccgdm_create_grids(dm); return ccgdm->gridHidden; } @@ -2968,7 +2968,7 @@ struct DerivedMesh *subsurf_make_derived_from_derived( if (levels == 0) return dm; - + ss = _getSubSurf(NULL, levels, 3, useSimple | CCG_USE_ARENA | CCG_CALC_NORMALS); ss_sync_from_derivedmesh(ss, dm, vertCos, useSimple, useSubsurfUv); @@ -3061,9 +3061,9 @@ struct DerivedMesh *subsurf_make_derived_from_derived( void subsurf_calculate_limit_positions(Mesh *me, float (*r_positions)[3]) { - /* Finds the subsurf limit positions for the verts in a mesh - * and puts them in an array of floats. Please note that the - * calculated vert positions is incorrect for the verts + /* Finds the subsurf limit positions for the verts in a mesh + * and puts them in an array of floats. Please note that the + * calculated vert positions is incorrect for the verts * on the boundary of the mesh. */ CCGSubSurf *ss = _getSubSurf(NULL, 1, 3, CCG_USE_ARENA); diff --git a/source/blender/blenkernel/intern/suggestions.c b/source/blender/blenkernel/intern/suggestions.c index b74143b5c07..043fc813b95 100644 --- a/source/blender/blenkernel/intern/suggestions.c +++ b/source/blender/blenkernel/intern/suggestions.c @@ -164,7 +164,7 @@ void texttool_suggest_prefix(const char *prefix, const int prefix_len) suggestions.lastmatch = suggestions.last; return; } - + first = last = NULL; for (match = suggestions.first; match; match = match->next) { cmp = BLI_strncasecmp(prefix, match->name, prefix_len); diff --git a/source/blender/blenkernel/intern/text.c b/source/blender/blenkernel/intern/text.c index 226ab33e45e..f876592c0a8 100644 --- a/source/blender/blenkernel/intern/text.c +++ b/source/blender/blenkernel/intern/text.c @@ -229,15 +229,15 @@ void BKE_text_init(Text *ta) tmp = (TextLine *) MEM_mallocN(sizeof(TextLine), "textline"); tmp->line = (char *) MEM_mallocN(1, "textline_string"); tmp->format = NULL; - + tmp->line[0] = 0; tmp->len = 0; - + tmp->next = NULL; tmp->prev = NULL; - + BLI_addhead(&ta->lines, tmp); - + ta->curl = ta->lines.first; ta->curc = 0; ta->sell = ta->lines.first; @@ -270,18 +270,18 @@ int txt_extended_ascii_as_utf8(char **str) added++; i += bad_char + 1; } - + if (added != 0) { char *newstr = MEM_mallocN(length + added + 1, "text_line"); ptrdiff_t mi = 0; i = 0; - + while ((*str)[i]) { if ((bad_char = BLI_utf8_invalid_byte((*str) + i, length - i)) == -1) { memcpy(newstr + mi, (*str) + i, length - i + 1); break; } - + memcpy(newstr + mi, (*str) + i, bad_char); BLI_str_utf8_from_unicode((*str)[i + bad_char], newstr + mi + bad_char); @@ -292,7 +292,7 @@ int txt_extended_ascii_as_utf8(char **str) MEM_freeN(*str); *str = newstr; } - + return added; } @@ -389,7 +389,7 @@ bool BKE_text_reload(Text *text) BLI_strncpy(filepath_abs, text->name, FILE_MAX); BLI_path_abs(filepath_abs, BKE_main_blendfile_path_from_global()); - + buffer = BLI_file_read_text_as_mem(filepath_abs, 0, &buffer_len); if (buffer == NULL) { return false; @@ -424,7 +424,7 @@ Text *BKE_text_load_ex(Main *bmain, const char *file, const char *relpath, const BLI_strncpy(filepath_abs, file, FILE_MAX); if (relpath) /* can be NULL (bg mode) */ BLI_path_abs(filepath_abs, relpath); - + buffer = BLI_file_read_text_as_mem(filepath_abs, 0, &buffer_len); if (buffer == NULL) { return false; @@ -454,9 +454,9 @@ Text *BKE_text_load_ex(Main *bmain, const char *file, const char *relpath, const else { ta->mtime = 0; } - + text_from_buf(ta, buffer, buffer_len); - + MEM_freeN(buffer); return ta; @@ -605,7 +605,7 @@ static void make_new_line(TextLine *line, char *newline) { if (line->line) MEM_freeN(line->line); if (line->format) MEM_freeN(line->format); - + line->line = newline; line->len = strlen(newline); line->format = NULL; @@ -616,16 +616,16 @@ static TextLine *txt_new_line(const char *str) TextLine *tmp; if (!str) str = ""; - + tmp = (TextLine *) MEM_mallocN(sizeof(TextLine), "textline"); tmp->line = MEM_mallocN(strlen(str) + 1, "textline_string"); tmp->format = NULL; - + strcpy(tmp->line, str); - + tmp->len = strlen(str); tmp->next = tmp->prev = NULL; - + return tmp; } @@ -636,29 +636,29 @@ static TextLine *txt_new_linen(const char *str, int n) tmp = (TextLine *) MEM_mallocN(sizeof(TextLine), "textline"); tmp->line = MEM_mallocN(n + 1, "textline_string"); tmp->format = NULL; - + BLI_strncpy(tmp->line, (str) ? str : "", n + 1); - + tmp->len = strlen(tmp->line); tmp->next = tmp->prev = NULL; - + return tmp; } void txt_clean_text(Text *text) -{ +{ TextLine **top, **bot; if (!text->lines.first) { if (text->lines.last) text->lines.first = text->lines.last; else text->lines.first = text->lines.last = txt_new_line(NULL); } - + if (!text->lines.last) text->lines.last = text->lines.first; top = (TextLine **) &text->lines.first; bot = (TextLine **) &text->lines.last; - + while ((*top)->prev) *top = (*top)->prev; while ((*bot)->next) *bot = (*bot)->next; @@ -796,7 +796,7 @@ void txt_move_up(Text *text, const bool sel) int column = txt_utf8_offset_to_column((*linep)->line, *charp); *linep = (*linep)->prev; *charp = txt_utf8_column_to_offset((*linep)->line, column); - + } else { txt_move_bol(text, sel); @@ -888,7 +888,7 @@ void txt_move_left(Text *text, const bool sel) if (text->flags & TXT_TABSTOSPACES) { tabsize = txt_calc_tab_left(*linep, *charp); } - + if (tabsize) { (*charp) -= tabsize; } @@ -924,7 +924,7 @@ void txt_move_right(Text *text, const bool sel) if (text->flags & TXT_TABSTOSPACES) { tabsize = txt_calc_tab_right(*linep, *charp); } - + if (tabsize) { (*charp) += tabsize; } @@ -932,7 +932,7 @@ void txt_move_right(Text *text, const bool sel) (*charp) += BLI_str_utf8_size((*linep)->line + *charp); } } - + if (!sel) txt_pop_sel(text); } @@ -948,7 +948,7 @@ void txt_jump_left(Text *text, const bool sel, const bool use_init_step) BLI_str_cursor_step_utf8((*linep)->line, (*linep)->len, charp, STRCUR_DIR_PREV, STRCUR_JUMP_DELIM, use_init_step); - + if (!sel) txt_pop_sel(text); } @@ -960,11 +960,11 @@ void txt_jump_right(Text *text, const bool sel, const bool use_init_step) if (sel) txt_curs_sel(text, &linep, &charp); else { txt_pop_last(text); txt_curs_cur(text, &linep, &charp); } if (!*linep) return; - + BLI_str_cursor_step_utf8((*linep)->line, (*linep)->len, charp, STRCUR_DIR_NEXT, STRCUR_JUMP_DELIM, use_init_step); - + if (!sel) txt_pop_sel(text); } @@ -976,7 +976,7 @@ void txt_move_bol(Text *text, const bool sel) if (sel) txt_curs_sel(text, &linep, &charp); else txt_curs_cur(text, &linep, &charp); if (!*linep) return; - + *charp = 0; if (!sel) txt_pop_sel(text); @@ -1041,7 +1041,7 @@ void txt_move_to(Text *text, unsigned int line, unsigned int ch, const bool sel) if (sel) txt_curs_sel(text, &linep, &charp); else txt_curs_cur(text, &linep, &charp); if (!*linep) return; - + *linep = text->lines.first; for (i = 0; i < line; i++) { if ((*linep)->next) *linep = (*linep)->next; @@ -1050,7 +1050,7 @@ void txt_move_to(Text *text, unsigned int line, unsigned int ch, const bool sel) if (ch > (unsigned int)((*linep)->len)) ch = (unsigned int)((*linep)->len); *charp = ch; - + if (!sel) txt_pop_sel(text); } @@ -1062,7 +1062,7 @@ static void txt_curs_swap(Text *text) { TextLine *tmpl; int tmpc; - + tmpl = text->curl; text->curl = text->sell; text->sell = tmpl; @@ -1079,7 +1079,7 @@ static void txt_pop_first(Text *text) { txt_curs_swap(text); } - + txt_pop_sel(text); } @@ -1090,7 +1090,7 @@ static void txt_pop_last(Text *text) { txt_curs_swap(text); } - + txt_pop_sel(text); } @@ -1104,7 +1104,7 @@ void txt_order_cursors(Text *text, const bool reverse) { if (!text->curl) return; if (!text->sell) return; - + /* Flip so text->curl is before/after text->sell */ if (reverse == false) { if ((txt_get_span(text->curl, text->sell) < 0) || @@ -1136,7 +1136,7 @@ static void txt_delete_sel(Text *text, TextUndoBuf *utxt) if (!text->sell) return; if (!txt_has_sel(text)) return; - + txt_order_cursors(text, false); if (!undoing) { @@ -1152,15 +1152,15 @@ static void txt_delete_sel(Text *text, TextUndoBuf *utxt) buf[text->curc + (text->sell->len - text->selc)] = 0; make_new_line(text->curl, buf); - + tmpl = text->sell; while (tmpl != text->curl) { tmpl = tmpl->prev; if (!tmpl) break; - + txt_delete_line(text, tmpl->next); } - + text->sell = text->curl; text->selc = text->curc; } @@ -1169,7 +1169,7 @@ void txt_sel_all(Text *text) { text->curl = text->lines.first; text->curc = 0; - + text->sell = text->lines.last; text->selc = text->sell->len; } @@ -1190,7 +1190,7 @@ void txt_sel_clear(Text *text) void txt_sel_line(Text *text) { if (!text->curl) return; - + text->curc = 0; text->sell = text->curl; text->selc = text->sell->len; @@ -1213,7 +1213,7 @@ char *txt_to_buf(Text *text) linef = text->lines.first; charf = 0; - + linel = text->lines.last; charl = linel->len; @@ -1221,7 +1221,7 @@ char *txt_to_buf(Text *text) length = charl - charf; buf = MEM_mallocN(length + 2, "text buffer"); - + BLI_strncpy(buf, linef->line + charf, length + 1); buf[length] = 0; } @@ -1229,37 +1229,37 @@ char *txt_to_buf(Text *text) length = linef->len - charf; length += charl; length += 2; /* For the 2 '\n' */ - + tmp = linef->next; while (tmp && tmp != linel) { length += tmp->len + 1; tmp = tmp->next; } - + buf = MEM_mallocN(length + 1, "cut buffer"); strncpy(buf, linef->line + charf, linef->len - charf); length = linef->len - charf; - + buf[length++] = '\n'; - + tmp = linef->next; while (tmp && tmp != linel) { strncpy(buf + length, tmp->line, tmp->len); length += tmp->len; - + buf[length++] = '\n'; - + tmp = tmp->next; } strncpy(buf + length, linel->line, charl); length += charl; - + /* python compiler wants an empty end line */ buf[length++] = '\n'; buf[length] = 0; } - + return buf; } @@ -1269,11 +1269,11 @@ int txt_find_string(Text *text, const char *findstr, int wrap, int match_case) const char *s = NULL; if (!text->curl || !text->sell) return 0; - + txt_order_cursors(text, false); tl = startl = text->sell; - + if (match_case) s = strstr(&tl->line[text->selc], findstr); else s = BLI_strcasestr(&tl->line[text->selc], findstr); while (!s) { @@ -1290,7 +1290,7 @@ int txt_find_string(Text *text, const char *findstr, int wrap, int match_case) if (tl == startl) break; } - + if (s) { int newl = txt_get_span(text->lines.first, tl); int newc = (int)(s - tl->line); @@ -1311,10 +1311,10 @@ char *txt_sel_to_buf(Text *text) if (!text->curl) return NULL; if (!text->sell) return NULL; - + if (text->curl == text->sell) { linef = linel = text->curl; - + if (text->curc < text->selc) { charf = text->curc; charl = text->selc; @@ -1334,7 +1334,7 @@ char *txt_sel_to_buf(Text *text) else { linef = text->curl; linel = text->sell; - + charf = text->curc; charl = text->selc; } @@ -1343,39 +1343,39 @@ char *txt_sel_to_buf(Text *text) length = charl - charf; buf = MEM_mallocN(length + 1, "sel buffer"); - + BLI_strncpy(buf, linef->line + charf, length + 1); } else { length += linef->len - charf; length += charl; length++; /* For the '\n' */ - + tmp = linef->next; while (tmp && tmp != linel) { length += tmp->len + 1; tmp = tmp->next; } - + buf = MEM_mallocN(length + 1, "sel buffer"); - + strncpy(buf, linef->line + charf, linef->len - charf); length = linef->len - charf; - + buf[length++] = '\n'; - + tmp = linef->next; while (tmp && tmp != linel) { strncpy(buf + length, tmp->line, tmp->len); length += tmp->len; - + buf[length++] = '\n'; - + tmp = tmp->next; } strncpy(buf + length, linel->line, charl); length += charl; - + buf[length] = 0; } @@ -1393,11 +1393,11 @@ void txt_insert_buf(Text *text, TextUndoBuf *utxt, const char *in_buffer) if (!in_buffer) return; txt_delete_sel(text, utxt); - + len = strlen(in_buffer); buffer = BLI_strdupn(in_buffer, len); len += txt_extended_ascii_as_utf8(&buffer); - + if (!undoing) { txt_undo_add_blockop(text, utxt, UNDO_IBLOCK, buffer); } @@ -1407,7 +1407,7 @@ void txt_insert_buf(Text *text, TextUndoBuf *utxt, const char *in_buffer) while (buffer[i] && buffer[i] != '\n') { txt_add_raw_char(text, utxt, BLI_str_utf8_as_unicode_step(buffer, &i)); } - + if (buffer[i] == '\n') { txt_split_curline(text, utxt); i++; @@ -1492,16 +1492,16 @@ void txt_print_undo(Text *text) int op; const char *ops; int linep, charp; - + dump_buffer(text); - + printf("---< Undo Buffer >---\n"); - + printf("UndoPosition is %d\n", utxt->pos); - + while (i <= utxt->pos) { op = utxt->buf[i]; - + if (op == UNDO_INSERT_1) { ops = "Insert ascii "; } @@ -1559,7 +1559,7 @@ void txt_print_undo(Text *text) else { ops = "Unknown"; } - + printf("Op (%o) at %d = %s", op, i, ops); if (op >= UNDO_INSERT_1 && op <= UNDO_DEL_4) { i++; @@ -1600,14 +1600,14 @@ void txt_print_undo(Text *text) linep = linep + (utxt->buf[i] << 8); i++; linep = linep + (utxt->buf[i] << 16); i++; linep = linep + (utxt->buf[i] << 24); i++; - + printf(" (length %d) <", linep); - + while (linep > 0) { putchar(utxt->buf[i]); linep--; i++; } - + linep = utxt->buf[i]; i++; linep = linep + (utxt->buf[i] << 8); i++; linep = linep + (utxt->buf[i] << 16); i++; @@ -1624,7 +1624,7 @@ void txt_print_undo(Text *text) linep = linep + (utxt->buf[i] << 8); i++; linep = linep + (utxt->buf[i] << 16); i++; linep = linep + (utxt->buf[i] << 24); i++; - + printf("to <%d, %d> ", linep, charp); charp = utxt->buf[i]; i++; @@ -1634,17 +1634,17 @@ void txt_print_undo(Text *text) linep = linep + (utxt->buf[i] << 8); i++; linep = linep + (utxt->buf[i] << 16); i++; linep = linep + (utxt->buf[i] << 24); i++; - + printf("from <%d, %d>", linep, charp); } - + printf(" %d\n", i); i++; } } #endif -static void txt_undo_store_uint16(char *undo_buf, int *undo_pos, unsigned short value) +static void txt_undo_store_uint16(char *undo_buf, int *undo_pos, unsigned short value) { undo_buf[*undo_pos] = (value) & 0xff; (*undo_pos)++; @@ -1652,7 +1652,7 @@ static void txt_undo_store_uint16(char *undo_buf, int *undo_pos, unsigned short (*undo_pos)++; } -static void txt_undo_store_uint32(char *undo_buf, int *undo_pos, unsigned int value) +static void txt_undo_store_uint32(char *undo_buf, int *undo_pos, unsigned int value) { undo_buf[*undo_pos] = (value) & 0xff; (*undo_pos)++; @@ -1736,7 +1736,7 @@ static void txt_undo_add_charop(Text *text, TextUndoBuf *utxt, int op_start, uns { char utf8[BLI_UTF8_MAX]; size_t i, utf8_size = BLI_str_utf8_from_unicode(c, utf8); - + if (utf8_size < 4 && 0) { if (!max_undo_test(utxt, 2 + 6 + utf8_size + 1)) { return; @@ -1770,7 +1770,7 @@ static void txt_undo_add_charop(Text *text, TextUndoBuf *utxt, int op_start, uns /* 1 byte */ utxt->buf[utxt->pos] = op_start + 3; } - + txt_undo_end(text, utxt); } @@ -1869,10 +1869,10 @@ static unsigned int txt_undo_read_unicode(const char *undo_buf, int *undo_pos, s { unsigned int unicode; char utf8[BLI_UTF8_MAX + 1]; - + switch (bytes) { case 1: /* ascii */ - unicode = undo_buf[*undo_pos]; (*undo_pos)--; + unicode = undo_buf[*undo_pos]; (*undo_pos)--; break; case 2: /* 2-byte symbol */ utf8[2] = '\0'; @@ -1896,7 +1896,7 @@ static unsigned int txt_undo_read_unicode(const char *undo_buf, int *undo_pos, s unicode = 0; break; } - + return unicode; } @@ -1945,10 +1945,10 @@ static unsigned int txt_redo_read_unicode(const char *undo_buf, int *undo_pos, s { unsigned int unicode; char utf8[BLI_UTF8_MAX + 1]; - + switch (bytes) { case 1: /* ascii */ - unicode = undo_buf[*undo_pos]; (*undo_pos)++; + unicode = undo_buf[*undo_pos]; (*undo_pos)++; break; case 2: /* 2-byte symbol */ utf8[0] = undo_buf[*undo_pos]; (*undo_pos)++; @@ -1972,7 +1972,7 @@ static unsigned int txt_redo_read_unicode(const char *undo_buf, int *undo_pos, s unicode = 0; break; } - + return unicode; } @@ -1986,7 +1986,7 @@ void txt_do_undo(Text *text, TextUndoBuf *utxt) unsigned short curc, selc; unsigned short charp; char *buf; - + if (utxt->pos < 0) { return; } @@ -1994,21 +1994,21 @@ void txt_do_undo(Text *text, TextUndoBuf *utxt) utxt->pos--; undoing = 1; - + switch (op) { case UNDO_INSERT_1: case UNDO_INSERT_2: case UNDO_INSERT_3: case UNDO_INSERT_4: utxt->pos -= op - UNDO_INSERT_1 + 1; - + /* get and restore the cursors */ txt_undo_read_cur(utxt->buf, &utxt->pos, &curln, &curc); txt_move_to(text, curln, curc, 0); txt_move_to(text, curln, curc, 1); - + txt_delete_char(text, utxt); - + utxt->pos--; break; @@ -2018,12 +2018,12 @@ void txt_do_undo(Text *text, TextUndoBuf *utxt) case UNDO_BS_4: charp = op - UNDO_BS_1 + 1; uni_char = txt_undo_read_unicode(utxt->buf, &utxt->pos, charp); - + /* get and restore the cursors */ txt_undo_read_cur(utxt->buf, &utxt->pos, &curln, &curc); txt_move_to(text, curln, curc, 0); txt_move_to(text, curln, curc, 1); - + txt_add_char(text, utxt, uni_char); utxt->pos--; @@ -2069,7 +2069,7 @@ void txt_do_undo(Text *text, TextUndoBuf *utxt) /* move cur to location that needs buff inserted */ txt_move_to(text, curln, curc, 0); - + txt_insert_buf(text, utxt, buf); MEM_freeN(buf); @@ -2078,7 +2078,7 @@ void txt_do_undo(Text *text, TextUndoBuf *utxt) txt_move_to(text, selln, selc, 1); utxt->pos--; - + break; } case UNDO_IBLOCK: @@ -2086,7 +2086,7 @@ void txt_do_undo(Text *text, TextUndoBuf *utxt) int i; /* length of the string in the buffer */ linep = txt_undo_read_uint32(utxt->buf, &utxt->pos); - + /* txt_backspace_char removes utf8-characters, not bytes */ buf = MEM_mallocN(linep + 1, "iblock buffer"); for (i = 0; i < linep; i++) { @@ -2096,29 +2096,29 @@ void txt_do_undo(Text *text, TextUndoBuf *utxt) buf[i] = 0; linep = BLI_strlen_utf8(buf); MEM_freeN(buf); - + /* skip over the length that was stored again */ utxt->pos -= 4; /* get and restore the cursors */ txt_undo_read_cursors(utxt->buf, &utxt->pos, &curln, &curc, &selln, &selc); - + txt_move_to(text, curln, curc, 0); txt_move_to(text, selln, selc, 1); - + if ((curln == selln) && (curc == selc)) { /* disable tabs to spaces since moving right may involve skipping multiple spaces */ prev_flags = text->flags; text->flags &= ~TXT_TABSTOSPACES; - + for (i = 0; i < linep; i++) txt_move_right(text, 1); - + text->flags = prev_flags; } - + txt_delete_selected(text, utxt); - + utxt->pos--; break; } @@ -2131,7 +2131,7 @@ void txt_do_undo(Text *text, TextUndoBuf *utxt) txt_undo_read_cursors(utxt->buf, &utxt->pos, &curln, &curc, &selln, &selc); txt_move_to(text, curln, curc, 0); txt_move_to(text, selln, selc, 1); - + if (op == UNDO_INDENT) { txt_unindent(text, utxt); } @@ -2147,7 +2147,7 @@ void txt_do_undo(Text *text, TextUndoBuf *utxt) else if (op == UNDO_MOVE_LINES_DOWN) { txt_move_lines(text, utxt, TXT_MOVE_LINE_UP); } - + utxt->pos--; break; case UNDO_UNINDENT: @@ -2196,10 +2196,10 @@ void txt_do_undo(Text *text, TextUndoBuf *utxt) default: //XXX error("Undo buffer error - resetting"); utxt->pos = -1; - + break; } - + undoing = 0; } @@ -2212,15 +2212,15 @@ void txt_do_redo(Text *text, TextUndoBuf *utxt) unsigned int uni_uchar; unsigned int curln, selln; unsigned short curc, selc; - + utxt->pos++; op = utxt->buf[utxt->pos]; - + if (!op) { utxt->pos--; return; } - + undoing = 1; switch (op) { @@ -2229,12 +2229,12 @@ void txt_do_redo(Text *text, TextUndoBuf *utxt) case UNDO_INSERT_3: case UNDO_INSERT_4: utxt->pos++; - + /* get and restore the cursors */ txt_redo_read_cur(utxt->buf, &utxt->pos, &curln, &curc); txt_move_to(text, curln, curc, 0); txt_move_to(text, curln, curc, 1); - + charp = op - UNDO_INSERT_1 + 1; uni_uchar = txt_redo_read_unicode(utxt->buf, &utxt->pos, charp); @@ -2253,7 +2253,7 @@ void txt_do_redo(Text *text, TextUndoBuf *utxt) txt_move_to(text, curln, curc, 1); utxt->pos += op - UNDO_BS_1 + 1; - + /* move right so we backspace the correct char */ txt_move_right(text, 0); txt_backspace_char(text, utxt); @@ -2270,7 +2270,7 @@ void txt_do_redo(Text *text, TextUndoBuf *utxt) txt_redo_read_cur(utxt->buf, &utxt->pos, &curln, &curc); txt_move_to(text, curln, curc, 0); txt_move_to(text, curln, curc, 1); - + utxt->pos += op - UNDO_DEL_1 + 1; txt_delete_char(text, utxt); @@ -2287,12 +2287,12 @@ void txt_do_redo(Text *text, TextUndoBuf *utxt) /* length of the block */ linep = txt_redo_read_uint32(utxt->buf, &utxt->pos); - + utxt->pos += linep; /* skip over the length that was stored again */ utxt->pos += 4; - + txt_delete_sel(text, utxt); break; @@ -2312,7 +2312,7 @@ void txt_do_redo(Text *text, TextUndoBuf *utxt) memcpy(buf, &utxt->buf[utxt->pos], linep); utxt->pos += linep; buf[linep] = 0; - + txt_insert_buf(text, utxt, buf); MEM_freeN(buf); @@ -2320,7 +2320,7 @@ void txt_do_redo(Text *text, TextUndoBuf *utxt) utxt->pos += 4; break; - + case UNDO_INDENT: case UNDO_COMMENT: case UNDO_UNCOMMENT: @@ -2389,15 +2389,15 @@ void txt_do_redo(Text *text, TextUndoBuf *utxt) default: //XXX error("Undo buffer error - resetting"); utxt->pos = -1; - + break; } - + undoing = 0; } /**************************/ -/* Line editing functions */ +/* Line editing functions */ /**************************/ void txt_split_curline(Text *text, TextUndoBuf *utxt) @@ -2410,13 +2410,13 @@ void txt_split_curline(Text *text, TextUndoBuf *utxt) txt_delete_sel(text, utxt); if (!undoing) txt_undo_add_charop(text, utxt, UNDO_INSERT_1, '\n'); - + /* Make the two half strings */ left = MEM_mallocN(text->curc + 1, "textline_string"); if (text->curc) memcpy(left, text->curl->line, text->curc); left[text->curc] = 0; - + right = MEM_mallocN(text->curl->len - text->curc + 1, "textline_string"); memcpy(right, text->curl->line + text->curc, text->curl->len - text->curc + 1); @@ -2424,7 +2424,7 @@ void txt_split_curline(Text *text, TextUndoBuf *utxt) if (text->curl->format) MEM_freeN(text->curl->format); /* Make the new TextLine */ - + ins = MEM_mallocN(sizeof(TextLine), "textline"); ins->line = left; ins->format = NULL; @@ -2433,14 +2433,14 @@ void txt_split_curline(Text *text, TextUndoBuf *utxt) text->curl->line = right; text->curl->format = NULL; text->curl->len = text->curl->len - text->curc; - + BLI_insertlinkbefore(&text->lines, text->curl, ins); - + text->curc = 0; - + txt_make_dirty(text); txt_clean_text(text); - + txt_pop_sel(text); } @@ -2449,7 +2449,7 @@ static void txt_delete_line(Text *text, TextLine *line) if (!text->curl) return; BLI_remlink(&text->lines, line); - + if (line->line) MEM_freeN(line->line); if (line->format) MEM_freeN(line->format); @@ -2462,21 +2462,21 @@ static void txt_delete_line(Text *text, TextLine *line) static void txt_combine_lines(Text *text, TextLine *linea, TextLine *lineb) { char *tmp, *s; - + if (!linea || !lineb) return; tmp = MEM_mallocN(linea->len + lineb->len + 1, "textline_string"); - + s = tmp; s += BLI_strcpy_rlen(s, linea->line); s += BLI_strcpy_rlen(s, lineb->line); (void)s; make_new_line(linea, tmp); - + txt_delete_line(text, lineb); - + txt_make_dirty(text); txt_clean_text(text); } @@ -2484,16 +2484,16 @@ static void txt_combine_lines(Text *text, TextLine *linea, TextLine *lineb) void txt_duplicate_line(Text *text, TextUndoBuf *utxt) { TextLine *textline; - + if (!text->curl) return; - + if (text->curl == text->sell) { textline = txt_new_line(text->curl->line); BLI_insertlinkafter(&text->lines, text->curl, textline); - + txt_make_dirty(text); txt_clean_text(text); - + if (!undoing) txt_undo_add_op(text, utxt, UNDO_DUPLICATE); } } @@ -2520,7 +2520,7 @@ void txt_delete_char(Text *text, TextUndoBuf *utxt) else { /* Just deleting a char */ size_t c_len = 0; c = BLI_str_utf8_as_unicode_and_size(text->curl->line + text->curc, &c_len); - + memmove(text->curl->line + text->curc, text->curl->line + text->curc + c_len, text->curl->len - text->curc - c_len + 1); text->curl->len -= c_len; @@ -2530,7 +2530,7 @@ void txt_delete_char(Text *text, TextUndoBuf *utxt) txt_make_dirty(text); txt_clean_text(text); - + if (!undoing) txt_undo_add_charop(text, utxt, UNDO_DEL_1, c); } @@ -2544,9 +2544,9 @@ void txt_delete_word(Text *text, TextUndoBuf *utxt) void txt_backspace_char(Text *text, TextUndoBuf *utxt) { unsigned int c = '\n'; - + if (!text->curl) return; - + if (txt_has_sel(text)) { /* deleting a selection */ txt_delete_sel(text, utxt); txt_make_dirty(text); @@ -2554,10 +2554,10 @@ void txt_backspace_char(Text *text, TextUndoBuf *utxt) } else if (text->curc == 0) { /* Appending two lines */ if (!text->curl->prev) return; - + text->curl = text->curl->prev; text->curc = text->curl->len; - + txt_combine_lines(text, text->curl, text->curl->next); txt_pop_sel(text); } @@ -2565,7 +2565,7 @@ void txt_backspace_char(Text *text, TextUndoBuf *utxt) size_t c_len = 0; const char *prev = BLI_str_prev_char_utf8(text->curl->line + text->curc); c = BLI_str_utf8_as_unicode_and_size(prev, &c_len); - + /* source and destination overlap, don't use memcpy() */ memmove(text->curl->line + text->curc - c_len, text->curl->line + text->curc, @@ -2579,7 +2579,7 @@ void txt_backspace_char(Text *text, TextUndoBuf *utxt) txt_make_dirty(text); txt_clean_text(text); - + if (!undoing) txt_undo_add_charop(text, utxt, UNDO_BS_1, c); } @@ -2616,7 +2616,7 @@ static bool txt_add_char_intern(Text *text, TextUndoBuf *utxt, unsigned int add, txt_split_curline(text, utxt); return true; } - + /* insert spaces rather than tabs */ if (add == '\t' && replace_tabs) { txt_convert_tab_to_spaces(text, utxt); @@ -2624,23 +2624,23 @@ static bool txt_add_char_intern(Text *text, TextUndoBuf *utxt, unsigned int add, } txt_delete_sel(text, utxt); - + if (!undoing) txt_undo_add_charop(text, utxt, UNDO_INSERT_1, add); add_len = BLI_str_utf8_from_unicode(add, ch); - + tmp = MEM_mallocN(text->curl->len + add_len + 1, "textline_string"); - + memcpy(tmp, text->curl->line, text->curc); memcpy(tmp + text->curc, ch, add_len); memcpy(tmp + text->curc + add_len, text->curl->line + text->curc, text->curl->len - text->curc + 1); make_new_line(text->curl, tmp); - + text->curc += add_len; txt_pop_sel(text); - + txt_make_dirty(text); txt_clean_text(text); @@ -2675,10 +2675,10 @@ bool txt_replace_char(Text *text, TextUndoBuf *utxt, unsigned int add) if (text->curc == text->curl->len || txt_has_sel(text) || add == '\n') { return txt_add_char(text, utxt, add); } - + del = BLI_str_utf8_as_unicode_and_size(text->curl->line + text->curc, &del_size); add_size = BLI_str_utf8_from_unicode(add, ch); - + if (add_size > del_size) { char *tmp = MEM_mallocN(text->curl->len + add_size - del_size + 1, "textline_string"); memcpy(tmp, text->curl->line, text->curc); @@ -2690,11 +2690,11 @@ bool txt_replace_char(Text *text, TextUndoBuf *utxt, unsigned int add) char *tmp = text->curl->line; memmove(tmp + text->curc + add_size, tmp + text->curc + del_size, text->curl->len - text->curc - del_size + 1); } - + memcpy(text->curl->line + text->curc, ch, add_size); text->curc += add_size; text->curl->len += add_size - del_size; - + txt_pop_sel(text); txt_make_dirty(text); txt_clean_text(text); @@ -2749,7 +2749,7 @@ static void txt_select_prefix(Text *text, const char *add) txt_make_dirty(text); txt_clean_text(text); } - + if (text->curl == text->sell) { text->selc += indentlen; break; @@ -2766,7 +2766,7 @@ static void txt_select_prefix(Text *text, const char *add) text->curl = text->curl->prev; num--; } - + /* caller must handle undo */ } @@ -2816,10 +2816,10 @@ static void txt_select_unprefix( (*r_line_index_mask_len) += 1; } } - + txt_make_dirty(text); txt_clean_text(text); - + if (text->curl == text->sell) { if (changed) text->selc = MAX2(text->selc - indentlen, 0); @@ -2830,7 +2830,7 @@ static void txt_select_unprefix( num++; } - + } if (unindented_first) @@ -2898,7 +2898,7 @@ void txt_unindent(Text *text, TextUndoBuf *utxt) const char *prefix = (text->flags & TXT_TABSTOSPACES) ? tab_to_spaces : "\t"; ListBase line_index_mask; int line_index_mask_len; - + if (ELEM(NULL, text->curl, text->sell)) { return; } @@ -2919,13 +2919,13 @@ void txt_move_lines(struct Text *text, TextUndoBuf *utxt, const int direction) BLI_assert(ELEM(direction, TXT_MOVE_LINE_UP, TXT_MOVE_LINE_DOWN)); if (!text->curl || !text->sell) return; - + txt_order_cursors(text, false); line_other = (direction == TXT_MOVE_LINE_DOWN) ? text->sell->next : text->curl->prev; - + if (!line_other) return; - + BLI_remlink(&text->lines, line_other); if (direction == TXT_MOVE_LINE_DOWN) { @@ -2937,7 +2937,7 @@ void txt_move_lines(struct Text *text, TextUndoBuf *utxt, const int direction) txt_make_dirty(text); txt_clean_text(text); - + if (!undoing) { txt_undo_add_op(text, utxt, (direction == TXT_MOVE_LINE_DOWN) ? UNDO_MOVE_LINES_DOWN : UNDO_MOVE_LINES_UP); } @@ -2967,7 +2967,7 @@ int txt_setcurr_tab_spaces(Text *text, int space) /* if we find a ':' on this line, then add a tab but not if it is: * 1) in a comment * 2) within an identifier - * 3) after the cursor (text->curc), i.e. when creating space before a function def [#25414] + * 3) after the cursor (text->curc), i.e. when creating space before a function def [#25414] */ int a; bool is_indent = false; diff --git a/source/blender/blenkernel/intern/texture.c b/source/blender/blenkernel/intern/texture.c index 2bf2fa7807b..ad60e81fe19 100644 --- a/source/blender/blenkernel/intern/texture.c +++ b/source/blender/blenkernel/intern/texture.c @@ -76,9 +76,9 @@ TexMapping *BKE_texture_mapping_add(int type) { TexMapping *texmap = MEM_callocN(sizeof(TexMapping), "TexMapping"); - + BKE_texture_mapping_default(texmap, type); - + return texmap; } @@ -132,7 +132,7 @@ void BKE_texture_mapping_init(TexMapping *texmap) if (fabsf(size[2]) < 1e-5f) size[2] = signf(size[2]) * 1e-5f; } - + size_to_mat4(smat, texmap->size); /* rotation */ @@ -173,9 +173,9 @@ void BKE_texture_mapping_init(TexMapping *texmap) ColorMapping *BKE_texture_colormapping_add(void) { ColorMapping *colormap = MEM_callocN(sizeof(ColorMapping), "ColorMapping"); - + BKE_texture_colormapping_default(colormap); - + return colormap; } @@ -211,7 +211,7 @@ void BKE_texture_free(Tex *tex) } MEM_SAFE_FREE(tex->coba); - + BKE_icon_id_delete((ID *)tex); BKE_previewimg_free(&tex->preview); } @@ -271,7 +271,7 @@ void BKE_texture_default(Tex *tex) tex->iuser.ok = 1; tex->iuser.frames = 100; tex->iuser.sfra = 1; - + tex->preview = NULL; } @@ -287,9 +287,9 @@ Tex *BKE_texture_add(Main *bmain, const char *name) Tex *tex; tex = BKE_libblock_alloc(bmain, ID_TE, name, 0); - + BKE_texture_default(tex); - + return tex; } @@ -369,11 +369,11 @@ void BKE_texture_mtex_default(MTex *mtex) MTex *BKE_texture_mtex_add(void) { MTex *mtex; - + mtex = MEM_callocN(sizeof(MTex), "BKE_texture_mtex_add"); - + BKE_texture_mtex_default(mtex); - + return mtex; } @@ -388,7 +388,7 @@ MTex *BKE_texture_mtex_add_id(ID *id, int slot) if (mtex_ar == NULL) { return NULL; } - + if (slot == -1) { /* find first free */ int i; @@ -474,19 +474,19 @@ Tex *BKE_texture_localize(Tex *tex) * ... Once f*** nodes are fully converted to that too :( */ Tex *texn; - + texn = BKE_libblock_copy_nolib(&tex->id, false); - + /* image texture: BKE_texture_free also doesn't decrease */ - + if (texn->coba) texn->coba = MEM_dupallocN(texn->coba); - + texn->preview = NULL; - + if (tex->nodetree) { texn->nodetree = ntreeLocalize(tex->nodetree); } - + return texn; } @@ -590,12 +590,12 @@ Tex *give_current_particle_texture(ParticleSettings *part) { MTex *mtex = NULL; Tex *tex = NULL; - + if (!part) return NULL; - + mtex = part->mtex[(int)(part->texact)]; if (mtex) tex = mtex->tex; - + return tex; } @@ -612,7 +612,7 @@ void set_current_particle_texture(ParticleSettings *part, Tex *newtex) part->mtex[act]->texco = TEXCO_ORCO; part->mtex[act]->blendtype = MTEX_MUL; } - + part->mtex[act]->tex = newtex; id_us_plus(&newtex->id); } @@ -657,7 +657,7 @@ PointDensity *BKE_texture_pointdensity_add(void) PointDensity *pd = MEM_callocN(sizeof(PointDensity), "pointdensity"); BKE_texture_pointdensity_init_data(pd); return pd; -} +} PointDensity *BKE_texture_pointdensity_copy(const PointDensity *pd, const int UNUSED(flag)) { diff --git a/source/blender/blenkernel/intern/tracking_solver.c b/source/blender/blenkernel/intern/tracking_solver.c index c21883c6eb8..a5d35449229 100644 --- a/source/blender/blenkernel/intern/tracking_solver.c +++ b/source/blender/blenkernel/intern/tracking_solver.c @@ -518,7 +518,7 @@ bool BKE_tracking_reconstruction_finish(MovieReconstructContext *context, MovieT BKE_tracking_dopesheet_tag_update(tracking); object = BKE_tracking_object_get_named(tracking, context->object_name); - + if (context->is_camera) reconstruction = &tracking->reconstruction; else diff --git a/source/blender/blenkernel/intern/undo_system.c b/source/blender/blenkernel/intern/undo_system.c index a05e79aae1f..173b459f442 100644 --- a/source/blender/blenkernel/intern/undo_system.c +++ b/source/blender/blenkernel/intern/undo_system.c @@ -235,6 +235,23 @@ void BKE_undosys_stack_clear(UndoStack *ustack) ustack->step_active = NULL; } +void BKE_undosys_stack_clear_active(UndoStack *ustack) +{ + /* Remove active and all following undos. */ + UndoStep *us = ustack->step_active; + + if (us) { + ustack->step_active = us->prev; + bool is_not_empty = ustack->step_active != NULL; + + while (ustack->steps.last != ustack->step_active) { + UndoStep *us_iter = ustack->steps.last; + undosys_step_free_and_unlink(ustack, us_iter); + undosys_stack_validate(ustack, is_not_empty); + } + } +} + static bool undosys_stack_push_main(UndoStack *ustack, const char *name, struct Main *bmain) { UNDO_NESTED_ASSERT(false); diff --git a/source/blender/blenkernel/intern/workspace.c b/source/blender/blenkernel/intern/workspace.c index b71dfaf5aea..99fb6b14a35 100644 --- a/source/blender/blenkernel/intern/workspace.c +++ b/source/blender/blenkernel/intern/workspace.c @@ -227,13 +227,14 @@ void BKE_workspace_instance_hook_free(const Main *bmain, WorkSpaceInstanceHook * * Add a new layout to \a workspace for \a screen. */ WorkSpaceLayout *BKE_workspace_layout_add( + Main *bmain, WorkSpace *workspace, bScreen *screen, const char *name) { WorkSpaceLayout *layout = MEM_callocN(sizeof(*layout), __func__); - BLI_assert(!workspaces_is_screen_used(G.main, screen)); + BLI_assert(!workspaces_is_screen_used(bmain, screen)); layout->screen = screen; workspace_layout_name_set(workspace, layout, name); BLI_addtail(&workspace->layouts, layout); diff --git a/source/blender/blenkernel/intern/world.c b/source/blender/blenkernel/intern/world.c index 1b06e7ed851..69096ad7a08 100644 --- a/source/blender/blenkernel/intern/world.c +++ b/source/blender/blenkernel/intern/world.c @@ -70,7 +70,7 @@ void BKE_world_free(World *wrld) } GPU_material_free(&wrld->gpumaterial); - + BKE_icon_id_delete((struct ID *)wrld); BKE_previewimg_free(&wrld->preview); } @@ -85,7 +85,7 @@ void BKE_world_init(World *wrld) wrld->aodist = 10.0f; wrld->aoenergy = 1.0f; - + wrld->preview = NULL; wrld->miststa = 5.0f; wrld->mistdist = 25.0f; @@ -145,16 +145,16 @@ World *BKE_world_localize(World *wrld) * ... Once f*** nodes are fully converted to that too :( */ World *wrldn; - + wrldn = BKE_libblock_copy_nolib(&wrld->id, false); - + if (wrld->nodetree) wrldn->nodetree = ntreeLocalize(wrld->nodetree); - + wrldn->preview = NULL; - + BLI_listbase_clear(&wrldn->gpumaterial); - + return wrldn; } diff --git a/source/blender/blenkernel/intern/writeavi.c b/source/blender/blenkernel/intern/writeavi.c index 33ac312425b..994592ec307 100644 --- a/source/blender/blenkernel/intern/writeavi.c +++ b/source/blender/blenkernel/intern/writeavi.c @@ -150,7 +150,7 @@ static void filepath_avi(char *string, RenderData *rd, bool preview, const char BLI_make_existing_file(string); if (rd->scemode & R_EXTENSION) { - if (!BLI_testextensie(string, ".avi")) { + if (!BLI_path_extension_check(string, ".avi")) { BLI_path_frame_range(string, sfra, efra, 4); strcat(string, ".avi"); } @@ -189,7 +189,7 @@ static int start_avi(void *context_v, Scene *UNUSED(scene), RenderData *rd, int BKE_report(reports, RPT_ERROR, "Cannot open or start AVI movie file"); return 0; } - + AVI_set_compress_option(avi, AVI_OPTION_TYPE_MAIN, 0, AVI_OPTION_WIDTH, &x); AVI_set_compress_option(avi, AVI_OPTION_TYPE_MAIN, 0, AVI_OPTION_HEIGHT, &y); AVI_set_compress_option(avi, AVI_OPTION_TYPE_MAIN, 0, AVI_OPTION_QUALITY, &quality); @@ -199,7 +199,7 @@ static int start_avi(void *context_v, Scene *UNUSED(scene), RenderData *rd, int avi->odd_fields = 0; /* avi->interlace = rd->mode & R_FIELDS; */ /* avi->odd_fields = (rd->mode & R_ODDFIELD) ? 1 : 0; */ - + printf("Created avi: %s\n", name); return 1; } @@ -211,7 +211,7 @@ static int append_avi(void *context_v, RenderData *UNUSED(rd), int start_frame, int x, y; char *cp, rt; AviMovie *avi = context_v; - + if (avi == NULL) return 0; @@ -222,7 +222,7 @@ static int append_avi(void *context_v, RenderData *UNUSED(rd), int start_frame, /* flip y and convert to abgr */ for (y = 0; y < recty; y++, rt1 += rectx, rt2 -= rectx) { memcpy(rt1, rt2, rectx * sizeof(int)); - + cp = (char *)rt1; for (x = rectx; x > 0; x--) { rt = cp[0]; @@ -234,7 +234,7 @@ static int append_avi(void *context_v, RenderData *UNUSED(rd), int start_frame, cp += 4; } } - + AVI_write_frame(avi, (frame - start_frame), AVI_FORMAT_RGB32, rectot, rectx * recty * 4); // printf("added frame %3d (frame %3d in avi): ", frame, frame-start_frame); diff --git a/source/blender/blenkernel/intern/writeffmpeg.c b/source/blender/blenkernel/intern/writeffmpeg.c index 17c665f3bcd..394f4cc1122 100644 --- a/source/blender/blenkernel/intern/writeffmpeg.c +++ b/source/blender/blenkernel/intern/writeffmpeg.c @@ -231,7 +231,7 @@ static AVFrame *alloc_picture(int pix_fmt, int width, int height) AVFrame *f; uint8_t *buf; int size; - + /* allocate space for the struct */ f = av_frame_alloc(); if (!f) return NULL; @@ -511,7 +511,7 @@ static void set_ffmpeg_properties(RenderData *rd, AVCodecContext *c, const char if (!rd->ffcodecdata.properties) { return; } - + prop = IDP_GetPropertyFromGroup(rd->ffcodecdata.properties, prop_name); if (!prop) { return; @@ -540,13 +540,13 @@ static AVStream *alloc_video_stream(FFMpegContext *context, RenderData *rd, int st->id = 0; /* Set up the codec context */ - + c = st->codec; c->codec_id = codec_id; c->codec_type = AVMEDIA_TYPE_VIDEO; /* Get some values from the current render settings */ - + c->width = rectx; c->height = recty; @@ -563,7 +563,7 @@ static AVStream *alloc_video_stream(FFMpegContext *context, RenderData *rd, int c->time_base.den = rd->frs_sec * 100000; c->time_base.num = ((double) rd->frs_sec_base) * 100000; } - + c->gop_size = context->ffmpeg_gop_size; c->max_b_frames = context->ffmpeg_max_b_frames; @@ -617,11 +617,11 @@ static AVStream *alloc_video_stream(FFMpegContext *context, RenderData *rd, int /* Deprecated and not doing anything since July 2015, deleted in recent ffmpeg */ //c->me_method = ME_EPZS; - + codec = avcodec_find_encoder(c->codec_id); if (!codec) return NULL; - + /* Be sure to use the correct pixel format(e.g. RGB, YUV) */ if (codec->pix_fmts) { @@ -643,7 +643,7 @@ static AVStream *alloc_video_stream(FFMpegContext *context, RenderData *rd, int c->qmin = 10; c->qmax = 51; } - + /* Keep lossless encodes in the RGB domain. */ if (codec_id == AV_CODEC_ID_HUFFYUV) { if (rd->im_format.planes == R_IMF_PLANES_RGBA) { @@ -681,7 +681,7 @@ static AVStream *alloc_video_stream(FFMpegContext *context, RenderData *rd, int PRINT("Using global header\n"); c->flags |= CODEC_FLAG_GLOBAL_HEADER; } - + /* xasp & yasp got float lately... */ st->sample_aspect_ratio = c->sample_aspect_ratio = av_d2q(((double) rd->xasp / (double) rd->yasp), 255); @@ -879,7 +879,7 @@ static int start_ffmpeg_impl(FFMpegContext *context, struct RenderData *rd, int name, context->ffmpeg_type, context->ffmpeg_codec, context->ffmpeg_audio_codec, context->ffmpeg_video_bitrate, context->ffmpeg_audio_bitrate, context->ffmpeg_gop_size, context->ffmpeg_autosplit, rectx, recty); - + exts = get_file_extensions(context->ffmpeg_type); if (!exts) { BKE_report(reports, RPT_ERROR, "No valid formats found"); @@ -967,7 +967,7 @@ static int start_ffmpeg_impl(FFMpegContext *context, struct RenderData *rd, int goto fail; } } - + if (context->ffmpeg_type == FFMPEG_DV) { fmt->audio_codec = AV_CODEC_ID_PCM_S16LE; if (context->ffmpeg_audio_codec != AV_CODEC_ID_NONE && rd->ffcodecdata.audio_mixrate != 48000 && rd->ffcodecdata.audio_channels != 2) { @@ -975,7 +975,7 @@ static int start_ffmpeg_impl(FFMpegContext *context, struct RenderData *rd, int goto fail; } } - + if (fmt->video_codec != AV_CODEC_ID_NONE) { context->video_stream = alloc_video_stream(context, rd, fmt->video_codec, of, rectx, recty, error, sizeof(error)); PRINT("alloc video stream %p\n", context->video_stream); @@ -1061,14 +1061,14 @@ fail: static void flush_ffmpeg(FFMpegContext *context) { int ret = 0; - + AVCodecContext *c = context->video_stream->codec; /* get the delayed frames */ while (1) { int got_output; AVPacket packet = { 0 }; av_init_packet(&packet); - + ret = avcodec_encode_video2(c, &packet, NULL, &got_output); if (ret < 0) { fprintf(stderr, "Error encoding delayed frame %d\n", ret); @@ -1294,11 +1294,11 @@ static void end_ffmpeg_impl(FFMpegContext *context, int is_autosplit) PRINT("Flushing delayed frames...\n"); flush_ffmpeg(context); } - + if (context->outfile) { av_write_trailer(context->outfile); } - + /* Close the video codec */ if (context->video_stream != NULL && context->video_stream->codec != NULL) { @@ -1360,7 +1360,7 @@ void BKE_ffmpeg_property_del(RenderData *rd, void *type, void *prop_) { struct IDProperty *prop = (struct IDProperty *) prop_; IDProperty *group; - + if (!rd->ffcodecdata.properties) { return; } @@ -1379,17 +1379,17 @@ static IDProperty *BKE_ffmpeg_property_add(RenderData *rd, const char *type, con IDPropertyTemplate val; int idp_type; char name[256]; - + val.i = 0; avcodec_get_context_defaults3(&c, NULL); if (!rd->ffcodecdata.properties) { - rd->ffcodecdata.properties = IDP_New(IDP_GROUP, &val, "ffmpeg"); + rd->ffcodecdata.properties = IDP_New(IDP_GROUP, &val, "ffmpeg"); } group = IDP_GetPropertyFromGroup(rd->ffcodecdata.properties, type); - + if (!group) { group = IDP_New(IDP_GROUP, &val, type); IDP_AddToGroup(rd->ffcodecdata.properties, group); @@ -1449,7 +1449,7 @@ int BKE_ffmpeg_property_add_string(RenderData *rd, const char *type, const char char *name; char *param; IDProperty *prop = NULL; - + avcodec_get_context_defaults3(&c, NULL); BLI_strncpy(name_, str, sizeof(name_)); @@ -1466,7 +1466,7 @@ int BKE_ffmpeg_property_add_string(RenderData *rd, const char *type, const char *param++ = '\0'; while (*param == ' ') param++; } - + o = av_opt_find(&c, name, NULL, 0, AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ); if (!o) { PRINT("Ignoring unknown expert option %s\n", str); @@ -1487,7 +1487,7 @@ int BKE_ffmpeg_property_add_string(RenderData *rd, const char *type, const char else { prop = BKE_ffmpeg_property_add(rd, (char *) type, o, NULL); } - + if (!prop) { return 0; diff --git a/source/blender/blenkernel/nla_private.h b/source/blender/blenkernel/nla_private.h index c441f00ceaa..87f4e37e86d 100644 --- a/source/blender/blenkernel/nla_private.h +++ b/source/blender/blenkernel/nla_private.h @@ -40,13 +40,13 @@ struct Depsgraph; /* used for list of strips to accumulate at current time */ typedef struct NlaEvalStrip { struct NlaEvalStrip *next, *prev; - + NlaTrack *track; /* track that this strip belongs to */ NlaStrip *strip; /* strip that's being used */ - + short track_index; /* the index of the track within the list */ short strip_mode; /* which end of the strip are we looking at */ - + float strip_time; /* time at which which strip is being evaluated */ } NlaEvalStrip; @@ -56,7 +56,7 @@ enum eNlaEvalStrip_StripMode { NES_TIME_BEFORE = -1, NES_TIME_WITHIN, NES_TIME_AFTER, - + /* transition-strip evaluations */ NES_TIME_TRANSITION_START, NES_TIME_TRANSITION_END, @@ -67,11 +67,11 @@ enum eNlaEvalStrip_StripMode { // TODO: maybe this will be used as the 'cache' stuff needed for editable values too? typedef struct NlaEvalChannel { struct NlaEvalChannel *next, *prev; - + PointerRNA ptr; /* pointer to struct containing property to use */ PropertyRNA *prop; /* RNA-property type to use (should be in the struct given) */ int index; /* array index (where applicable) */ - + float value; /* value of this channel */ } NlaEvalChannel; |