diff options
author | Lukas Tönne <lukas.toenne@gmail.com> | 2016-04-28 18:33:19 +0300 |
---|---|---|
committer | Lukas Tönne <lukas.toenne@gmail.com> | 2016-04-28 18:33:19 +0300 |
commit | 1f723603c882e6d79ab69bea6e5c034ae21a6ce7 (patch) | |
tree | 098b0133beea06c460c3e9e92010bc669d151e5d /source/blender/blenkernel/intern | |
parent | 3632c4997f5019d2a519996d9e216d474aa05d3b (diff) | |
parent | a48d7407986d04492107a2ef16d0ff6f0d012c45 (diff) |
Merge branch 'master' into temp_remove_particlestemp_remove_particles
Diffstat (limited to 'source/blender/blenkernel/intern')
22 files changed, 1671 insertions, 1245 deletions
diff --git a/source/blender/blenkernel/intern/DerivedMesh.c b/source/blender/blenkernel/intern/DerivedMesh.c index d120678c005..57926e6a56a 100644 --- a/source/blender/blenkernel/intern/DerivedMesh.c +++ b/source/blender/blenkernel/intern/DerivedMesh.c @@ -49,6 +49,7 @@ #include "BLI_math.h" #include "BLI_utildefines.h" #include "BLI_linklist.h" +#include "BLI_task.h" #include "BKE_cdderivedmesh.h" #include "BKE_editmesh.h" @@ -595,50 +596,49 @@ void DM_generate_tangent_tessface_data(DerivedMesh *dm, bool generate) int mf_idx; int *polyindex = CustomData_get_layer(fdata, CD_ORIGINDEX); - unsigned int (*loopindex)[4]; + unsigned int (*loopindex)[4] = NULL; /* Should never occure, but better abort than segfault! */ if (!polyindex) return; if (generate) { - for (int i = 0; i < ldata->totlayer; i++) { - if (ldata->layers[i].type == CD_TANGENT) { - CustomData_add_layer_named(fdata, CD_TANGENT, CD_CALLOC, NULL, totface, ldata->layers[i].name); - } - } - CustomData_bmesh_update_active_layers(fdata, pdata, ldata); - } - - BLI_assert(CustomData_from_bmeshpoly_test(fdata, pdata, ldata, true)); - - loopindex = MEM_mallocN(sizeof(*loopindex) * totface, __func__); - - for (mf_idx = 0, mf = mface; mf_idx < totface; mf_idx++, mf++) { - const int mf_len = mf->v4 ? 4 : 3; - unsigned int *ml_idx = loopindex[mf_idx]; - int i, not_done; + for (int j = 0; j < ldata->totlayer; j++) { + if (ldata->layers[j].type == CD_TANGENT) { + CustomData_add_layer_named(fdata, CD_TANGENT, CD_CALLOC, NULL, totface, ldata->layers[j].name); + CustomData_bmesh_update_active_layers(fdata, pdata, ldata); + + if (!loopindex) { + loopindex = MEM_mallocN(sizeof(*loopindex) * totface, __func__); + for (mf_idx = 0, mf = mface; mf_idx < totface; mf_idx++, mf++) { + const int mf_len = mf->v4 ? 4 : 3; + unsigned int *ml_idx = loopindex[mf_idx]; + + /* Find out loop indices. */ + /* NOTE: This assumes tessface are valid and in sync with loop/poly... Else, most likely, segfault! */ + for (int i = mp[polyindex[mf_idx]].loopstart, not_done = mf_len; not_done; i++) { + const int tf_v = BKE_MESH_TESSFACE_VINDEX_ORDER(mf, ml[i].v); + if (tf_v != -1) { + ml_idx[tf_v] = i; + not_done--; + } + } + } + } - /* Find out loop indices. */ - /* NOTE: This assumes tessface are valid and in sync with loop/poly... Else, most likely, segfault! */ - for (i = mp[polyindex[mf_idx]].loopstart, not_done = mf_len; not_done; i++) { - const int tf_v = BKE_MESH_TESSFACE_VINDEX_ORDER(mf, ml[i].v); - if (tf_v != -1) { - ml_idx[tf_v] = i; - not_done--; + /* NOTE: quad detection issue - fourth vertidx vs fourth loopidx: + * Here, our tfaces' fourth vertex index is never 0 for a quad. However, we know our fourth loop index may be + * 0 for quads (because our quads may have been rotated compared to their org poly, see tessellation code). + * So we pass the MFace's, and BKE_mesh_loops_to_tessdata will use MFace->v4 index as quad test. + */ + BKE_mesh_tangent_loops_to_tessdata(fdata, ldata, mface, polyindex, loopindex, totface, ldata->layers[j].name); } } + if (loopindex) + MEM_freeN(loopindex); + BLI_assert(CustomData_from_bmeshpoly_test(fdata, pdata, ldata, true)); } - /* NOTE: quad detection issue - fourth vertidx vs fourth loopidx: - * Here, our tfaces' fourth vertex index is never 0 for a quad. However, we know our fourth loop index may be - * 0 for quads (because our quads may have been rotated compared to their org poly, see tessellation code). - * So we pass the MFace's, and BKE_mesh_loops_to_tessdata will use MFace->v4 index as quad test. - */ - BKE_mesh_tangent_loops_to_tessdata(fdata, ldata, mface, polyindex, loopindex, totface); - - MEM_freeN(loopindex); - if (G.debug & G_DEBUG) printf("%s: Updated tessellated tangents of dm %p\n", __func__, dm); } @@ -3207,96 +3207,28 @@ finally: pRes[3] = fSign; } -void DM_calc_loop_tangents(DerivedMesh *dm) +void DM_calc_tangents_names_from_gpu( + const GPUVertexAttribs *gattribs, + char (*tangent_names)[MAX_NAME], int *r_tangent_names_count) { - /* mesh vars */ - const MLoopTri *looptri; - MVert *mvert; - MLoopUV *mloopuv; - MPoly *mpoly; - MLoop *mloop; - float (*orco)[3] = NULL, (*tangent)[4]; - int /* totvert, */ totface; - float (*fnors)[3]; - float (*tlnors)[3]; - - if (CustomData_get_layer_index(&dm->loopData, CD_TANGENT) != -1) - return; - - fnors = dm->getPolyDataArray(dm, CD_NORMAL); - /* Note, we assume we do have tessellated loop normals at this point (in case it is object-enabled), - * have to check this is valid... - */ - tlnors = dm->getLoopDataArray(dm, CD_NORMAL); - - /* check we have all the needed layers */ - /* totvert = dm->getNumVerts(dm); */ /* UNUSED */ - looptri = dm->getLoopTriArray(dm); - totface = dm->getNumLoopTri(dm); - - mvert = dm->getVertArray(dm); - mpoly = dm->getPolyArray(dm); - mloop = dm->getLoopArray(dm); - mloopuv = dm->getLoopDataArray(dm, CD_MLOOPUV); - - if (!mloopuv) { - orco = dm->getVertDataArray(dm, CD_ORCO); - if (!orco) - return; - } - - /* create tangent layer */ - DM_add_loop_layer(dm, CD_TANGENT, CD_CALLOC, NULL); - tangent = DM_get_loop_data_layer(dm, CD_TANGENT); - -#ifdef USE_LOOPTRI_DETECT_QUADS - int num_face_as_quad_map; - int *face_as_quad_map = NULL; - - /* map faces to quads */ - if (totface != dm->getNumPolys(dm)) { - /* over alloc, since we dont know how many ngon or quads we have */ - - /* map fake face index to looptri */ - face_as_quad_map = MEM_mallocN(sizeof(int) * totface, __func__); - int i, j; - for (i = 0, j = 0; j < totface; i++, j++) { - face_as_quad_map[i] = j; - /* step over all quads */ - if (mpoly[looptri[j].poly].totloop == 4) { - j++; /* skips the nest looptri */ - } + int count = 0; + for (int b = 0; b < gattribs->totlayer; b++) { + if (gattribs->layer[b].type == CD_TANGENT) { + strcpy(tangent_names[count++], gattribs->layer[b].name); } - num_face_as_quad_map = i; - } - else { - num_face_as_quad_map = totface; } -#endif + *r_tangent_names_count = count; +} +static void DM_calc_loop_tangents_thread(TaskPool *UNUSED(pool), void *taskdata, int UNUSED(threadid)) +{ + struct SGLSLMeshToTangent *mesh2tangent = taskdata; /* new computation method */ { - SGLSLMeshToTangent mesh2tangent = {NULL}; SMikkTSpaceContext sContext = {NULL}; SMikkTSpaceInterface sInterface = {NULL}; - mesh2tangent.precomputedFaceNormals = fnors; - mesh2tangent.precomputedLoopNormals = tlnors; - mesh2tangent.looptri = looptri; - mesh2tangent.mloopuv = mloopuv; - mesh2tangent.mpoly = mpoly; - mesh2tangent.mloop = mloop; - mesh2tangent.mvert = mvert; - mesh2tangent.orco = orco; - mesh2tangent.tangent = tangent; - mesh2tangent.numTessFaces = totface; - -#ifdef USE_LOOPTRI_DETECT_QUADS - mesh2tangent.face_as_quad_map = face_as_quad_map; - mesh2tangent.num_face_as_quad_map = num_face_as_quad_map; -#endif - - sContext.m_pUserData = &mesh2tangent; + sContext.m_pUserData = mesh2tangent; sContext.m_pInterface = &sInterface; sInterface.m_getNumFaces = dm_ts_GetNumFaces; sInterface.m_getNumVerticesOfFace = dm_ts_GetNumVertsOfFace; @@ -3307,13 +3239,211 @@ void DM_calc_loop_tangents(DerivedMesh *dm) /* 0 if failed */ genTangSpaceDefault(&sContext); + } +} + +void DM_add_named_tangent_layer_for_uv( + CustomData *uv_data, CustomData *tan_data, int numLoopData, + const char *layer_name) +{ + if (CustomData_get_named_layer_index(tan_data, CD_TANGENT, layer_name) == -1 && + CustomData_get_named_layer_index(uv_data, CD_MLOOPUV, layer_name) != -1) + { + CustomData_add_layer_named( + tan_data, CD_TANGENT, CD_CALLOC, NULL, + numLoopData, layer_name); + } +} + +/** + * Here we get some useful information such as active uv layer name and search if it is already in tangent_names. + * Also, we calculate tangent_mask that works as a descriptor of tangents state. + * If tangent_mask has changed, then recalculate tangents. + */ +void DM_calc_loop_tangents_step_0( + const CustomData *loopData, bool calc_active_tangent, + const char (*tangent_names)[MAX_NAME], int tangent_names_count, + bool *rcalc_act, bool *rcalc_ren, int *ract_uv_n, int *rren_uv_n, + char *ract_uv_name, char *rren_uv_name, char *rtangent_mask) { + /* Active uv in viewport */ + *ract_uv_n = CustomData_get_active_layer(loopData, CD_MLOOPUV); + ract_uv_name[0] = 0; + if (*ract_uv_n != -1) { + strcpy(ract_uv_name, loopData->layers[*ract_uv_n].name); + } + + /* Active tangent in render */ + *rren_uv_n = CustomData_get_render_layer(loopData, CD_MLOOPUV); + rren_uv_name[0] = 0; + if (*rren_uv_n != -1) { + strcpy(rren_uv_name, loopData->layers[*rren_uv_n].name); + } + + /* If active tangent not in tangent_names we take it into account */ + *rcalc_act = false; + *rcalc_ren = false; + for (int i = 0; i < tangent_names_count; i++) { + if (tangent_names[i][0] == 0) { + calc_active_tangent = true; + } + } + if (calc_active_tangent) { + *rcalc_act = true; + *rcalc_ren = true; + for (int i = 0; i < tangent_names_count; i++) { + if (STREQ(ract_uv_name, tangent_names[i])) + *rcalc_act = false; + if (STREQ(rren_uv_name, tangent_names[i])) + *rcalc_ren = false; + } + } + *rtangent_mask = 0; + + const int uv_layer_num = CustomData_number_of_layers(loopData, CD_MLOOPUV); + for (int n = 0; n < uv_layer_num; n++) { + const char *name = CustomData_get_layer_name(loopData, CD_MLOOPUV, n); + bool add = false; + for (int i = 0; i < tangent_names_count; i++) { + if (tangent_names[i][0] && STREQ(tangent_names[i], name)) { + add = true; + break; + } + } + if ((*rcalc_act && ract_uv_name[0] && STREQ(ract_uv_name, name)) || + (*rcalc_ren && rren_uv_name[0] && STREQ(rren_uv_name, name))) + { + add = true; + } + if (add) + *rtangent_mask |= 1 << n; + } +} + +void DM_calc_loop_tangents( + DerivedMesh *dm, bool calc_active_tangent, + const char (*tangent_names)[MAX_NAME], int tangent_names_count) +{ + if (CustomData_number_of_layers(&dm->loopData, CD_MLOOPUV) == 0) + return; + int act_uv_n = -1; + int ren_uv_n = -1; + bool calc_act = false; + bool calc_ren = false; + char act_uv_name[MAX_NAME]; + char ren_uv_name[MAX_NAME]; + char tangent_mask = 0; + DM_calc_loop_tangents_step_0( + &dm->loopData, calc_active_tangent, tangent_names, tangent_names_count, + &calc_act, &calc_ren, &act_uv_n, &ren_uv_n, act_uv_name, ren_uv_name, &tangent_mask); + if ((dm->tangent_mask | tangent_mask) != dm->tangent_mask) { + /* Check we have all the needed layers */ + MPoly *mpoly = dm->getPolyArray(dm); + const MLoopTri *looptri = dm->getLoopTriArray(dm); + int totface = dm->getNumLoopTri(dm); + /* Allocate needed tangent layers */ + for (int i = 0; i < tangent_names_count; i++) + if (tangent_names[i][0]) + DM_add_named_tangent_layer_for_uv(&dm->loopData, &dm->loopData, dm->numLoopData, tangent_names[i]); + if (calc_act && act_uv_name[0]) + DM_add_named_tangent_layer_for_uv(&dm->loopData, &dm->loopData, dm->numLoopData, act_uv_name); + if (calc_ren && ren_uv_name[0]) + DM_add_named_tangent_layer_for_uv(&dm->loopData, &dm->loopData, dm->numLoopData, ren_uv_name); #ifdef USE_LOOPTRI_DETECT_QUADS + int num_face_as_quad_map; + int *face_as_quad_map = NULL; + + /* map faces to quads */ + if (totface != dm->getNumPolys(dm)) { + /* over alloc, since we dont know how many ngon or quads we have */ + + /* map fake face index to looptri */ + face_as_quad_map = MEM_mallocN(sizeof(int) * totface, __func__); + int k, j; + for (k = 0, j = 0; j < totface; k++, j++) { + face_as_quad_map[k] = j; + /* step over all quads */ + if (mpoly[looptri[j].poly].totloop == 4) { + j++; /* skips the nest looptri */ + } + } + num_face_as_quad_map = k; + } + else { + num_face_as_quad_map = totface; + } +#endif + + /* Calculation */ + { + TaskScheduler *scheduler = BLI_task_scheduler_get(); + TaskPool *task_pool; + task_pool = BLI_task_pool_create(scheduler, NULL); + + dm->tangent_mask = 0; + /* Calculate tangent layers */ + SGLSLMeshToTangent data_array[MAX_MTFACE]; + const int tangent_layer_num = CustomData_number_of_layers(&dm->loopData, CD_TANGENT); + for (int n = 0; n < tangent_layer_num; n++) { + int index = CustomData_get_layer_index_n(&dm->loopData, CD_TANGENT, n); + BLI_assert(n < MAX_MTFACE); + SGLSLMeshToTangent *mesh2tangent = &data_array[n]; + mesh2tangent->numTessFaces = totface; +#ifdef USE_LOOPTRI_DETECT_QUADS + mesh2tangent->face_as_quad_map = face_as_quad_map; + mesh2tangent->num_face_as_quad_map = num_face_as_quad_map; +#endif + mesh2tangent->mvert = dm->getVertArray(dm); + mesh2tangent->mpoly = dm->getPolyArray(dm); + mesh2tangent->mloop = dm->getLoopArray(dm); + mesh2tangent->looptri = dm->getLoopTriArray(dm); + /* Note, we assume we do have tessellated loop normals at this point (in case it is object-enabled), + * have to check this is valid... + */ + mesh2tangent->precomputedLoopNormals = dm->getLoopDataArray(dm, CD_NORMAL); + mesh2tangent->precomputedFaceNormals = CustomData_get_layer(&dm->faceData, CD_NORMAL); + + mesh2tangent->orco = NULL; + mesh2tangent->mloopuv = CustomData_get_layer_named(&dm->loopData, CD_MLOOPUV, dm->loopData.layers[index].name); + if (!mesh2tangent->mloopuv) { + mesh2tangent->orco = dm->getVertDataArray(dm, CD_ORCO); + if (!mesh2tangent->orco) + continue; + } + mesh2tangent->tangent = dm->loopData.layers[index].data; + + /* Fill the resulting tangent_mask */ + int uv_ind = CustomData_get_named_layer_index(&dm->loopData, CD_MLOOPUV, dm->loopData.layers[index].name); + int uv_start = CustomData_get_layer_index(&dm->loopData, CD_MLOOPUV); + BLI_assert(uv_ind != -1 && uv_start != -1); + BLI_assert(uv_ind - uv_start < MAX_MTFACE); + dm->tangent_mask |= 1 << (uv_ind - uv_start); + BLI_task_pool_push(task_pool, DM_calc_loop_tangents_thread, mesh2tangent, false, TASK_PRIORITY_LOW); + } + + BLI_assert(dm->tangent_mask == tangent_mask); + BLI_task_pool_work_and_wait(task_pool); + BLI_task_pool_free(task_pool); + } +#ifdef USE_LOOPTRI_DETECT_QUADS if (face_as_quad_map) { MEM_freeN(face_as_quad_map); } #undef USE_LOOPTRI_DETECT_QUADS + #endif + + int uv_index, tan_index; + + /* Update active layer index */ + uv_index = CustomData_get_layer_index_n(&dm->loopData, CD_MLOOPUV, act_uv_n); + tan_index = CustomData_get_named_layer_index(&dm->loopData, CD_TANGENT, dm->loopData.layers[uv_index].name); + CustomData_set_layer_active_index(&dm->loopData, CD_TANGENT, tan_index); + + /* Update render layer index */ + uv_index = CustomData_get_layer_index_n(&dm->loopData, CD_MLOOPUV, ren_uv_n); + tan_index = CustomData_get_named_layer_index(&dm->loopData, CD_TANGENT, dm->loopData.layers[uv_index].name); + CustomData_set_layer_render_index(&dm->loopData, CD_TANGENT, tan_index); } } @@ -3487,15 +3617,13 @@ void DM_vertex_attributes_from_gpu(DerivedMesh *dm, GPUVertexAttribs *gattribs, if (dm->auto_bump_scale <= 0.0f) DM_calc_auto_bump_scale(dm); - /* add a tangent layer if necessary */ - for (b = 0; b < gattribs->totlayer; b++) { - if (gattribs->layer[b].type == CD_TANGENT) { - if (CustomData_get_layer_index(&dm->loopData, CD_TANGENT) == -1) { - dm->calcLoopTangents(dm); - } - break; - } - } + char tangent_names[MAX_MTFACE][MAX_NAME]; + int tangent_names_count; + /* Add a tangent layer/layers. */ + DM_calc_tangents_names_from_gpu(gattribs, tangent_names, &tangent_names_count); + + if (tangent_names_count) + dm->calcLoopTangents(dm, false, (const char (*)[MAX_NAME])tangent_names, tangent_names_count); for (b = 0; b < gattribs->totlayer; b++) { if (gattribs->layer[b].type == CD_MTFACE) { @@ -3541,20 +3669,24 @@ void DM_vertex_attributes_from_gpu(DerivedMesh *dm, GPUVertexAttribs *gattribs, } else if (gattribs->layer[b].type == CD_TANGENT) { /* note, even with 'is_editmesh' this uses the derived-meshes loop data */ - layer = CustomData_get_layer_index(&dm->loopData, CD_TANGENT); - attribs->tottang = 1; + if (gattribs->layer[b].name[0]) + layer = CustomData_get_named_layer_index(&dm->loopData, CD_TANGENT, gattribs->layer[b].name); + else + layer = CustomData_get_active_layer_index(&dm->loopData, CD_TANGENT); + + a = attribs->tottang++; if (layer != -1) { - attribs->tang.array = dm->loopData.layers[layer].data; - attribs->tang.em_offset = dm->loopData.layers[layer].offset; + attribs->tang[a].array = dm->loopData.layers[layer].data; + attribs->tang[a].em_offset = dm->loopData.layers[layer].offset; } else { - attribs->tang.array = NULL; - attribs->tang.em_offset = -1; + attribs->tang[a].array = NULL; + attribs->tang[a].em_offset = -1; } - attribs->tang.gl_index = gattribs->layer[b].glindex; + attribs->tang[a].gl_index = gattribs->layer[b].glindex; } else if (gattribs->layer[b].type == CD_ORCO) { /* original coordinates */ @@ -3636,10 +3768,12 @@ void DM_draw_attrib_vertex(DMVertexAttribs *attribs, int a, int index, int vert, } /* tangent for normal mapping */ - if (attribs->tottang) { - /*const*/ float (*array)[4] = attribs->tang.array; - const float *tang = (array) ? array[loop] : zero; - glVertexAttrib4fv(attribs->tang.gl_index, tang); + for (b = 0; b < attribs->tottang; b++) { + if (attribs->tang[b].array) { + /*const*/ float (*array)[4] = attribs->tang[b].array; + const float *tang = (array) ? array[a * 4 + vert] : zero; + glVertexAttrib4fv(attribs->tang[b].gl_index, tang); + } } } diff --git a/source/blender/blenkernel/intern/action.c b/source/blender/blenkernel/intern/action.c index 3e1cf6a74a4..5b1bb8cb2bb 100644 --- a/source/blender/blenkernel/intern/action.c +++ b/source/blender/blenkernel/intern/action.c @@ -1414,6 +1414,12 @@ void what_does_obaction(Object *ob, Object *workob, bPose *pose, bAction *act, c 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) { + BKE_pose_channels_hash_make(pose); + if (pose->flag & POSE_CONSTRAINTS_NEED_UPDATE_FLAGS) { + BKE_pose_update_constraint_flags(pose); + } + } 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 */ diff --git a/source/blender/blenkernel/intern/appdir.c b/source/blender/blenkernel/intern/appdir.c index de21d9105e2..b1dcc40279f 100644 --- a/source/blender/blenkernel/intern/appdir.c +++ b/source/blender/blenkernel/intern/appdir.c @@ -32,7 +32,7 @@ #include "BLI_fileops.h" #include "BLI_path_util.h" -#include "BKE_blender.h" /* BLENDER_VERSION */ +#include "BKE_blender_version.h" #include "BKE_appdir.h" /* own include */ #include "GHOST_Path-api.h" diff --git a/source/blender/blenkernel/intern/armature.c b/source/blender/blenkernel/intern/armature.c index 54fe98940aa..564c670fb3a 100644 --- a/source/blender/blenkernel/intern/armature.c +++ b/source/blender/blenkernel/intern/armature.c @@ -633,7 +633,7 @@ typedef struct bPoseChanDeform { DualQuat *b_bone_dual_quats; } bPoseChanDeform; -static void pchan_b_bone_defmats(bPoseChannel *pchan, bPoseChanDeform *pdef_info, int use_quaternion) +static void pchan_b_bone_defmats(bPoseChannel *pchan, bPoseChanDeform *pdef_info, const bool use_quaternion) { Bone *bone = pchan->bone; Mat4 b_bone[MAX_BBONE_SUBDIV], b_bone_rest[MAX_BBONE_SUBDIV]; @@ -867,16 +867,19 @@ void armature_deform_verts(Object *armOb, Object *target, DerivedMesh *dm, float bDeformGroup *dg; DualQuat *dualquats = NULL; float obinv[4][4], premat[4][4], postmat[4][4]; - const short use_envelope = deformflag & ARM_DEF_ENVELOPE; - const short use_quaternion = deformflag & ARM_DEF_QUATERNION; - const short invert_vgroup = deformflag & ARM_DEF_INVERT_VGROUP; + const bool use_envelope = (deformflag & ARM_DEF_ENVELOPE) != 0; + const bool use_quaternion = (deformflag & ARM_DEF_QUATERNION) != 0; + const bool invert_vgroup = (deformflag & ARM_DEF_INVERT_VGROUP) != 0; int defbase_tot = 0; /* safety for vertexgroup index overflow */ int i, target_totvert = 0; /* safety for vertexgroup overflow */ bool use_dverts = false; int armature_def_nr; int totchan; - if (arm->edbo) return; + /* in editmode, or not an armature */ + if (arm->edbo || (armOb->pose == NULL)) { + return; + } invert_m4_m4(obinv, target->obmat); copy_m4_m4(premat, target->obmat); diff --git a/source/blender/blenkernel/intern/blender.c b/source/blender/blenkernel/intern/blender.c index baf93ffd824..15492fbd20d 100644 --- a/source/blender/blenkernel/intern/blender.c +++ b/source/blender/blenkernel/intern/blender.c @@ -27,89 +27,55 @@ /** \file blender/blenkernel/intern/blender.c * \ingroup bke + * + * Application level startup/shutdown functionality. */ -#ifndef _GNU_SOURCE -/* Needed for O_NOFOLLOW on some platforms. */ -# define _GNU_SOURCE 1 -#endif - -#ifndef _WIN32 -# include <unistd.h> // for read close -#else -# include <io.h> // for open close read -#endif - #include <stdlib.h> #include <stdio.h> -#include <stddef.h> #include <string.h> -#include <fcntl.h> /* for open */ -#include <errno.h> #include "MEM_guardedalloc.h" -#include "DNA_userdef_types.h" -#include "DNA_scene_types.h" -#include "DNA_screen_types.h" -#include "DNA_view3d_types.h" -#include "DNA_windowmanager_types.h" - -#include "BLI_blenlib.h" +#include "BLI_string.h" +#include "BLI_listbase.h" #include "BLI_utildefines.h" #include "BLI_callbacks.h" #include "IMB_imbuf.h" #include "IMB_moviecache.h" -#include "BKE_appdir.h" -#include "BKE_blender.h" -#include "BKE_bpath.h" +#include "BKE_blender.h" /* own include */ +#include "BKE_blender_version.h" /* own include */ +#include "BKE_blendfile.h" #include "BKE_brush.h" #include "BKE_context.h" #include "BKE_depsgraph.h" #include "BKE_global.h" #include "BKE_idprop.h" #include "BKE_image.h" -#include "BKE_ipo.h" #include "BKE_library.h" -#include "BKE_main.h" #include "BKE_node.h" #include "BKE_report.h" #include "BKE_scene.h" #include "BKE_screen.h" #include "BKE_sequencer.h" -#include "BKE_sound.h" #include "RE_pipeline.h" #include "RE_render_ext.h" #include "BLF_api.h" -#include "BLO_undofile.h" -#include "BLO_readfile.h" -#include "BLO_writefile.h" - -#include "RNA_access.h" - -#include "WM_api.h" // XXXXX BAD, very BAD dependency (bad level call) - remove asap, elubie - -#include "IMB_colormanagement.h" - -#ifdef WITH_PYTHON -# include "BPY_extern.h" -#endif Global G; UserDef U; -/* ListBase = {NULL, NULL}; */ char versionstr[48] = ""; /* ********** free ********** */ /* only to be called on exit blender */ -void free_blender(void) +void BKE_blender_free(void) { /* samples are in a global list..., also sets G.main->sound->sample NULL */ BKE_main_free(G.main); @@ -132,7 +98,7 @@ void free_blender(void) free_nodesystem(); } -void initglobals(void) +void BKE_blender_globals_init(void) { memset(&G, 0, sizeof(Global)); @@ -154,300 +120,14 @@ void initglobals(void) #endif } -/***/ - -static void clear_global(void) +void BKE_blender_globals_clear(void) { -// extern short winqueue_break; /* screen.c */ - BKE_main_free(G.main); /* free all lib data */ - -// free_vertexpaint(); G.main = NULL; } -static bool clean_paths_visit_cb(void *UNUSED(userdata), char *path_dst, const char *path_src) -{ - strcpy(path_dst, path_src); - BLI_path_native_slash(path_dst); - return !STREQ(path_dst, path_src); -} - -/* make sure path names are correct for OS */ -static void clean_paths(Main *main) -{ - Scene *scene; - - BKE_bpath_traverse_main(main, clean_paths_visit_cb, BKE_BPATH_TRAVERSE_SKIP_MULTIFILE, NULL); - - for (scene = main->scene.first; scene; scene = scene->id.next) { - BLI_path_native_slash(scene->r.pic); - } -} - -static bool wm_scene_is_visible(wmWindowManager *wm, Scene *scene) -{ - wmWindow *win; - for (win = wm->windows.first; win; win = win->next) { - if (win->screen->scene == scene) { - return true; - } - } - return false; -} - -/** - * Context matching, handle no-ui case - * - * \note this is called on Undo so any slow conversion functions here - * should be avoided or check (mode != LOAD_UNDO). - * - * \param bfd: Blend file data, freed by this function on exit. - * \param filepath: File path or identifier. - */ -static void setup_app_data( - bContext *C, BlendFileData *bfd, - const char *filepath, ReportList *reports) -{ - Scene *curscene = NULL; - const bool recover = (G.fileflags & G_FILE_RECOVER) != 0; - enum { - LOAD_UI = 1, - LOAD_UI_OFF, - LOAD_UNDO, - } mode; - - if (BLI_listbase_is_empty(&bfd->main->screen)) { - mode = LOAD_UNDO; - } - else if (G.fileflags & G_FILE_NO_UI) { - mode = LOAD_UI_OFF; - } - else { - mode = LOAD_UI; - } - - if (mode != LOAD_UNDO) { - /* may happen with library files */ - if (ELEM(NULL, bfd->curscreen, bfd->curscene)) { - BKE_report(reports, RPT_WARNING, "Library file, loading empty scene"); - mode = LOAD_UI_OFF; - } - } - - /* Free all render results, without this stale data gets displayed after loading files */ - if (mode != LOAD_UNDO) { - RE_FreeAllRenderResults(); - } - - /* Only make filepaths compatible when loading for real (not undo) */ - if (mode != LOAD_UNDO) { - clean_paths(bfd->main); - } - - /* XXX here the complex windowmanager matching */ - - /* no load screens? */ - if (mode != LOAD_UI) { - /* Logic for 'track_undo_scene' is to keep using the scene which the active screen has, - * as long as the scene associated with the undo operation is visible in one of the open windows. - * - * - 'curscreen->scene' - scene the user is currently looking at. - * - 'bfd->curscene' - scene undo-step was created in. - * - * This means users can have 2+ windows open and undo in both without screens switching. - * But if they close one of the screens, - * undo will ensure that the scene being operated on will be activated - * (otherwise we'd be undoing on an off-screen scene which isn't acceptable). - * see: T43424 - */ - bScreen *curscreen = NULL; - bool track_undo_scene; - - /* comes from readfile.c */ - SWAP(ListBase, G.main->wm, bfd->main->wm); - SWAP(ListBase, G.main->screen, bfd->main->screen); - - /* we re-use current screen */ - curscreen = CTX_wm_screen(C); - /* but use new Scene pointer */ - curscene = bfd->curscene; - - track_undo_scene = (mode == LOAD_UNDO && curscreen && curscene && bfd->main->wm.first); - - if (curscene == NULL) { - curscene = bfd->main->scene.first; - } - /* empty file, we add a scene to make Blender work */ - if (curscene == NULL) { - curscene = BKE_scene_add(bfd->main, "Empty"); - } - - if (track_undo_scene) { - /* keep the old (free'd) scene, let 'blo_lib_link_screen_restore' - * replace it with 'curscene' if its needed */ - } - else { - /* and we enforce curscene to be in current screen */ - if (curscreen) { - /* can run in bgmode */ - curscreen->scene = curscene; - } - } - - /* clear_global will free G.main, here we can still restore pointers */ - blo_lib_link_screen_restore(bfd->main, curscreen, curscene); - /* curscreen might not be set when loading without ui (see T44217) so only re-assign if available */ - if (curscreen) { - curscene = curscreen->scene; - } - - if (track_undo_scene) { - wmWindowManager *wm = bfd->main->wm.first; - if (wm_scene_is_visible(wm, bfd->curscene) == false) { - curscene = bfd->curscene; - curscreen->scene = curscene; - BKE_screen_view3d_scene_sync(curscreen); - } - } - } - - /* free G.main Main database */ -// CTX_wm_manager_set(C, NULL); - clear_global(); - - /* clear old property update cache, in case some old references are left dangling */ - RNA_property_update_cache_free(); - - G.main = bfd->main; - - CTX_data_main_set(C, G.main); - - if (bfd->user) { - - /* only here free userdef themes... */ - BKE_userdef_free(); - - U = *bfd->user; - - /* Security issue: any blend file could include a USER block. - * - * Currently we load prefs from BLENDER_STARTUP_FILE and later on load BLENDER_USERPREF_FILE, - * to load the preferences defined in the users home dir. - * - * This means we will never accidentally (or maliciously) - * enable scripts auto-execution by loading a '.blend' file. - */ - U.flag |= USER_SCRIPT_AUTOEXEC_DISABLE; - - MEM_freeN(bfd->user); - } - - /* case G_FILE_NO_UI or no screens in file */ - if (mode != LOAD_UI) { - /* leave entire context further unaltered? */ - CTX_data_scene_set(C, curscene); - } - else { - G.fileflags = bfd->fileflags; - CTX_wm_manager_set(C, G.main->wm.first); - CTX_wm_screen_set(C, bfd->curscreen); - CTX_data_scene_set(C, bfd->curscene); - CTX_wm_area_set(C, NULL); - CTX_wm_region_set(C, NULL); - CTX_wm_menu_set(C, NULL); - curscene = bfd->curscene; - } - - /* this can happen when active scene was lib-linked, and doesn't exist anymore */ - if (CTX_data_scene(C) == NULL) { - /* in case we don't even have a local scene, add one */ - if (!G.main->scene.first) - BKE_scene_add(G.main, "Empty"); - - CTX_data_scene_set(C, G.main->scene.first); - CTX_wm_screen(C)->scene = CTX_data_scene(C); - curscene = CTX_data_scene(C); - } - - BLI_assert(curscene == CTX_data_scene(C)); - - - /* special cases, override loaded flags: */ - if (G.f != bfd->globalf) { - const int flags_keep = (G_SWAP_EXCHANGE | G_SCRIPT_AUTOEXEC | G_SCRIPT_OVERRIDE_PREF); - bfd->globalf = (bfd->globalf & ~flags_keep) | (G.f & flags_keep); - } - - - G.f = bfd->globalf; - -#ifdef WITH_PYTHON - /* let python know about new main */ - BPY_context_update(C); -#endif - - /* FIXME: this version patching should really be part of the file-reading code, - * but we still get too many unrelated data-corruption crashes otherwise... */ - if (G.main->versionfile < 250) - do_versions_ipos_to_animato(G.main); - - G.main->recovered = 0; - - /* startup.blend or recovered startup */ - if (bfd->filename[0] == 0) { - G.main->name[0] = 0; - } - else if (recover && G.relbase_valid) { - /* in case of autosave or quit.blend, use original filename instead - * use relbase_valid to make sure the file is saved, else we get <memory2> in the filename */ - filepath = bfd->filename; - G.main->recovered = 1; - - /* these are the same at times, should never copy to the same location */ - if (G.main->name != filepath) - BLI_strncpy(G.main->name, filepath, FILE_MAX); - } - - /* baseflags, groups, make depsgraph, etc */ - /* first handle case if other windows have different scenes visible */ - if (mode == LOAD_UI) { - wmWindowManager *wm = G.main->wm.first; - - if (wm) { - wmWindow *win; - - for (win = wm->windows.first; win; win = win->next) { - if (win->screen && win->screen->scene) /* zealous check... */ - if (win->screen->scene != curscene) - BKE_scene_set_background(G.main, win->screen->scene); - } - } - } - BKE_scene_set_background(G.main, curscene); - - if (mode != LOAD_UNDO) { - RE_FreeAllPersistentData(); - IMB_colormanagement_check_file_config(G.main); - } - - MEM_freeN(bfd); - -} - -static int handle_subversion_warning(Main *main, ReportList *reports) -{ - if (main->minversionfile > BLENDER_VERSION || - (main->minversionfile == BLENDER_VERSION && - main->minsubversionfile > BLENDER_SUBVERSION)) - { - BKE_reportf(reports, RPT_ERROR, "File written by newer Blender binary (%d.%d), expect loss of data!", - main->minversionfile, main->minsubversionfile); - } - - return 1; -} +/***/ static void keymap_item_free(wmKeyMapItem *kmi) { @@ -459,7 +139,11 @@ static void keymap_item_free(wmKeyMapItem *kmi) MEM_freeN(kmi->ptr); } -void BKE_userdef_free(void) +/** + * When loading a new userdef from file, + * or when exiting Blender. + */ +void BKE_blender_userdef_free(void) { wmKeyMap *km; wmKeyMapItem *kmi; @@ -509,8 +193,10 @@ void BKE_userdef_free(void) BLI_freelistN(&U.user_keymaps); } -/* handle changes in settings that need recalc */ -void BKE_userdef_state(void) +/** + * Handle changes in settings that need refreshing. + */ +void BKE_blender_userdef_refresh(void) { /* prevent accidents */ if (U.pixelsize == 0) U.pixelsize = 1; @@ -520,116 +206,6 @@ void BKE_userdef_state(void) } -int BKE_read_file(bContext *C, const char *filepath, ReportList *reports) -{ - BlendFileData *bfd; - int retval = BKE_READ_FILE_OK; - - if (strstr(filepath, BLENDER_STARTUP_FILE) == NULL) /* don't print user-pref loading */ - printf("read blend: %s\n", filepath); - - bfd = BLO_read_from_file(filepath, reports); - if (bfd) { - if (bfd->user) retval = BKE_READ_FILE_OK_USERPREFS; - - if (0 == handle_subversion_warning(bfd->main, reports)) { - BKE_main_free(bfd->main); - MEM_freeN(bfd); - bfd = NULL; - retval = BKE_READ_FILE_FAIL; - } - else { - setup_app_data(C, bfd, filepath, reports); - } - } - else - BKE_reports_prependf(reports, "Loading '%s' failed: ", filepath); - - return (bfd ? retval : BKE_READ_FILE_FAIL); -} - -bool BKE_read_file_from_memory( - bContext *C, const void *filebuf, int filelength, - ReportList *reports, bool update_defaults) -{ - BlendFileData *bfd; - - bfd = BLO_read_from_memory(filebuf, filelength, reports); - if (bfd) { - if (update_defaults) - BLO_update_defaults_startup_blend(bfd->main); - setup_app_data(C, bfd, "<memory2>", reports); - } - else { - BKE_reports_prepend(reports, "Loading failed: "); - } - - return (bfd != NULL); -} - -/* memfile is the undo buffer */ -bool BKE_read_file_from_memfile( - bContext *C, MemFile *memfile, - ReportList *reports) -{ - BlendFileData *bfd; - - bfd = BLO_read_from_memfile(CTX_data_main(C), G.main->name, memfile, reports); - if (bfd) { - /* remove the unused screens and wm */ - while (bfd->main->wm.first) - BKE_libblock_free_ex(bfd->main, bfd->main->wm.first, true); - while (bfd->main->screen.first) - BKE_libblock_free_ex(bfd->main, bfd->main->screen.first, true); - - setup_app_data(C, bfd, "<memory1>", reports); - } - else { - BKE_reports_prepend(reports, "Loading failed: "); - } - - return (bfd != NULL); -} - -/* only read the userdef from a .blend */ -int BKE_read_file_userdef(const char *filepath, ReportList *reports) -{ - BlendFileData *bfd; - int retval = BKE_READ_FILE_FAIL; - - bfd = BLO_read_from_file(filepath, reports); - if (bfd) { - if (bfd->user) { - retval = BKE_READ_FILE_OK_USERPREFS; - - /* only here free userdef themes... */ - BKE_userdef_free(); - - U = *bfd->user; - MEM_freeN(bfd->user); - } - BKE_main_free(bfd->main); - MEM_freeN(bfd); - } - - return retval; -} - -/* only write the userdef in a .blend */ -int BKE_write_file_userdef(const char *filepath, ReportList *reports) -{ - Main *mainb = MEM_callocN(sizeof(Main), "empty main"); - int retval = 0; - - if (BLO_write_file(mainb, filepath, G_FILE_USERPREFS, reports, NULL)) { - retval = 1; - } - - MEM_freeN(mainb); - - return retval; -} - /* ***************** testing for break ************* */ static void (*blender_test_break_cb)(void) = NULL; @@ -640,7 +216,7 @@ void BKE_blender_callback_test_break_set(void (*func)(void)) } -int blender_test_break(void) +int BKE_blender_test_break(void) { if (!G.background) { if (blender_test_break_cb) @@ -650,514 +226,3 @@ int blender_test_break(void) return (G.is_break == true); } - -/* -------------------------------------------------------------------- */ - -/** \name Global Undo - * \{ */ - -#define UNDO_DISK 0 - -typedef struct UndoElem { - struct UndoElem *next, *prev; - char str[FILE_MAX]; - char name[BKE_UNDO_STR_MAX]; - MemFile memfile; - uintptr_t undosize; -} UndoElem; - -static ListBase undobase = {NULL, NULL}; -static UndoElem *curundo = NULL; - - -static int read_undosave(bContext *C, UndoElem *uel) -{ - char mainstr[sizeof(G.main->name)]; - int success = 0, fileflags; - - /* This is needed so undoing/redoing doesn't crash with threaded previews going */ - WM_jobs_kill_all_except(CTX_wm_manager(C), CTX_wm_screen(C)); - - BLI_strncpy(mainstr, G.main->name, sizeof(mainstr)); /* temporal store */ - - fileflags = G.fileflags; - G.fileflags |= G_FILE_NO_UI; - - if (UNDO_DISK) - success = (BKE_read_file(C, uel->str, NULL) != BKE_READ_FILE_FAIL); - else - success = BKE_read_file_from_memfile(C, &uel->memfile, NULL); - - /* restore */ - BLI_strncpy(G.main->name, mainstr, sizeof(G.main->name)); /* restore */ - G.fileflags = fileflags; - - if (success) { - /* important not to update time here, else non keyed tranforms are lost */ - DAG_on_visible_update(G.main, false); - } - - return success; -} - -/* name can be a dynamic string */ -void BKE_undo_write(bContext *C, const char *name) -{ - uintptr_t maxmem, totmem, memused; - int nr /*, success */ /* UNUSED */; - UndoElem *uel; - - if ((U.uiflag & USER_GLOBALUNDO) == 0) { - return; - } - - if (U.undosteps == 0) { - return; - } - - /* remove all undos after (also when curundo == NULL) */ - while (undobase.last != curundo) { - uel = undobase.last; - BLI_remlink(&undobase, uel); - BLO_memfile_free(&uel->memfile); - MEM_freeN(uel); - } - - /* make new */ - curundo = uel = MEM_callocN(sizeof(UndoElem), "undo file"); - BLI_strncpy(uel->name, name, sizeof(uel->name)); - BLI_addtail(&undobase, uel); - - /* and limit amount to the maximum */ - nr = 0; - uel = undobase.last; - while (uel) { - nr++; - if (nr == U.undosteps) break; - uel = uel->prev; - } - if (uel) { - while (undobase.first != uel) { - UndoElem *first = undobase.first; - BLI_remlink(&undobase, first); - /* the merge is because of compression */ - BLO_memfile_merge(&first->memfile, &first->next->memfile); - MEM_freeN(first); - } - } - - - /* disk save version */ - if (UNDO_DISK) { - static int counter = 0; - char filepath[FILE_MAX]; - char numstr[32]; - int fileflags = G.fileflags & ~(G_FILE_HISTORY); /* don't do file history on undo */ - - /* calculate current filepath */ - counter++; - counter = counter % U.undosteps; - - BLI_snprintf(numstr, sizeof(numstr), "%d.blend", counter); - BLI_make_file_string("/", filepath, BKE_tempdir_session(), numstr); - - /* success = */ /* UNUSED */ BLO_write_file(CTX_data_main(C), filepath, fileflags, NULL, NULL); - - BLI_strncpy(curundo->str, filepath, sizeof(curundo->str)); - } - else { - MemFile *prevfile = NULL; - - if (curundo->prev) prevfile = &(curundo->prev->memfile); - - memused = MEM_get_memory_in_use(); - /* success = */ /* UNUSED */ BLO_write_file_mem(CTX_data_main(C), prevfile, &curundo->memfile, G.fileflags); - curundo->undosize = MEM_get_memory_in_use() - memused; - } - - if (U.undomemory != 0) { - /* limit to maximum memory (afterwards, we can't know in advance) */ - totmem = 0; - maxmem = ((uintptr_t)U.undomemory) * 1024 * 1024; - - /* keep at least two (original + other) */ - uel = undobase.last; - while (uel && uel->prev) { - totmem += uel->undosize; - if (totmem > maxmem) break; - uel = uel->prev; - } - - if (uel) { - if (uel->prev && uel->prev->prev) - uel = uel->prev; - - while (undobase.first != uel) { - UndoElem *first = undobase.first; - BLI_remlink(&undobase, first); - /* the merge is because of compression */ - BLO_memfile_merge(&first->memfile, &first->next->memfile); - MEM_freeN(first); - } - } - } -} - -/* 1 = an undo, -1 is a redo. we have to make sure 'curundo' remains at current situation */ -void BKE_undo_step(bContext *C, int step) -{ - - if (step == 0) { - read_undosave(C, curundo); - } - else if (step == 1) { - /* curundo should never be NULL, after restart or load file it should call undo_save */ - if (curundo == NULL || curundo->prev == NULL) { - // XXX error("No undo available"); - } - else { - if (G.debug & G_DEBUG) printf("undo %s\n", curundo->name); - curundo = curundo->prev; - read_undosave(C, curundo); - } - } - else { - /* curundo has to remain current situation! */ - - if (curundo == NULL || curundo->next == NULL) { - // XXX error("No redo available"); - } - else { - read_undosave(C, curundo->next); - curundo = curundo->next; - if (G.debug & G_DEBUG) printf("redo %s\n", curundo->name); - } - } -} - -void BKE_undo_reset(void) -{ - UndoElem *uel; - - uel = undobase.first; - while (uel) { - BLO_memfile_free(&uel->memfile); - uel = uel->next; - } - - BLI_freelistN(&undobase); - curundo = NULL; -} - -/* based on index nr it does a restore */ -void BKE_undo_number(bContext *C, int nr) -{ - curundo = BLI_findlink(&undobase, nr); - BKE_undo_step(C, 0); -} - -/* go back to the last occurance of name in stack */ -void BKE_undo_name(bContext *C, const char *name) -{ - UndoElem *uel = BLI_rfindstring(&undobase, name, offsetof(UndoElem, name)); - - if (uel && uel->prev) { - curundo = uel->prev; - BKE_undo_step(C, 0); - } -} - -/* name optional */ -bool BKE_undo_is_valid(const char *name) -{ - if (name) { - UndoElem *uel = BLI_rfindstring(&undobase, name, offsetof(UndoElem, name)); - return uel && uel->prev; - } - - return undobase.last != undobase.first; -} - -/* get name of undo item, return null if no item with this index */ -/* if active pointer, set it to 1 if true */ -const char *BKE_undo_get_name(int nr, bool *r_active) -{ - UndoElem *uel = BLI_findlink(&undobase, nr); - - if (r_active) *r_active = false; - - if (uel) { - if (r_active && (uel == curundo)) { - *r_active = true; - } - return uel->name; - } - return NULL; -} - -/** - * Saves .blend using undo buffer. - * - * \return success. - */ -bool BKE_undo_save_file(const char *filename) -{ - UndoElem *uel; - MemFileChunk *chunk; - int file, oflags; - - if ((U.uiflag & USER_GLOBALUNDO) == 0) { - return false; - } - - uel = curundo; - if (uel == NULL) { - fprintf(stderr, "No undo buffer to save recovery file\n"); - return false; - } - - /* note: This is currently used for autosave and 'quit.blend', where _not_ following symlinks is OK, - * however if this is ever executed explicitly by the user, we may want to allow writing to symlinks. - */ - - oflags = O_BINARY | O_WRONLY | O_CREAT | O_TRUNC; -#ifdef O_NOFOLLOW - /* use O_NOFOLLOW to avoid writing to a symlink - use 'O_EXCL' (CVE-2008-1103) */ - oflags |= O_NOFOLLOW; -#else - /* TODO(sergey): How to deal with symlinks on windows? */ -# ifndef _MSC_VER -# warning "Symbolic links will be followed on undo save, possibly causing CVE-2008-1103" -# endif -#endif - file = BLI_open(filename, oflags, 0666); - - if (file == -1) { - fprintf(stderr, "Unable to save '%s': %s\n", - filename, errno ? strerror(errno) : "Unknown error opening file"); - return false; - } - - for (chunk = uel->memfile.chunks.first; chunk; chunk = chunk->next) { - if (write(file, chunk->buf, chunk->size) != chunk->size) { - break; - } - } - - close(file); - - if (chunk) { - fprintf(stderr, "Unable to save '%s': %s\n", - filename, errno ? strerror(errno) : "Unknown error writing file"); - return false; - } - return true; -} - -/* sets curscene */ -Main *BKE_undo_get_main(Scene **r_scene) -{ - Main *mainp = NULL; - BlendFileData *bfd = BLO_read_from_memfile(G.main, G.main->name, &curundo->memfile, NULL); - - if (bfd) { - mainp = bfd->main; - if (r_scene) { - *r_scene = bfd->curscene; - } - - MEM_freeN(bfd); - } - - return mainp; -} - -/** \} */ - - -/* -------------------------------------------------------------------- */ - -/** \name Partial `.blend` file save. - * \{ */ - -void BKE_blendfile_write_partial_begin(Main *bmain_src) -{ - BKE_main_id_tag_all(bmain_src, LIB_TAG_NEED_EXPAND | LIB_TAG_DOIT, false); -} - -void BKE_blendfile_write_partial_tag_ID(ID *id, bool set) -{ - if (set) { - id->tag |= LIB_TAG_NEED_EXPAND | LIB_TAG_DOIT; - } - else { - id->tag &= ~(LIB_TAG_NEED_EXPAND | LIB_TAG_DOIT); - } -} - -static void blendfile_write_partial_cb(void *UNUSED(handle), Main *UNUSED(bmain), void *vid) -{ - if (vid) { - ID *id = vid; - /* only tag for need-expand if not done, prevents eternal loops */ - if ((id->tag & LIB_TAG_DOIT) == 0) - id->tag |= LIB_TAG_NEED_EXPAND | LIB_TAG_DOIT; - } -} - -/** - * \return Success. - */ -bool BKE_blendfile_write_partial( - Main *bmain_src, const char *filepath, const int write_flags, ReportList *reports) -{ - Main *bmain_dst = MEM_callocN(sizeof(Main), "copybuffer"); - ListBase *lbarray_dst[MAX_LIBARRAY], *lbarray_src[MAX_LIBARRAY]; - int a, retval; - - void *path_list_backup = NULL; - const int path_list_flag = (BKE_BPATH_TRAVERSE_SKIP_LIBRARY | BKE_BPATH_TRAVERSE_SKIP_MULTIFILE); - - if (write_flags & G_FILE_RELATIVE_REMAP) { - path_list_backup = BKE_bpath_list_backup(bmain_src, path_list_flag); - } - - BLO_main_expander(blendfile_write_partial_cb); - BLO_expand_main(NULL, bmain_src); - - /* move over all tagged blocks */ - set_listbasepointers(bmain_src, lbarray_src); - a = set_listbasepointers(bmain_dst, lbarray_dst); - while (a--) { - ID *id, *nextid; - ListBase *lb_dst = lbarray_dst[a], *lb_src = lbarray_src[a]; - - for (id = lb_src->first; id; id = nextid) { - nextid = id->next; - if (id->tag & LIB_TAG_DOIT) { - BLI_remlink(lb_src, id); - BLI_addtail(lb_dst, id); - } - } - } - - - /* save the buffer */ - retval = BLO_write_file(bmain_dst, filepath, write_flags, reports, NULL); - - /* move back the main, now sorted again */ - set_listbasepointers(bmain_src, lbarray_dst); - a = set_listbasepointers(bmain_dst, lbarray_src); - while (a--) { - ID *id; - ListBase *lb_dst = lbarray_dst[a], *lb_src = lbarray_src[a]; - - while ((id = BLI_pophead(lb_src))) { - BLI_addtail(lb_dst, id); - id_sort_by_name(lb_dst, id); - } - } - - MEM_freeN(bmain_dst); - - if (path_list_backup) { - BKE_bpath_list_restore(bmain_src, path_list_flag, path_list_backup); - BKE_bpath_list_free(path_list_backup); - } - - return retval; -} - -void BKE_blendfile_write_partial_end(Main *bmain_src) -{ - BKE_main_id_tag_all(bmain_src, LIB_TAG_NEED_EXPAND | LIB_TAG_DOIT, false); -} - -/** \} */ - - -/* -------------------------------------------------------------------- */ - -/** \name Copy/Paste `.blend`, partial saves. - * \{ */ - -void BKE_copybuffer_begin(Main *bmain_src) -{ - BKE_blendfile_write_partial_begin(bmain_src); -} - -void BKE_copybuffer_tag_ID(ID *id) -{ - BKE_blendfile_write_partial_tag_ID(id, true); -} - -/** - * \return Success. - */ -bool BKE_copybuffer_save(Main *bmain_src, const char *filename, ReportList *reports) -{ - const int write_flags = G_FILE_RELATIVE_REMAP; - - bool retval = BKE_blendfile_write_partial(bmain_src, filename, write_flags, reports); - - BKE_blendfile_write_partial_end(bmain_src); - - return retval; -} - -/** - * \return Success. - */ -bool BKE_copybuffer_paste(bContext *C, const char *libname, const short flag, ReportList *reports) -{ - Main *bmain = CTX_data_main(C); - Scene *scene = CTX_data_scene(C); - View3D *v3d = CTX_wm_view3d(C); - Main *mainl = NULL; - Library *lib; - BlendHandle *bh; - - bh = BLO_blendhandle_from_file(libname, reports); - - if (bh == NULL) { - /* error reports will have been made by BLO_blendhandle_from_file() */ - return false; - } - - BKE_scene_base_deselect_all(scene); - - /* tag everything, all untagged data can be made local - * its also generally useful to know what is new - * - * take extra care BKE_main_id_flag_all(bmain, LIB_TAG_PRE_EXISTING, false) is called after! */ - BKE_main_id_tag_all(bmain, LIB_TAG_PRE_EXISTING, true); - - /* here appending/linking starts */ - mainl = BLO_library_link_begin(bmain, &bh, libname); - - BLO_library_link_copypaste(mainl, bh); - - BLO_library_link_end(mainl, &bh, flag, scene, v3d); - - /* mark all library linked objects to be updated */ - BKE_main_lib_objects_recalc_all(bmain); - IMB_colormanagement_check_file_config(bmain); - - /* append, rather than linking */ - lib = BLI_findstring(&bmain->library, libname, offsetof(Library, filepath)); - BKE_library_make_local(bmain, lib, true, false); - - /* important we unset, otherwise these object wont - * link into other scenes from this blend file */ - BKE_main_id_tag_all(bmain, LIB_TAG_PRE_EXISTING, false); - - /* recreate dependency graph to include new objects */ - DAG_relations_tag_update(bmain); - - BLO_blendhandle_close(bh); - /* remove library... */ - - return true; -} - -/** \} */ diff --git a/source/blender/blenkernel/intern/blender_copybuffer.c b/source/blender/blenkernel/intern/blender_copybuffer.c new file mode 100644 index 00000000000..ad01fac2144 --- /dev/null +++ b/source/blender/blenkernel/intern/blender_copybuffer.c @@ -0,0 +1,143 @@ +/* + * ***** 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. + * + * ***** END GPL LICENSE BLOCK ***** + */ + +/** \file blender/blenkernel/intern/blender_copybuffer.c + * \ingroup bke + * + * Used for copy/paste operator, (using a temporary file). + */ + +#include <stdlib.h> + +#include "MEM_guardedalloc.h" + +#include "DNA_userdef_types.h" +#include "DNA_scene_types.h" +#include "DNA_screen_types.h" +#include "DNA_view3d_types.h" +#include "DNA_windowmanager_types.h" + +#include "BLI_blenlib.h" +#include "BLI_utildefines.h" +#include "BLI_callbacks.h" + +#include "IMB_imbuf.h" +#include "IMB_moviecache.h" + +#include "BKE_blender_copybuffer.h" /* own include */ +#include "BKE_blendfile.h" +#include "BKE_context.h" +#include "BKE_depsgraph.h" +#include "BKE_global.h" +#include "BKE_library.h" +#include "BKE_main.h" +#include "BKE_scene.h" + +#include "BLO_readfile.h" +#include "BLO_writefile.h" + +#include "IMB_colormanagement.h" + + +/* -------------------------------------------------------------------- */ + +/** \name Copy/Paste `.blend`, partial saves. + * \{ */ + +void BKE_copybuffer_begin(Main *bmain_src) +{ + BKE_blendfile_write_partial_begin(bmain_src); +} + +void BKE_copybuffer_tag_ID(ID *id) +{ + BKE_blendfile_write_partial_tag_ID(id, true); +} + +/** + * \return Success. + */ +bool BKE_copybuffer_save(Main *bmain_src, const char *filename, ReportList *reports) +{ + const int write_flags = G_FILE_RELATIVE_REMAP; + + bool retval = BKE_blendfile_write_partial(bmain_src, filename, write_flags, reports); + + BKE_blendfile_write_partial_end(bmain_src); + + return retval; +} + +/** + * \return Success. + */ +bool BKE_copybuffer_paste(bContext *C, const char *libname, const short flag, ReportList *reports) +{ + Main *bmain = CTX_data_main(C); + Scene *scene = CTX_data_scene(C); + View3D *v3d = CTX_wm_view3d(C); + Main *mainl = NULL; + Library *lib; + BlendHandle *bh; + + bh = BLO_blendhandle_from_file(libname, reports); + + if (bh == NULL) { + /* error reports will have been made by BLO_blendhandle_from_file() */ + return false; + } + + BKE_scene_base_deselect_all(scene); + + /* tag everything, all untagged data can be made local + * its also generally useful to know what is new + * + * take extra care BKE_main_id_flag_all(bmain, LIB_TAG_PRE_EXISTING, false) is called after! */ + BKE_main_id_tag_all(bmain, LIB_TAG_PRE_EXISTING, true); + + /* here appending/linking starts */ + mainl = BLO_library_link_begin(bmain, &bh, libname); + + BLO_library_link_copypaste(mainl, bh); + + BLO_library_link_end(mainl, &bh, flag, scene, v3d); + + /* mark all library linked objects to be updated */ + BKE_main_lib_objects_recalc_all(bmain); + IMB_colormanagement_check_file_config(bmain); + + /* append, rather than linking */ + lib = BLI_findstring(&bmain->library, libname, offsetof(Library, filepath)); + BKE_library_make_local(bmain, lib, true, false); + + /* important we unset, otherwise these object wont + * link into other scenes from this blend file */ + BKE_main_id_tag_all(bmain, LIB_TAG_PRE_EXISTING, false); + + /* recreate dependency graph to include new objects */ + DAG_relations_tag_update(bmain); + + BLO_blendhandle_close(bh); + /* remove library... */ + + return true; +} + +/** \} */ diff --git a/source/blender/blenkernel/intern/blender_undo.c b/source/blender/blenkernel/intern/blender_undo.c new file mode 100644 index 00000000000..ca0a1b91cea --- /dev/null +++ b/source/blender/blenkernel/intern/blender_undo.c @@ -0,0 +1,393 @@ +/* + * ***** 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. + * + * ***** END GPL LICENSE BLOCK ***** + */ + +/** \file blender/blenkernel/intern/blender_undo.c + * \ingroup bke + * + * Blend file undo (known as 'Global Undo'). + * DNA level diffing for undo. + */ + +#ifndef _WIN32 +# include <unistd.h> // for read close +#else +# include <io.h> // for open close read +#endif + +#include <stdlib.h> +#include <stdio.h> +#include <stddef.h> +#include <string.h> +#include <fcntl.h> /* for open */ +#include <errno.h> + +#include "MEM_guardedalloc.h" + +#include "DNA_scene_types.h" + +#include "BLI_fileops.h" +#include "BLI_listbase.h" +#include "BLI_path_util.h" +#include "BLI_string.h" +#include "BLI_utildefines.h" + +#include "IMB_imbuf.h" +#include "IMB_moviecache.h" + +#include "BKE_blender_undo.h" /* own include */ +#include "BKE_blendfile.h" +#include "BKE_appdir.h" +#include "BKE_brush.h" +#include "BKE_context.h" +#include "BKE_depsgraph.h" +#include "BKE_global.h" +#include "BKE_image.h" +#include "BKE_main.h" +#include "RE_pipeline.h" + +#include "BLO_undofile.h" +#include "BLO_readfile.h" +#include "BLO_writefile.h" + +#include "WM_api.h" // XXXXX BAD, very BAD dependency (bad level call) - remove asap, elubie + + +/* -------------------------------------------------------------------- */ + +/** \name Global Undo + * \{ */ + +#define UNDO_DISK 0 + +typedef struct UndoElem { + struct UndoElem *next, *prev; + char str[FILE_MAX]; + char name[BKE_UNDO_STR_MAX]; + MemFile memfile; + uintptr_t undosize; +} UndoElem; + +static ListBase undobase = {NULL, NULL}; +static UndoElem *curundo = NULL; + + +static int read_undosave(bContext *C, UndoElem *uel) +{ + char mainstr[sizeof(G.main->name)]; + int success = 0, fileflags; + + /* This is needed so undoing/redoing doesn't crash with threaded previews going */ + WM_jobs_kill_all_except(CTX_wm_manager(C), CTX_wm_screen(C)); + + BLI_strncpy(mainstr, G.main->name, sizeof(mainstr)); /* temporal store */ + + fileflags = G.fileflags; + G.fileflags |= G_FILE_NO_UI; + + if (UNDO_DISK) + success = (BKE_blendfile_read(C, uel->str, NULL) != BKE_BLENDFILE_READ_FAIL); + else + success = BKE_blendfile_read_from_memfile(C, &uel->memfile, NULL); + + /* restore */ + BLI_strncpy(G.main->name, mainstr, sizeof(G.main->name)); /* restore */ + G.fileflags = fileflags; + + if (success) { + /* important not to update time here, else non keyed tranforms are lost */ + DAG_on_visible_update(G.main, false); + } + + return success; +} + +/* name can be a dynamic string */ +void BKE_undo_write(bContext *C, const char *name) +{ + uintptr_t maxmem, totmem, memused; + int nr /*, success */ /* UNUSED */; + UndoElem *uel; + + if ((U.uiflag & USER_GLOBALUNDO) == 0) { + return; + } + + if (U.undosteps == 0) { + return; + } + + /* remove all undos after (also when curundo == NULL) */ + while (undobase.last != curundo) { + uel = undobase.last; + BLI_remlink(&undobase, uel); + BLO_memfile_free(&uel->memfile); + MEM_freeN(uel); + } + + /* make new */ + curundo = uel = MEM_callocN(sizeof(UndoElem), "undo file"); + BLI_strncpy(uel->name, name, sizeof(uel->name)); + BLI_addtail(&undobase, uel); + + /* and limit amount to the maximum */ + nr = 0; + uel = undobase.last; + while (uel) { + nr++; + if (nr == U.undosteps) break; + uel = uel->prev; + } + if (uel) { + while (undobase.first != uel) { + UndoElem *first = undobase.first; + BLI_remlink(&undobase, first); + /* the merge is because of compression */ + BLO_memfile_merge(&first->memfile, &first->next->memfile); + MEM_freeN(first); + } + } + + + /* disk save version */ + if (UNDO_DISK) { + static int counter = 0; + char filepath[FILE_MAX]; + char numstr[32]; + int fileflags = G.fileflags & ~(G_FILE_HISTORY); /* don't do file history on undo */ + + /* calculate current filepath */ + counter++; + counter = counter % U.undosteps; + + BLI_snprintf(numstr, sizeof(numstr), "%d.blend", counter); + BLI_make_file_string("/", filepath, BKE_tempdir_session(), numstr); + + /* success = */ /* UNUSED */ BLO_write_file(CTX_data_main(C), filepath, fileflags, NULL, NULL); + + BLI_strncpy(curundo->str, filepath, sizeof(curundo->str)); + } + else { + MemFile *prevfile = NULL; + + if (curundo->prev) prevfile = &(curundo->prev->memfile); + + memused = MEM_get_memory_in_use(); + /* success = */ /* UNUSED */ BLO_write_file_mem(CTX_data_main(C), prevfile, &curundo->memfile, G.fileflags); + curundo->undosize = MEM_get_memory_in_use() - memused; + } + + if (U.undomemory != 0) { + /* limit to maximum memory (afterwards, we can't know in advance) */ + totmem = 0; + maxmem = ((uintptr_t)U.undomemory) * 1024 * 1024; + + /* keep at least two (original + other) */ + uel = undobase.last; + while (uel && uel->prev) { + totmem += uel->undosize; + if (totmem > maxmem) break; + uel = uel->prev; + } + + if (uel) { + if (uel->prev && uel->prev->prev) + uel = uel->prev; + + while (undobase.first != uel) { + UndoElem *first = undobase.first; + BLI_remlink(&undobase, first); + /* the merge is because of compression */ + BLO_memfile_merge(&first->memfile, &first->next->memfile); + MEM_freeN(first); + } + } + } +} + +/* 1 = an undo, -1 is a redo. we have to make sure 'curundo' remains at current situation */ +void BKE_undo_step(bContext *C, int step) +{ + + if (step == 0) { + read_undosave(C, curundo); + } + else if (step == 1) { + /* curundo should never be NULL, after restart or load file it should call undo_save */ + if (curundo == NULL || curundo->prev == NULL) { + // XXX error("No undo available"); + } + else { + if (G.debug & G_DEBUG) printf("undo %s\n", curundo->name); + curundo = curundo->prev; + read_undosave(C, curundo); + } + } + else { + /* curundo has to remain current situation! */ + + if (curundo == NULL || curundo->next == NULL) { + // XXX error("No redo available"); + } + else { + read_undosave(C, curundo->next); + curundo = curundo->next; + if (G.debug & G_DEBUG) printf("redo %s\n", curundo->name); + } + } +} + +void BKE_undo_reset(void) +{ + UndoElem *uel; + + uel = undobase.first; + while (uel) { + BLO_memfile_free(&uel->memfile); + uel = uel->next; + } + + BLI_freelistN(&undobase); + curundo = NULL; +} + +/* based on index nr it does a restore */ +void BKE_undo_number(bContext *C, int nr) +{ + curundo = BLI_findlink(&undobase, nr); + BKE_undo_step(C, 0); +} + +/* go back to the last occurance of name in stack */ +void BKE_undo_name(bContext *C, const char *name) +{ + UndoElem *uel = BLI_rfindstring(&undobase, name, offsetof(UndoElem, name)); + + if (uel && uel->prev) { + curundo = uel->prev; + BKE_undo_step(C, 0); + } +} + +/* name optional */ +bool BKE_undo_is_valid(const char *name) +{ + if (name) { + UndoElem *uel = BLI_rfindstring(&undobase, name, offsetof(UndoElem, name)); + return uel && uel->prev; + } + + return undobase.last != undobase.first; +} + +/* get name of undo item, return null if no item with this index */ +/* if active pointer, set it to 1 if true */ +const char *BKE_undo_get_name(int nr, bool *r_active) +{ + UndoElem *uel = BLI_findlink(&undobase, nr); + + if (r_active) *r_active = false; + + if (uel) { + if (r_active && (uel == curundo)) { + *r_active = true; + } + return uel->name; + } + return NULL; +} + +/** + * Saves .blend using undo buffer. + * + * \return success. + */ +bool BKE_undo_save_file(const char *filename) +{ + UndoElem *uel; + MemFileChunk *chunk; + int file, oflags; + + if ((U.uiflag & USER_GLOBALUNDO) == 0) { + return false; + } + + uel = curundo; + if (uel == NULL) { + fprintf(stderr, "No undo buffer to save recovery file\n"); + return false; + } + + /* note: This is currently used for autosave and 'quit.blend', where _not_ following symlinks is OK, + * however if this is ever executed explicitly by the user, we may want to allow writing to symlinks. + */ + + oflags = O_BINARY | O_WRONLY | O_CREAT | O_TRUNC; +#ifdef O_NOFOLLOW + /* use O_NOFOLLOW to avoid writing to a symlink - use 'O_EXCL' (CVE-2008-1103) */ + oflags |= O_NOFOLLOW; +#else + /* TODO(sergey): How to deal with symlinks on windows? */ +# ifndef _MSC_VER +# warning "Symbolic links will be followed on undo save, possibly causing CVE-2008-1103" +# endif +#endif + file = BLI_open(filename, oflags, 0666); + + if (file == -1) { + fprintf(stderr, "Unable to save '%s': %s\n", + filename, errno ? strerror(errno) : "Unknown error opening file"); + return false; + } + + for (chunk = uel->memfile.chunks.first; chunk; chunk = chunk->next) { + if (write(file, chunk->buf, chunk->size) != chunk->size) { + break; + } + } + + close(file); + + if (chunk) { + fprintf(stderr, "Unable to save '%s': %s\n", + filename, errno ? strerror(errno) : "Unknown error writing file"); + return false; + } + return true; +} + +/* sets curscene */ +Main *BKE_undo_get_main(Scene **r_scene) +{ + Main *mainp = NULL; + BlendFileData *bfd = BLO_read_from_memfile(G.main, G.main->name, &curundo->memfile, NULL); + + if (bfd) { + mainp = bfd->main; + if (r_scene) { + *r_scene = bfd->curscene; + } + + MEM_freeN(bfd); + } + + return mainp; +} + +/** \} */ diff --git a/source/blender/blenkernel/intern/blendfile.c b/source/blender/blenkernel/intern/blendfile.c new file mode 100644 index 00000000000..4605a12f9a0 --- /dev/null +++ b/source/blender/blenkernel/intern/blendfile.c @@ -0,0 +1,566 @@ +/* + * ***** 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. + * + * ***** END GPL LICENSE BLOCK ***** + */ + +/** \file blender/blenkernel/intern/blendfile.c + * \ingroup bke + * + * High level `.blend` file read/write, + * and functions for writing *partial* files (only selected data-blocks). + */ + +#include <stdlib.h> +#include <string.h> + +#include "MEM_guardedalloc.h" + +#include "DNA_scene_types.h" +#include "DNA_screen_types.h" + +#include "BLI_listbase.h" +#include "BLI_string.h" +#include "BLI_path_util.h" +#include "BLI_utildefines.h" + +#include "IMB_colormanagement.h" + +#include "BKE_appdir.h" +#include "BKE_blender.h" +#include "BKE_blender_version.h" +#include "BKE_blendfile.h" +#include "BKE_bpath.h" +#include "BKE_context.h" +#include "BKE_global.h" +#include "BKE_ipo.h" +#include "BKE_library.h" +#include "BKE_main.h" +#include "BKE_report.h" +#include "BKE_scene.h" +#include "BKE_screen.h" + +#include "BLO_readfile.h" +#include "BLO_writefile.h" + +#include "RNA_access.h" + +#include "RE_pipeline.h" + +#ifdef WITH_PYTHON +# include "BPY_extern.h" +#endif + +/* -------------------------------------------------------------------- */ + +/** \name High Level `.blend` file read/write. + * \{ */ + +static bool clean_paths_visit_cb(void *UNUSED(userdata), char *path_dst, const char *path_src) +{ + strcpy(path_dst, path_src); + BLI_path_native_slash(path_dst); + return !STREQ(path_dst, path_src); +} + +/* make sure path names are correct for OS */ +static void clean_paths(Main *main) +{ + Scene *scene; + + BKE_bpath_traverse_main(main, clean_paths_visit_cb, BKE_BPATH_TRAVERSE_SKIP_MULTIFILE, NULL); + + for (scene = main->scene.first; scene; scene = scene->id.next) { + BLI_path_native_slash(scene->r.pic); + } +} + +static bool wm_scene_is_visible(wmWindowManager *wm, Scene *scene) +{ + wmWindow *win; + for (win = wm->windows.first; win; win = win->next) { + if (win->screen->scene == scene) { + return true; + } + } + return false; +} + +/** + * Context matching, handle no-ui case + * + * \note this is called on Undo so any slow conversion functions here + * should be avoided or check (mode != LOAD_UNDO). + * + * \param bfd: Blend file data, freed by this function on exit. + * \param filepath: File path or identifier. + */ +static void setup_app_data( + bContext *C, BlendFileData *bfd, + const char *filepath, ReportList *reports) +{ + Scene *curscene = NULL; + const bool recover = (G.fileflags & G_FILE_RECOVER) != 0; + enum { + LOAD_UI = 1, + LOAD_UI_OFF, + LOAD_UNDO, + } mode; + + if (BLI_listbase_is_empty(&bfd->main->screen)) { + mode = LOAD_UNDO; + } + else if (G.fileflags & G_FILE_NO_UI) { + mode = LOAD_UI_OFF; + } + else { + mode = LOAD_UI; + } + + if (mode != LOAD_UNDO) { + /* may happen with library files */ + if (ELEM(NULL, bfd->curscreen, bfd->curscene)) { + BKE_report(reports, RPT_WARNING, "Library file, loading empty scene"); + mode = LOAD_UI_OFF; + } + } + + /* Free all render results, without this stale data gets displayed after loading files */ + if (mode != LOAD_UNDO) { + RE_FreeAllRenderResults(); + } + + /* Only make filepaths compatible when loading for real (not undo) */ + if (mode != LOAD_UNDO) { + clean_paths(bfd->main); + } + + /* XXX here the complex windowmanager matching */ + + /* no load screens? */ + if (mode != LOAD_UI) { + /* Logic for 'track_undo_scene' is to keep using the scene which the active screen has, + * as long as the scene associated with the undo operation is visible in one of the open windows. + * + * - 'curscreen->scene' - scene the user is currently looking at. + * - 'bfd->curscene' - scene undo-step was created in. + * + * This means users can have 2+ windows open and undo in both without screens switching. + * But if they close one of the screens, + * undo will ensure that the scene being operated on will be activated + * (otherwise we'd be undoing on an off-screen scene which isn't acceptable). + * see: T43424 + */ + bScreen *curscreen = NULL; + bool track_undo_scene; + + /* comes from readfile.c */ + SWAP(ListBase, G.main->wm, bfd->main->wm); + SWAP(ListBase, G.main->screen, bfd->main->screen); + + /* we re-use current screen */ + curscreen = CTX_wm_screen(C); + /* but use new Scene pointer */ + curscene = bfd->curscene; + + track_undo_scene = (mode == LOAD_UNDO && curscreen && curscene && bfd->main->wm.first); + + if (curscene == NULL) { + curscene = bfd->main->scene.first; + } + /* empty file, we add a scene to make Blender work */ + if (curscene == NULL) { + curscene = BKE_scene_add(bfd->main, "Empty"); + } + + if (track_undo_scene) { + /* keep the old (free'd) scene, let 'blo_lib_link_screen_restore' + * replace it with 'curscene' if its needed */ + } + else { + /* and we enforce curscene to be in current screen */ + if (curscreen) { + /* can run in bgmode */ + curscreen->scene = curscene; + } + } + + /* BKE_blender_globals_clear will free G.main, here we can still restore pointers */ + blo_lib_link_screen_restore(bfd->main, curscreen, curscene); + /* curscreen might not be set when loading without ui (see T44217) so only re-assign if available */ + if (curscreen) { + curscene = curscreen->scene; + } + + if (track_undo_scene) { + wmWindowManager *wm = bfd->main->wm.first; + if (wm_scene_is_visible(wm, bfd->curscene) == false) { + curscene = bfd->curscene; + curscreen->scene = curscene; + BKE_screen_view3d_scene_sync(curscreen); + } + } + } + + /* 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(); + + G.main = bfd->main; + + CTX_data_main_set(C, G.main); + + if (bfd->user) { + + /* only here free userdef themes... */ + BKE_blender_userdef_free(); + + U = *bfd->user; + + /* Security issue: any blend file could include a USER block. + * + * Currently we load prefs from BLENDER_STARTUP_FILE and later on load BLENDER_USERPREF_FILE, + * to load the preferences defined in the users home dir. + * + * This means we will never accidentally (or maliciously) + * enable scripts auto-execution by loading a '.blend' file. + */ + U.flag |= USER_SCRIPT_AUTOEXEC_DISABLE; + + MEM_freeN(bfd->user); + } + + /* case G_FILE_NO_UI or no screens in file */ + if (mode != LOAD_UI) { + /* leave entire context further unaltered? */ + CTX_data_scene_set(C, curscene); + } + else { + G.fileflags = bfd->fileflags; + CTX_wm_manager_set(C, G.main->wm.first); + CTX_wm_screen_set(C, bfd->curscreen); + CTX_data_scene_set(C, bfd->curscene); + CTX_wm_area_set(C, NULL); + CTX_wm_region_set(C, NULL); + CTX_wm_menu_set(C, NULL); + curscene = bfd->curscene; + } + + /* this can happen when active scene was lib-linked, and doesn't exist anymore */ + if (CTX_data_scene(C) == NULL) { + /* in case we don't even have a local scene, add one */ + if (!G.main->scene.first) + BKE_scene_add(G.main, "Empty"); + + CTX_data_scene_set(C, G.main->scene.first); + CTX_wm_screen(C)->scene = CTX_data_scene(C); + curscene = CTX_data_scene(C); + } + + BLI_assert(curscene == CTX_data_scene(C)); + + + /* special cases, override loaded flags: */ + if (G.f != bfd->globalf) { + const int flags_keep = (G_SWAP_EXCHANGE | G_SCRIPT_AUTOEXEC | G_SCRIPT_OVERRIDE_PREF); + bfd->globalf = (bfd->globalf & ~flags_keep) | (G.f & flags_keep); + } + + + G.f = bfd->globalf; + +#ifdef WITH_PYTHON + /* let python know about new main */ + BPY_context_update(C); +#endif + + /* FIXME: this version patching should really be part of the file-reading code, + * but we still get too many unrelated data-corruption crashes otherwise... */ + if (G.main->versionfile < 250) + do_versions_ipos_to_animato(G.main); + + G.main->recovered = 0; + + /* startup.blend or recovered startup */ + if (bfd->filename[0] == 0) { + G.main->name[0] = 0; + } + else if (recover && G.relbase_valid) { + /* in case of autosave or quit.blend, use original filename instead + * use relbase_valid to make sure the file is saved, else we get <memory2> in the filename */ + filepath = bfd->filename; + G.main->recovered = 1; + + /* these are the same at times, should never copy to the same location */ + if (G.main->name != filepath) + BLI_strncpy(G.main->name, filepath, FILE_MAX); + } + + /* baseflags, groups, make depsgraph, etc */ + /* first handle case if other windows have different scenes visible */ + if (mode == LOAD_UI) { + wmWindowManager *wm = G.main->wm.first; + + if (wm) { + wmWindow *win; + + for (win = wm->windows.first; win; win = win->next) { + if (win->screen && win->screen->scene) /* zealous check... */ + if (win->screen->scene != curscene) + BKE_scene_set_background(G.main, win->screen->scene); + } + } + } + BKE_scene_set_background(G.main, curscene); + + if (mode != LOAD_UNDO) { + RE_FreeAllPersistentData(); + IMB_colormanagement_check_file_config(G.main); + } + + MEM_freeN(bfd); + +} + +static int handle_subversion_warning(Main *main, ReportList *reports) +{ + if (main->minversionfile > BLENDER_VERSION || + (main->minversionfile == BLENDER_VERSION && + main->minsubversionfile > BLENDER_SUBVERSION)) + { + BKE_reportf(reports, RPT_ERROR, "File written by newer Blender binary (%d.%d), expect loss of data!", + main->minversionfile, main->minsubversionfile); + } + + return 1; +} + +int BKE_blendfile_read(bContext *C, const char *filepath, ReportList *reports) +{ + BlendFileData *bfd; + int retval = BKE_BLENDFILE_READ_OK; + + if (strstr(filepath, BLENDER_STARTUP_FILE) == NULL) /* don't print user-pref loading */ + printf("read blend: %s\n", filepath); + + bfd = BLO_read_from_file(filepath, reports); + if (bfd) { + if (bfd->user) retval = BKE_BLENDFILE_READ_OK_USERPREFS; + + if (0 == handle_subversion_warning(bfd->main, reports)) { + BKE_main_free(bfd->main); + MEM_freeN(bfd); + bfd = NULL; + retval = BKE_BLENDFILE_READ_FAIL; + } + else { + setup_app_data(C, bfd, filepath, reports); + } + } + else + BKE_reports_prependf(reports, "Loading '%s' failed: ", filepath); + + return (bfd ? retval : BKE_BLENDFILE_READ_FAIL); +} + +bool BKE_blendfile_read_from_memory( + bContext *C, const void *filebuf, int filelength, + ReportList *reports, bool update_defaults) +{ + BlendFileData *bfd; + + bfd = BLO_read_from_memory(filebuf, filelength, reports); + if (bfd) { + if (update_defaults) + BLO_update_defaults_startup_blend(bfd->main); + setup_app_data(C, bfd, "<memory2>", reports); + } + else { + BKE_reports_prepend(reports, "Loading failed: "); + } + + return (bfd != NULL); +} + +/* memfile is the undo buffer */ +bool BKE_blendfile_read_from_memfile( + bContext *C, struct MemFile *memfile, + ReportList *reports) +{ + BlendFileData *bfd; + + bfd = BLO_read_from_memfile(CTX_data_main(C), G.main->name, memfile, reports); + if (bfd) { + /* remove the unused screens and wm */ + while (bfd->main->wm.first) + BKE_libblock_free_ex(bfd->main, bfd->main->wm.first, true); + while (bfd->main->screen.first) + BKE_libblock_free_ex(bfd->main, bfd->main->screen.first, true); + + setup_app_data(C, bfd, "<memory1>", reports); + } + else { + BKE_reports_prepend(reports, "Loading failed: "); + } + + return (bfd != NULL); +} + +/* only read the userdef from a .blend */ +int BKE_blendfile_read_userdef(const char *filepath, ReportList *reports) +{ + BlendFileData *bfd; + int retval = BKE_BLENDFILE_READ_FAIL; + + bfd = BLO_read_from_file(filepath, reports); + if (bfd) { + if (bfd->user) { + retval = BKE_BLENDFILE_READ_OK_USERPREFS; + + /* only here free userdef themes... */ + BKE_blender_userdef_free(); + + U = *bfd->user; + MEM_freeN(bfd->user); + } + BKE_main_free(bfd->main); + MEM_freeN(bfd); + } + + return retval; +} + +/* only write the userdef in a .blend */ +int BKE_blendfile_write_userdef(const char *filepath, ReportList *reports) +{ + Main *mainb = MEM_callocN(sizeof(Main), "empty main"); + int retval = 0; + + if (BLO_write_file(mainb, filepath, G_FILE_USERPREFS, reports, NULL)) { + retval = 1; + } + + MEM_freeN(mainb); + + return retval; +} + +/** \} */ + + +/* -------------------------------------------------------------------- */ + +/** \name Partial `.blend` file save. + * \{ */ + +void BKE_blendfile_write_partial_begin(Main *bmain_src) +{ + BKE_main_id_tag_all(bmain_src, LIB_TAG_NEED_EXPAND | LIB_TAG_DOIT, false); +} + +void BKE_blendfile_write_partial_tag_ID(ID *id, bool set) +{ + if (set) { + id->tag |= LIB_TAG_NEED_EXPAND | LIB_TAG_DOIT; + } + else { + id->tag &= ~(LIB_TAG_NEED_EXPAND | LIB_TAG_DOIT); + } +} + +static void blendfile_write_partial_cb(void *UNUSED(handle), Main *UNUSED(bmain), void *vid) +{ + if (vid) { + ID *id = vid; + /* only tag for need-expand if not done, prevents eternal loops */ + if ((id->tag & LIB_TAG_DOIT) == 0) + id->tag |= LIB_TAG_NEED_EXPAND | LIB_TAG_DOIT; + } +} + +/** + * \return Success. + */ +bool BKE_blendfile_write_partial( + Main *bmain_src, const char *filepath, const int write_flags, ReportList *reports) +{ + Main *bmain_dst = MEM_callocN(sizeof(Main), "copybuffer"); + ListBase *lbarray_dst[MAX_LIBARRAY], *lbarray_src[MAX_LIBARRAY]; + int a, retval; + + void *path_list_backup = NULL; + const int path_list_flag = (BKE_BPATH_TRAVERSE_SKIP_LIBRARY | BKE_BPATH_TRAVERSE_SKIP_MULTIFILE); + + if (write_flags & G_FILE_RELATIVE_REMAP) { + path_list_backup = BKE_bpath_list_backup(bmain_src, path_list_flag); + } + + BLO_main_expander(blendfile_write_partial_cb); + BLO_expand_main(NULL, bmain_src); + + /* move over all tagged blocks */ + set_listbasepointers(bmain_src, lbarray_src); + a = set_listbasepointers(bmain_dst, lbarray_dst); + while (a--) { + ID *id, *nextid; + ListBase *lb_dst = lbarray_dst[a], *lb_src = lbarray_src[a]; + + for (id = lb_src->first; id; id = nextid) { + nextid = id->next; + if (id->tag & LIB_TAG_DOIT) { + BLI_remlink(lb_src, id); + BLI_addtail(lb_dst, id); + } + } + } + + + /* save the buffer */ + retval = BLO_write_file(bmain_dst, filepath, write_flags, reports, NULL); + + /* move back the main, now sorted again */ + set_listbasepointers(bmain_src, lbarray_dst); + a = set_listbasepointers(bmain_dst, lbarray_src); + while (a--) { + ID *id; + ListBase *lb_dst = lbarray_dst[a], *lb_src = lbarray_src[a]; + + while ((id = BLI_pophead(lb_src))) { + BLI_addtail(lb_dst, id); + id_sort_by_name(lb_dst, id); + } + } + + MEM_freeN(bmain_dst); + + if (path_list_backup) { + BKE_bpath_list_restore(bmain_src, path_list_flag, path_list_backup); + BKE_bpath_list_free(path_list_backup); + } + + return retval; +} + +void BKE_blendfile_write_partial_end(Main *bmain_src) +{ + BKE_main_id_tag_all(bmain_src, LIB_TAG_NEED_EXPAND | LIB_TAG_DOIT, false); +} + +/** \} */ diff --git a/source/blender/blenkernel/intern/cdderivedmesh.c b/source/blender/blenkernel/intern/cdderivedmesh.c index 519b7b44637..e6741657f47 100644 --- a/source/blender/blenkernel/intern/cdderivedmesh.c +++ b/source/blender/blenkernel/intern/cdderivedmesh.c @@ -1049,11 +1049,13 @@ static void cdDM_drawMappedFacesGLSL( numdata++; } } - if (matconv[a].attribs.tottang && matconv[a].attribs.tang.array) { - matconv[a].datatypes[numdata].index = matconv[a].attribs.tang.gl_index; - matconv[a].datatypes[numdata].size = 4; - matconv[a].datatypes[numdata].type = GL_FLOAT; - numdata++; + for (b = 0; b < matconv[a].attribs.tottang; b++) { + if (matconv[a].attribs.tang[b].array) { + matconv[a].datatypes[numdata].index = matconv[a].attribs.tang[b].gl_index; + matconv[a].datatypes[numdata].size = 4; + matconv[a].datatypes[numdata].type = GL_FLOAT; + numdata++; + } } if (numdata != 0) { matconv[a].numdata = numdata; @@ -1105,11 +1107,13 @@ static void cdDM_drawMappedFacesGLSL( offset += sizeof(unsigned char) * 4; } } - if (matconv[i].attribs.tottang && matconv[i].attribs.tang.array) { - const float (*looptang)[4] = (const float (*)[4])matconv[i].attribs.tang.array; - for (j = 0; j < mpoly->totloop; j++) - copy_v4_v4((float *)&varray[offset + j * max_element_size], looptang[mpoly->loopstart + j]); - offset += sizeof(float) * 4; + for (b = 0; b < matconv[i].attribs.tottang; b++) { + if (matconv[i].attribs.tottang && matconv[i].attribs.tang[b].array) { + const float (*looptang)[4] = (const float (*)[4])matconv[i].attribs.tang[b].array; + for (j = 0; j < mpoly->totloop; j++) + copy_v4_v4((float *)&varray[offset + j * max_element_size], looptang[mpoly->loopstart + j]); + offset += sizeof(float) * 4; + } } } diff --git a/source/blender/blenkernel/intern/constraint.c b/source/blender/blenkernel/intern/constraint.c index dabe606fa55..1b9ac499e1f 100644 --- a/source/blender/blenkernel/intern/constraint.c +++ b/source/blender/blenkernel/intern/constraint.c @@ -3523,8 +3523,6 @@ static void shrinkwrap_get_tarmat(bConstraint *con, bConstraintOb *cob, bConstra free_bvhtree_from_mesh(&treeData); - target->release(target); - if (fail == true) { /* Don't move the point */ zero_v3(co); diff --git a/source/blender/blenkernel/intern/customdata.c b/source/blender/blenkernel/intern/customdata.c index a12d5434b30..b0d0dc08126 100644 --- a/source/blender/blenkernel/intern/customdata.c +++ b/source/blender/blenkernel/intern/customdata.c @@ -1259,7 +1259,7 @@ static const LayerTypeInfo LAYERTYPEINFO[CD_NUMTYPES] = { 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, NULL, NULL, NULL, NULL, NULL, NULL}, + {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, diff --git a/source/blender/blenkernel/intern/depsgraph.c b/source/blender/blenkernel/intern/depsgraph.c index 0582d07d99c..30dcba66c5e 100644 --- a/source/blender/blenkernel/intern/depsgraph.c +++ b/source/blender/blenkernel/intern/depsgraph.c @@ -834,6 +834,8 @@ DagForest *build_dag(Main *bmain, Scene *sce, short mask) } dag->need_update = false; + BKE_main_id_tag_idcode(bmain, ID_OB, LIB_TAG_DOIT, false); + /* clear "LIB_TAG_DOIT" flag from all materials, to prevent infinite recursion problems later [#32017] */ BKE_main_id_tag_idcode(bmain, ID_MA, LIB_TAG_DOIT, false); BKE_main_id_tag_idcode(bmain, ID_LA, LIB_TAG_DOIT, false); @@ -845,14 +847,43 @@ DagForest *build_dag(Main *bmain, Scene *sce, short mask) /* add current scene objects */ for (base = sce->base.first; base; base = base->next) { ob = base->object; - + ob->id.tag |= LIB_TAG_DOIT; build_dag_object(dag, scenenode, bmain, sce, ob, mask); if (ob->proxy) build_dag_object(dag, scenenode, bmain, sce, ob->proxy, mask); if (ob->dup_group) build_dag_group(dag, scenenode, bmain, sce, ob->dup_group, mask); } - + + /* There might be situations when object from current scene depends on + * objects form other scene AND objects from other scene has own + * dependencies on objects from other scene. + * + * This is really important to include such indirect dependencies in order + * to keep threaded update safe but since we don't really know if object is + * coming from current scene or another scene we do rather stupid tag-based + * check here: all the objects for which build_dag_object() was called are + * getting tagged with LIB_TAG_DOIT. This way if some node has untagged + * object we know it's an object from other scene. + * + * It should be enough to to it once, because if there's longer chain of + * indirect dependencies, all the new nodes will be added to the end of the + * list, meaning we'll keep covering them in this for loop. + */ + for (node = sce->theDag->DagNode.first; node != NULL; node = node->next) { + if (node->type == ID_OB) { + ob = node->ob; + if ((ob->id.tag & LIB_TAG_DOIT) == 0) { + ob->id.tag |= LIB_TAG_DOIT; + build_dag_object(dag, scenenode, bmain, sce, ob, mask); + if (ob->proxy) + build_dag_object(dag, scenenode, bmain, sce, ob->proxy, mask); + if (ob->dup_group) + build_dag_group(dag, scenenode, bmain, sce, ob->dup_group, mask); + } + } + } + BKE_main_id_tag_idcode(bmain, ID_GR, LIB_TAG_DOIT, false); /* Now all relations were built, but we need to solve 1 exceptional case; diff --git a/source/blender/blenkernel/intern/editderivedmesh.c b/source/blender/blenkernel/intern/editderivedmesh.c index 96bdfe88722..6c117447664 100644 --- a/source/blender/blenkernel/intern/editderivedmesh.c +++ b/source/blender/blenkernel/intern/editderivedmesh.c @@ -44,6 +44,7 @@ #include "BLI_math.h" #include "BLI_jitter.h" #include "BLI_bitmap.h" +#include "BLI_task.h" #include "BKE_cdderivedmesh.h" #include "BKE_mesh.h" @@ -451,118 +452,148 @@ finally: pRes[3] = fSign; } +static void emDM_calc_loop_tangents_thread(TaskPool *UNUSED(pool), void *taskdata, int UNUSED(threadid)) +{ + struct SGLSLEditMeshToTangent *mesh2tangent = taskdata; + /* new computation method */ + { + SMikkTSpaceContext sContext = {NULL}; + SMikkTSpaceInterface sInterface = {NULL}; + sContext.m_pUserData = mesh2tangent; + sContext.m_pInterface = &sInterface; + sInterface.m_getNumFaces = emdm_ts_GetNumFaces; + sInterface.m_getNumVerticesOfFace = emdm_ts_GetNumVertsOfFace; + sInterface.m_getPosition = emdm_ts_GetPosition; + sInterface.m_getTexCoord = emdm_ts_GetTextureCoordinate; + sInterface.m_getNormal = emdm_ts_GetNormal; + sInterface.m_setTSpaceBasic = emdm_ts_SetTSpace; + /* 0 if failed */ + genTangSpaceDefault(&sContext); + } +} + /** * \see #DM_calc_loop_tangents, same logic but used arrays instead of #BMesh data. * * \note This function is not so normal, its using `bm->ldata` as input, but output's to `dm->loopData`. * This is done because #CD_TANGENT is cache data used only for drawing. */ -static void emDM_calcLoopTangents(DerivedMesh *dm) + +static void emDM_calc_loop_tangents( + DerivedMesh *dm, bool calc_active_tangent, + const char (*tangent_names)[MAX_NAME], int tangent_names_count) { EditDerivedBMesh *bmdm = (EditDerivedBMesh *)dm; BMEditMesh *em = bmdm->em; BMesh *bm = bmdm->em->bm; - - /* mesh vars */ - int cd_loop_uv_offset; - float (*orco)[3] = NULL, (*tangent)[4]; - int /* totvert, */ totface; - const float (*fnors)[3]; - const float (*tlnors)[3]; - char htype_index = BM_LOOP; - - if (CustomData_get_layer_index(&dm->loopData, CD_TANGENT) != -1) + if (CustomData_number_of_layers(&bm->ldata, CD_MLOOPUV) == 0) return; - fnors = bmdm->polyNos; /* dm->getPolyDataArray(dm, CD_NORMAL) */ - - /* Note, we assume we do have tessellated loop normals at this point (in case it is object-enabled), - * have to check this is valid... - */ - tlnors = dm->getLoopDataArray(dm, CD_NORMAL); - - /* check we have all the needed layers */ - totface = em->tottri; - - cd_loop_uv_offset = CustomData_get_offset(&bm->ldata, CD_MLOOPUV); - - /* needed for indexing loop-tangents */ - htype_index = BM_LOOP; - if (cd_loop_uv_offset == -1) { - orco = dm->getVertDataArray(dm, CD_ORCO); - if (!orco) - return; - /* needed for orco lookups */ - htype_index |= BM_VERT; - } - - if (fnors) { - /* needed for face normal lookups */ - htype_index |= BM_FACE; - } - - BM_mesh_elem_index_ensure(bm, htype_index); + int act_uv_n = -1; + int ren_uv_n = -1; + bool calc_act = false; + bool calc_ren = false; + char act_uv_name[MAX_NAME]; + char ren_uv_name[MAX_NAME]; + char tangent_mask = 0; + + DM_calc_loop_tangents_step_0( + &bm->ldata, calc_active_tangent, tangent_names, tangent_names_count, + &calc_act, &calc_ren, &act_uv_n, &ren_uv_n, act_uv_name, ren_uv_name, &tangent_mask); + + if ((dm->tangent_mask | tangent_mask) != dm->tangent_mask) { + for (int i = 0; i < tangent_names_count; i++) + if (tangent_names[i][0]) + DM_add_named_tangent_layer_for_uv(&bm->ldata, &dm->loopData, dm->numLoopData, tangent_names[i]); + if (calc_act && act_uv_name[0]) + DM_add_named_tangent_layer_for_uv(&bm->ldata, &dm->loopData, dm->numLoopData, act_uv_name); + if (calc_ren && ren_uv_name[0]) + DM_add_named_tangent_layer_for_uv(&bm->ldata, &dm->loopData, dm->numLoopData, ren_uv_name); + int totface = em->tottri; +#ifdef USE_LOOPTRI_DETECT_QUADS + int num_face_as_quad_map; + int *face_as_quad_map = NULL; - /* create tangent layer */ - DM_add_loop_layer(dm, CD_TANGENT, CD_CALLOC, NULL); - tangent = DM_get_loop_data_layer(dm, CD_TANGENT); + /* map faces to quads */ + if (bmdm->em->tottri != bm->totface) { + /* over alloc, since we dont know how many ngon or quads we have */ -#ifdef USE_LOOPTRI_DETECT_QUADS - int num_face_as_quad_map; - int *face_as_quad_map = NULL; - - /* map faces to quads */ - if (bmdm->em->tottri != bm->totface) { - /* over alloc, since we dont know how many ngon or quads we have */ - - /* map fake face index to looptri */ - face_as_quad_map = MEM_mallocN(sizeof(int) * totface, __func__); - int i, j; - for (i = 0, j = 0; j < totface; i++, j++) { - face_as_quad_map[i] = j; - /* step over all quads */ - if (em->looptris[j][0]->f->len == 4) { - j++; /* skips the nest looptri */ + /* map fake face index to looptri */ + face_as_quad_map = MEM_mallocN(sizeof(int) * totface, __func__); + int i, j; + for (i = 0, j = 0; j < totface; i++, j++) { + face_as_quad_map[i] = j; + /* step over all quads */ + if (em->looptris[j][0]->f->len == 4) { + j++; /* skips the nest looptri */ + } } + num_face_as_quad_map = i; + } + else { + num_face_as_quad_map = totface; } - num_face_as_quad_map = i; - } - else { - num_face_as_quad_map = totface; - } #endif - - /* new computation method */ - { - SGLSLEditMeshToTangent mesh2tangent = {NULL}; - SMikkTSpaceContext sContext = {NULL}; - SMikkTSpaceInterface sInterface = {NULL}; - - mesh2tangent.precomputedFaceNormals = fnors; - mesh2tangent.precomputedLoopNormals = tlnors; - mesh2tangent.looptris = (const BMLoop *(*)[3])em->looptris; - mesh2tangent.cd_loop_uv_offset = cd_loop_uv_offset; - mesh2tangent.orco = (const float (*)[3])orco; - mesh2tangent.tangent = tangent; - mesh2tangent.numTessFaces = totface; - + /* Calculation */ + { + TaskScheduler *scheduler = BLI_task_scheduler_get(); + TaskPool *task_pool; + task_pool = BLI_task_pool_create(scheduler, NULL); + + dm->tangent_mask = 0; + /* Calculate tangent layers */ + SGLSLEditMeshToTangent data_array[MAX_MTFACE]; + int index = 0; + int n = 0; + CustomData_update_typemap(&dm->loopData); + const int tangent_layer_num = CustomData_number_of_layers(&dm->loopData, CD_TANGENT); + for (n = 0; n < tangent_layer_num; n++) { + index = CustomData_get_layer_index_n(&dm->loopData, CD_TANGENT, n); + BLI_assert(n < MAX_MTFACE); + SGLSLEditMeshToTangent *mesh2tangent = &data_array[n]; + mesh2tangent->numTessFaces = em->tottri; #ifdef USE_LOOPTRI_DETECT_QUADS - mesh2tangent.face_as_quad_map = face_as_quad_map; - mesh2tangent.num_face_as_quad_map = num_face_as_quad_map; + mesh2tangent->face_as_quad_map = face_as_quad_map; + mesh2tangent->num_face_as_quad_map = num_face_as_quad_map; #endif + mesh2tangent->precomputedFaceNormals = bmdm->polyNos; /* dm->getPolyDataArray(dm, CD_NORMAL) */ + /* Note, we assume we do have tessellated loop normals at this point (in case it is object-enabled), + * have to check this is valid... + */ + mesh2tangent->precomputedLoopNormals = CustomData_get_layer(&dm->loopData, CD_NORMAL); + mesh2tangent->cd_loop_uv_offset = CustomData_get_n_offset(&bm->ldata, CD_MLOOPUV, n); + + /* needed for indexing loop-tangents */ + int htype_index = BM_LOOP; + if (mesh2tangent->cd_loop_uv_offset == -1) { + mesh2tangent->orco = dm->getVertDataArray(dm, CD_ORCO); + if (!mesh2tangent->orco) + continue; + /* needed for orco lookups */ + htype_index |= BM_VERT; + } + if (mesh2tangent->precomputedFaceNormals) { + /* needed for face normal lookups */ + htype_index |= BM_FACE; + } + BM_mesh_elem_index_ensure(bm, htype_index); + + mesh2tangent->looptris = (const BMLoop *(*)[3])em->looptris; + mesh2tangent->tangent = dm->loopData.layers[index].data; + + /* Fill the resulting tangent_mask */ + int uv_ind = CustomData_get_named_layer_index(&bm->ldata, CD_MLOOPUV, dm->loopData.layers[index].name); + int uv_start = CustomData_get_layer_index(&bm->ldata, CD_MLOOPUV); + BLI_assert(uv_ind != -1 && uv_start != -1); + BLI_assert(uv_ind - uv_start < MAX_MTFACE); + dm->tangent_mask |= 1 << (uv_ind - uv_start); + BLI_task_pool_push(task_pool, emDM_calc_loop_tangents_thread, mesh2tangent, false, TASK_PRIORITY_LOW); + } - sContext.m_pUserData = &mesh2tangent; - sContext.m_pInterface = &sInterface; - sInterface.m_getNumFaces = emdm_ts_GetNumFaces; - sInterface.m_getNumVerticesOfFace = emdm_ts_GetNumVertsOfFace; - sInterface.m_getPosition = emdm_ts_GetPosition; - sInterface.m_getTexCoord = emdm_ts_GetTextureCoordinate; - sInterface.m_getNormal = emdm_ts_GetNormal; - sInterface.m_setTSpaceBasic = emdm_ts_SetTSpace; - - /* 0 if failed */ - genTangSpaceDefault(&sContext); - + BLI_assert(dm->tangent_mask == tangent_mask); + BLI_task_pool_work_and_wait(task_pool); + BLI_task_pool_free(task_pool); + } #ifdef USE_LOOPTRI_DETECT_QUADS if (face_as_quad_map) { MEM_freeN(face_as_quad_map); @@ -570,6 +601,15 @@ static void emDM_calcLoopTangents(DerivedMesh *dm) #undef USE_LOOPTRI_DETECT_QUADS #endif } + /* Update active layer index */ + int uv_index = CustomData_get_layer_index_n(&bm->ldata, CD_MLOOPUV, act_uv_n); + int tan_index = CustomData_get_named_layer_index(&dm->loopData, CD_TANGENT, bm->ldata.layers[uv_index].name); + CustomData_set_layer_active_index(&dm->loopData, CD_TANGENT, tan_index); + + /* Update render layer index */ + uv_index = CustomData_get_layer_index_n(&bm->ldata, CD_MLOOPUV, ren_uv_n); + tan_index = CustomData_get_named_layer_index(&dm->loopData, CD_TANGENT, bm->ldata.layers[uv_index].name); + CustomData_set_layer_render_index(&dm->loopData, CD_TANGENT, tan_index); } /** \} */ @@ -1419,15 +1459,16 @@ static void emdm_pass_attrib_vertex_glsl(const DMVertexAttribs *attribs, const B } glVertexAttrib4ubv(attribs->mcol[i].gl_index, col); } - if (attribs->tottang) { + + for (i = 0; i < attribs->tottang; i++) { const float *tang; - if (attribs->tang.em_offset != -1) { - tang = attribs->tang.array[BM_elem_index_get(loop)]; + if (attribs->tang[i].em_offset != -1) { + tang = attribs->tang[i].array[BM_elem_index_get(loop)]; } else { tang = zero; } - glVertexAttrib4fv(attribs->tang.gl_index, tang); + glVertexAttrib4fv(attribs->tang[i].gl_index, tang); } } @@ -2218,7 +2259,7 @@ DerivedMesh *getEditDerivedBMesh( bmdm->dm.calcNormals = emDM_calcNormals; bmdm->dm.calcLoopNormals = emDM_calcLoopNormals; bmdm->dm.calcLoopNormalsSpaceArray = emDM_calcLoopNormalsSpaceArray; - bmdm->dm.calcLoopTangents = emDM_calcLoopTangents; + bmdm->dm.calcLoopTangents = emDM_calc_loop_tangents; bmdm->dm.recalcTessellation = emDM_recalcTessellation; bmdm->dm.recalcLoopTri = emDM_recalcLoopTri; diff --git a/source/blender/blenkernel/intern/font.c b/source/blender/blenkernel/intern/font.c index 0a887dcf676..aed33d2c64d 100644 --- a/source/blender/blenkernel/intern/font.c +++ b/source/blender/blenkernel/intern/font.c @@ -1040,7 +1040,7 @@ makebreak: timeofs += distfac * cu->xof; /* not cyclic */ ct = chartransdata; - for (i = 0; i <= slen; i++, ct++) { + for (i = 0; i < slen; i++, ct++) { float ctime, dtime, vec[4], tvec[4], rotvec[3]; float si, co; @@ -1082,8 +1082,9 @@ makebreak: sb = &selboxes[i - selstart]; sb->rot = -ct->rot; } - } + /* null character is always zero width, no need to iterate over it */ + chartransdata[slen] = chartransdata[slen - 1]; } } diff --git a/source/blender/blenkernel/intern/image.c b/source/blender/blenkernel/intern/image.c index cdb3d1afc29..340b406722f 100644 --- a/source/blender/blenkernel/intern/image.c +++ b/source/blender/blenkernel/intern/image.c @@ -1992,7 +1992,7 @@ void BKE_image_stamp_buf( BLF_wordwrap(mono, width - (BUFF_MARGIN_X * 2)); BLF_buffer(mono, rectf, rect, width, height, channels, display); - BLF_buffer_col(mono, UNPACK4(scene->r.fg_stamp)); + BLF_buffer_col(mono, scene->r.fg_stamp); pad = BLF_width_max(mono); /* use 'h_fixed' rather than 'h', aligns better */ diff --git a/source/blender/blenkernel/intern/image_gen.c b/source/blender/blenkernel/intern/image_gen.c index 303d0c6adfc..10e7d46b315 100644 --- a/source/blender/blenkernel/intern/image_gen.c +++ b/source/blender/blenkernel/intern/image_gen.c @@ -297,6 +297,9 @@ static void checker_board_text(unsigned char *rect, float *rect_float, int width */ BLF_buffer(mono, rect_float, rect, width, height, 4, NULL); + const float text_color[4] = {0.0, 0.0, 0.0, 1.0}; + const float text_outline[4] = {1.0, 1.0, 1.0, 1.0}; + for (y = 0; y < height; y += step) { text[1] = '1'; @@ -306,7 +309,7 @@ static void checker_board_text(unsigned char *rect, float *rect_float, int width pen_y = y + 44; /* terribly crappy outline font! */ - BLF_buffer_col(mono, 1.0, 1.0, 1.0, 1.0); + BLF_buffer_col(mono, text_outline); BLF_position(mono, pen_x - outline, pen_y, 0.0); BLF_draw_buffer(mono, text, 2); @@ -326,7 +329,7 @@ static void checker_board_text(unsigned char *rect, float *rect_float, int width BLF_position(mono, pen_x + outline, pen_y - outline, 0.0); BLF_draw_buffer(mono, text, 2); - BLF_buffer_col(mono, 0.0, 0.0, 0.0, 1.0); + BLF_buffer_col(mono, text_color); BLF_position(mono, pen_x, pen_y, 0.0); BLF_draw_buffer(mono, text, 2); diff --git a/source/blender/blenkernel/intern/mask.c b/source/blender/blenkernel/intern/mask.c index 12db3a87ba0..930a3c487ec 100644 --- a/source/blender/blenkernel/intern/mask.c +++ b/source/blender/blenkernel/intern/mask.c @@ -116,7 +116,7 @@ MaskSplinePoint *BKE_mask_spline_point_array(MaskSpline *spline) return spline->points_deform ? spline->points_deform : spline->points; } -MaskSplinePoint *BKE_mask_spline_point_array_from_point(MaskSpline *spline, MaskSplinePoint *point_ref) +MaskSplinePoint *BKE_mask_spline_point_array_from_point(MaskSpline *spline, const MaskSplinePoint *point_ref) { if ((point_ref >= spline->points) && (point_ref < &spline->points[spline->tot_point])) { return spline->points; diff --git a/source/blender/blenkernel/intern/material.c b/source/blender/blenkernel/intern/material.c index 809b45d4b36..1fec725dbb7 100644 --- a/source/blender/blenkernel/intern/material.c +++ b/source/blender/blenkernel/intern/material.c @@ -1148,7 +1148,7 @@ static void init_render_nodetree(bNodeTree *ntree, Material *basemat, int r_mode /* parses the geom+tex nodes */ ntreeShaderGetTexcoMode(ntree, r_mode, &basemat->texco, &basemat->mode_l); - + basemat->nmap_tangent_names_count = 0; for (node = ntree->nodes.first; node; node = node->next) { if (node->id) { if (GS(node->id->name) == ID_MA) { @@ -1170,6 +1170,21 @@ static void init_render_nodetree(bNodeTree *ntree, Material *basemat, int r_mode else if (node->type == NODE_GROUP) init_render_nodetree((bNodeTree *)node->id, basemat, r_mode, amb); } + else if (node->typeinfo->type == SH_NODE_NORMAL_MAP) { + basemat->mode2_l |= MA_TANGENT_CONCRETE; + NodeShaderNormalMap *nm = node->storage; + bool taken_into_account = false; + for (int i = 0; i < basemat->nmap_tangent_names_count; i++) { + if (STREQ(basemat->nmap_tangent_names[i], nm->uv_map)) { + taken_into_account = true; + break; + } + } + if (!taken_into_account) { + BLI_assert(basemat->nmap_tangent_names_count < MAX_MTFACE + 1); + strcpy(basemat->nmap_tangent_names[basemat->nmap_tangent_names_count++], nm->uv_map); + } + } } } diff --git a/source/blender/blenkernel/intern/mesh_evaluate.c b/source/blender/blenkernel/intern/mesh_evaluate.c index 83e020cf2ea..577a21285f8 100644 --- a/source/blender/blenkernel/intern/mesh_evaluate.c +++ b/source/blender/blenkernel/intern/mesh_evaluate.c @@ -2417,30 +2417,42 @@ void BKE_mesh_loops_to_tessdata(CustomData *fdata, CustomData *ldata, CustomData } } -void BKE_mesh_tangent_loops_to_tessdata(CustomData *fdata, CustomData *ldata, MFace *mface, - int *polyindices, unsigned int (*loopindices)[4], const int num_faces) +void BKE_mesh_tangent_loops_to_tessdata( + CustomData *fdata, CustomData *ldata, MFace *mface, + int *polyindices, unsigned int (*loopindices)[4], const int num_faces, const char *layer_name) { /* Note: performances are sub-optimal when we get a NULL mface, we could be ~25% quicker with dedicated code... * Issue is, unless having two different functions with nearly the same code, there's not much ways to solve * this. Better imho to live with it for now. :/ --mont29 */ - const bool hasLoopTangent = CustomData_has_layer(ldata, CD_TANGENT); + + float (*ftangents)[4] = NULL; + float (*ltangents)[4] = NULL; + int findex, j; const int *pidx; unsigned int (*lidx)[4]; - if (hasLoopTangent) { - /* need to do for all uv maps at some point */ - float (*ftangents)[4] = CustomData_get_layer(fdata, CD_TANGENT); - float (*ltangents)[4] = CustomData_get_layer(ldata, CD_TANGENT); + if (layer_name) + ltangents = CustomData_get_layer_named(ldata, CD_TANGENT, layer_name); + else + ltangents = CustomData_get_layer(ldata, CD_TANGENT); - for (findex = 0, pidx = polyindices, lidx = loopindices; - findex < num_faces; - pidx++, lidx++, findex++) - { - int nverts = (mface ? mface[findex].v4 : (*lidx)[3]) ? 4 : 3; - for (j = nverts; j--;) { - copy_v4_v4(ftangents[findex * 4 + j], ltangents[(*lidx)[j]]); + if (ltangents) { + /* need to do for all uv maps at some point */ + if (layer_name) + ftangents = CustomData_get_layer_named(fdata, CD_TANGENT, layer_name); + else + ftangents = CustomData_get_layer(fdata, CD_TANGENT); + if (ftangents) { + for (findex = 0, pidx = polyindices, lidx = loopindices; + findex < num_faces; + pidx++, lidx++, findex++) + { + int nverts = (mface ? mface[findex].v4 : (*lidx)[3]) ? 4 : 3; + for (j = nverts; j--;) { + copy_v4_v4(ftangents[findex * 4 + j], ltangents[(*lidx)[j]]); + } } } } diff --git a/source/blender/blenkernel/intern/pointcache.c b/source/blender/blenkernel/intern/pointcache.c index a3529d8e6f2..c2950530e5c 100644 --- a/source/blender/blenkernel/intern/pointcache.c +++ b/source/blender/blenkernel/intern/pointcache.c @@ -58,7 +58,6 @@ #include "BKE_appdir.h" #include "BKE_anim.h" -#include "BKE_blender.h" #include "BKE_cloth.h" #include "BKE_dynamicpaint.h" #include "BKE_key.h" diff --git a/source/blender/blenkernel/intern/seqeffects.c b/source/blender/blenkernel/intern/seqeffects.c index 1b807adca4b..4086fc2b0f3 100644 --- a/source/blender/blenkernel/intern/seqeffects.c +++ b/source/blender/blenkernel/intern/seqeffects.c @@ -3084,6 +3084,10 @@ static void init_text_effect(Sequence *seq) data = seq->effectdata = MEM_callocN(sizeof(TextVars), "textvars"); data->text_size = 30; + + copy_v4_fl(data->color, 1.0f); + data->shadow_color[3] = 1.0f; + BLI_strncpy(data->text, "Text", sizeof(data->text)); data->loc[0] = 0.5f; @@ -3099,7 +3103,9 @@ static int num_inputs_text(void) static int early_out_text(Sequence *seq, float UNUSED(facf0), float UNUSED(facf1)) { TextVars *data = seq->effectdata; - if (data->text[0] == 0 || data->text_size < 1) { + if (data->text[0] == 0 || data->text_size < 1 || + ((data->color[3] == 0.0f) && (data->shadow_color[3] == 0.0f || (data->flag & SEQ_TEXT_SHADOW) == 0))) + { return EARLY_USE_INPUT_1; } return EARLY_NO_INPUT; @@ -3188,11 +3194,11 @@ static ImBuf *do_text_effect(const SeqRenderData *context, Sequence *seq, float fontx = BLF_width_max(mono); fonty = line_height; BLF_position(mono, x + max_ii(fontx / 25, 1), y + max_ii(fonty / 25, 1), 0.0f); - BLF_buffer_col(mono, 0.0f, 0.0f, 0.0f, 1.0f); + BLF_buffer_col(mono, data->shadow_color); BLF_draw_buffer(mono, data->text, BLF_DRAW_STR_DUMMY_MAX); } BLF_position(mono, x, y, 0.0f); - BLF_buffer_col(mono, 1.0f, 1.0f, 1.0f, 1.0f); + BLF_buffer_col(mono, data->color); BLF_draw_buffer(mono, data->text, BLF_DRAW_STR_DUMMY_MAX); BLF_buffer(mono, NULL, NULL, 0, 0, 0, NULL); diff --git a/source/blender/blenkernel/intern/subsurf_ccg.c b/source/blender/blenkernel/intern/subsurf_ccg.c index 97994332411..a84b8352417 100644 --- a/source/blender/blenkernel/intern/subsurf_ccg.c +++ b/source/blender/blenkernel/intern/subsurf_ccg.c @@ -3016,11 +3016,13 @@ static void ccgDM_drawMappedFacesGLSL(DerivedMesh *dm, numdata++; } } - if (matconv[a].attribs.tottang && matconv[a].attribs.tang.array) { - matconv[a].datatypes[numdata].index = matconv[a].attribs.tang.gl_index; - matconv[a].datatypes[numdata].size = 4; - matconv[a].datatypes[numdata].type = GL_FLOAT; - numdata++; + for (b = 0; b < matconv[a].attribs.tottang; b++) { + if (matconv[a].attribs.tottang && matconv[a].attribs.tang[b].array) { + matconv[a].datatypes[numdata].index = matconv[a].attribs.tang[b].gl_index; + matconv[a].datatypes[numdata].size = 4; + matconv[a].datatypes[numdata].type = GL_FLOAT; + numdata++; + } } if (numdata != 0) { matconv[a].numdata = numdata; @@ -3105,15 +3107,17 @@ static void ccgDM_drawMappedFacesGLSL(DerivedMesh *dm, offset += sizeof(unsigned char) * 4; } } - if (matconv[i].attribs.tottang && matconv[i].attribs.tang.array) { - const float (*looptang)[4] = (const float (*)[4])matconv[i].attribs.tang.array + tot_loops; + for (b = 0; b < matconv[i].attribs.tottang; b++) { + if (matconv[i].attribs.tottang && matconv[i].attribs.tang[b].array) { + const float (*looptang)[4] = (const float (*)[4])matconv[i].attribs.tang[b].array + tot_loops; - copy_v4_v4((float *)&varray[offset], looptang[0]); - copy_v4_v4((float *)&varray[offset + max_element_size], looptang[3]); - copy_v4_v4((float *)&varray[offset + 2 * max_element_size], looptang[2]); - copy_v4_v4((float *)&varray[offset + 3 * max_element_size], looptang[1]); + copy_v4_v4((float *)&varray[offset], looptang[0]); + copy_v4_v4((float *)&varray[offset + max_element_size], looptang[3]); + copy_v4_v4((float *)&varray[offset + 2 * max_element_size], looptang[2]); + copy_v4_v4((float *)&varray[offset + 3 * max_element_size], looptang[1]); - offset += sizeof(float) * 4; + offset += sizeof(float) * 4; + } } tot_loops += 4; @@ -4361,6 +4365,7 @@ static void ccgDM_recalcLoopTri(DerivedMesh *UNUSED(dm)) static const MLoopTri *ccgDM_getLoopTriArray(DerivedMesh *dm) { + BLI_rw_mutex_lock(&loops_cache_rwlock, THREAD_LOCK_WRITE); if (dm->looptris.array) { BLI_assert(poly_to_tri_count(dm->numPolyData, dm->numLoopData) == dm->looptris.num); } @@ -4391,6 +4396,7 @@ static const MLoopTri *ccgDM_getLoopTriArray(DerivedMesh *dm) lt->poly = poly_index; } } + BLI_rw_mutex_unlock(&loops_cache_rwlock); return dm->looptris.array; } |