Merge branch 'blender2.7'
[blender.git] / source / blender / blenkernel / intern / object.c
1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public License
4  * as published by the Free Software Foundation; either version 2
5  * of the License, or (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software Foundation,
14  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
15  *
16  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
17  * All rights reserved.
18  */
19
20 /** \file
21  * \ingroup bke
22  */
23
24
25 #include <string.h>
26 #include <math.h>
27 #include <stdio.h>
28
29 #include "CLG_log.h"
30
31 #include "MEM_guardedalloc.h"
32
33 #include "DNA_anim_types.h"
34 #include "DNA_armature_types.h"
35 #include "DNA_camera_types.h"
36 #include "DNA_collection_types.h"
37 #include "DNA_constraint_types.h"
38 #include "DNA_gpencil_types.h"
39 #include "DNA_gpencil_modifier_types.h"
40 #include "DNA_key_types.h"
41 #include "DNA_light_types.h"
42 #include "DNA_lattice_types.h"
43 #include "DNA_material_types.h"
44 #include "DNA_meta_types.h"
45 #include "DNA_mesh_types.h"
46 #include "DNA_meshdata_types.h"
47 #include "DNA_movieclip_types.h"
48 #include "DNA_scene_types.h"
49 #include "DNA_screen_types.h"
50 #include "DNA_sequence_types.h"
51 #include "DNA_shader_fx_types.h"
52 #include "DNA_smoke_types.h"
53 #include "DNA_space_types.h"
54 #include "DNA_view3d_types.h"
55 #include "DNA_world_types.h"
56 #include "DNA_object_types.h"
57 #include "DNA_lightprobe_types.h"
58 #include "DNA_rigidbody_types.h"
59
60 #include "BLI_blenlib.h"
61 #include "BLI_math.h"
62 #include "BLI_threads.h"
63 #include "BLI_utildefines.h"
64 #include "BLI_linklist.h"
65 #include "BLI_kdtree.h"
66
67 #include "BLT_translation.h"
68
69 #include "BKE_pbvh.h"
70 #include "BKE_main.h"
71 #include "BKE_global.h"
72 #include "BKE_idprop.h"
73 #include "BKE_armature.h"
74 #include "BKE_action.h"
75 #include "BKE_deform.h"
76 #include "BKE_DerivedMesh.h"
77 #include "BKE_animsys.h"
78 #include "BKE_anim.h"
79 #include "BKE_collection.h"
80 #include "BKE_constraint.h"
81 #include "BKE_curve.h"
82 #include "BKE_displist.h"
83 #include "BKE_effect.h"
84 #include "BKE_fcurve.h"
85 #include "BKE_gpencil_modifier.h"
86 #include "BKE_icons.h"
87 #include "BKE_key.h"
88 #include "BKE_light.h"
89 #include "BKE_layer.h"
90 #include "BKE_lattice.h"
91 #include "BKE_library.h"
92 #include "BKE_library_query.h"
93 #include "BKE_library_remap.h"
94 #include "BKE_linestyle.h"
95 #include "BKE_mesh.h"
96 #include "BKE_editmesh.h"
97 #include "BKE_mball.h"
98 #include "BKE_modifier.h"
99 #include "BKE_multires.h"
100 #include "BKE_node.h"
101 #include "BKE_object.h"
102 #include "BKE_object_facemap.h"
103 #include "BKE_paint.h"
104 #include "BKE_particle.h"
105 #include "BKE_pointcache.h"
106 #include "BKE_lightprobe.h"
107 #include "BKE_rigidbody.h"
108 #include "BKE_scene.h"
109 #include "BKE_sequencer.h"
110 #include "BKE_shader_fx.h"
111 #include "BKE_speaker.h"
112 #include "BKE_softbody.h"
113 #include "BKE_subsurf.h"
114 #include "BKE_subdiv_ccg.h"
115 #include "BKE_material.h"
116 #include "BKE_camera.h"
117 #include "BKE_image.h"
118 #include "BKE_gpencil.h"
119
120 #include "DEG_depsgraph.h"
121 #include "DEG_depsgraph_query.h"
122
123 #include "DRW_engine.h"
124
125 #ifdef WITH_MOD_FLUID
126 #include "LBM_fluidsim.h"
127 #endif
128
129 #ifdef WITH_PYTHON
130 #include "BPY_extern.h"
131 #endif
132
133 #include "CCGSubSurf.h"
134 #include "atomic_ops.h"
135
136 static CLG_LogRef LOG = {"bke.object"};
137
138 /* Vertex parent modifies original BMesh which is not safe for threading.
139  * Ideally such a modification should be handled as a separate DAG update
140  * callback for mesh datablock, but for until it is actually supported use
141  * simpler solution with a mutex lock.
142  *                                               - sergey -
143  */
144 #define VPARENT_THREADING_HACK
145
146 #ifdef VPARENT_THREADING_HACK
147 static ThreadMutex vparent_lock = BLI_MUTEX_INITIALIZER;
148 #endif
149
150 void BKE_object_workob_clear(Object *workob)
151 {
152         memset(workob, 0, sizeof(Object));
153
154         workob->scale[0] = workob->scale[1] = workob->scale[2] = 1.0f;
155         workob->dscale[0] = workob->dscale[1] = workob->dscale[2] = 1.0f;
156         workob->rotmode = ROT_MODE_EUL;
157 }
158
159 void BKE_object_free_particlesystems(Object *ob)
160 {
161         ParticleSystem *psys;
162
163         while ((psys = BLI_pophead(&ob->particlesystem))) {
164                 psys_free(ob, psys);
165         }
166 }
167
168 void BKE_object_free_softbody(Object *ob)
169 {
170         sbFree(ob);
171 }
172
173 void BKE_object_free_curve_cache(Object *ob)
174 {
175         if (ob->runtime.curve_cache) {
176                 BKE_displist_free(&ob->runtime.curve_cache->disp);
177                 BKE_curve_bevelList_free(&ob->runtime.curve_cache->bev);
178                 if (ob->runtime.curve_cache->path) {
179                         free_path(ob->runtime.curve_cache->path);
180                 }
181                 BKE_nurbList_free(&ob->runtime.curve_cache->deformed_nurbs);
182                 MEM_freeN(ob->runtime.curve_cache);
183                 ob->runtime.curve_cache = NULL;
184         }
185 }
186
187 void BKE_object_free_modifiers(Object *ob, const int flag)
188 {
189         ModifierData *md;
190         GpencilModifierData *gp_md;
191
192         while ((md = BLI_pophead(&ob->modifiers))) {
193                 modifier_free_ex(md, flag);
194         }
195
196         while ((gp_md = BLI_pophead(&ob->greasepencil_modifiers))) {
197                 BKE_gpencil_modifier_free_ex(gp_md, flag);
198         }
199         /* particle modifiers were freed, so free the particlesystems as well */
200         BKE_object_free_particlesystems(ob);
201
202         /* same for softbody */
203         BKE_object_free_softbody(ob);
204
205         /* modifiers may have stored data in the DM cache */
206         BKE_object_free_derived_caches(ob);
207 }
208
209 void BKE_object_free_shaderfx(Object *ob, const int flag)
210 {
211         ShaderFxData *fx;
212
213         while ((fx = BLI_pophead(&ob->shader_fx))) {
214                 BKE_shaderfx_free_ex(fx, flag);
215         }
216 }
217
218 void BKE_object_modifier_hook_reset(Object *ob, HookModifierData *hmd)
219 {
220         /* reset functionality */
221         if (hmd->object) {
222                 bPoseChannel *pchan = BKE_pose_channel_find_name(hmd->object->pose, hmd->subtarget);
223
224                 if (hmd->subtarget[0] && pchan) {
225                         float imat[4][4], mat[4][4];
226
227                         /* calculate the world-space matrix for the pose-channel target first, then carry on as usual */
228                         mul_m4_m4m4(mat, hmd->object->obmat, pchan->pose_mat);
229
230                         invert_m4_m4(imat, mat);
231                         mul_m4_m4m4(hmd->parentinv, imat, ob->obmat);
232                 }
233                 else {
234                         invert_m4_m4(hmd->object->imat, hmd->object->obmat);
235                         mul_m4_m4m4(hmd->parentinv, hmd->object->imat, ob->obmat);
236                 }
237         }
238 }
239
240 void BKE_object_modifier_gpencil_hook_reset(Object *ob, HookGpencilModifierData *hmd)
241 {
242         if (hmd->object == NULL) {
243                 return;
244         }
245         /* reset functionality */
246         bPoseChannel *pchan = BKE_pose_channel_find_name(hmd->object->pose, hmd->subtarget);
247
248         if (hmd->subtarget[0] && pchan) {
249                 float imat[4][4], mat[4][4];
250
251                 /* calculate the world-space matrix for the pose-channel target first, then carry on as usual */
252                 mul_m4_m4m4(mat, hmd->object->obmat, pchan->pose_mat);
253
254                 invert_m4_m4(imat, mat);
255                 mul_m4_m4m4(hmd->parentinv, imat, ob->obmat);
256         }
257         else {
258                 invert_m4_m4(hmd->object->imat, hmd->object->obmat);
259                 mul_m4_m4m4(hmd->parentinv, hmd->object->imat, ob->obmat);
260         }
261 }
262
263 bool BKE_object_support_modifier_type_check(const Object *ob, int modifier_type)
264 {
265         const ModifierTypeInfo *mti;
266
267         mti = modifierType_getInfo(modifier_type);
268
269         /* only geometry objects should be able to get modifiers [#25291] */
270         if (!ELEM(ob->type, OB_MESH, OB_CURVE, OB_SURF, OB_FONT, OB_LATTICE)) {
271                 return false;
272         }
273
274         if (ob->type == OB_LATTICE && (mti->flags & eModifierTypeFlag_AcceptsLattice) == 0) {
275                 return false;
276         }
277
278         if (!((mti->flags & eModifierTypeFlag_AcceptsCVs) ||
279               (ob->type == OB_MESH && (mti->flags & eModifierTypeFlag_AcceptsMesh))))
280         {
281                 return false;
282         }
283
284         return true;
285 }
286
287 void BKE_object_link_modifiers(Scene *scene, struct Object *ob_dst, const struct Object *ob_src)
288 {
289         ModifierData *md;
290         BKE_object_free_modifiers(ob_dst, 0);
291
292         if (!ELEM(ob_dst->type, OB_MESH, OB_CURVE, OB_SURF, OB_FONT, OB_LATTICE)) {
293                 /* only objects listed above can have modifiers and linking them to objects
294                  * which doesn't have modifiers stack is quite silly */
295                 return;
296         }
297
298         for (md = ob_src->modifiers.first; md; md = md->next) {
299                 ModifierData *nmd = NULL;
300
301                 if (ELEM(md->type,
302                          eModifierType_Hook,
303                          eModifierType_Collision))
304                 {
305                         continue;
306                 }
307
308                 if (!BKE_object_support_modifier_type_check(ob_dst, md->type))
309                         continue;
310
311                 switch (md->type) {
312                         case eModifierType_Softbody:
313                                 BKE_object_copy_softbody(ob_dst, ob_src, 0);
314                                 break;
315                         case eModifierType_Skin:
316                                 /* ensure skin-node customdata exists */
317                                 BKE_mesh_ensure_skin_customdata(ob_dst->data);
318                                 break;
319                 }
320
321                 nmd = modifier_new(md->type);
322                 BLI_strncpy(nmd->name, md->name, sizeof(nmd->name));
323
324                 if (md->type == eModifierType_Multires) {
325                         /* Has to be done after mod creation, but *before* we actually copy its settings! */
326                         multiresModifier_sync_levels_ex(scene, ob_dst, (MultiresModifierData *)md, (MultiresModifierData *)nmd);
327                 }
328
329                 modifier_copyData(md, nmd);
330                 BLI_addtail(&ob_dst->modifiers, nmd);
331                 modifier_unique_name(&ob_dst->modifiers, nmd);
332         }
333
334         BKE_object_copy_particlesystems(ob_dst, ob_src, 0);
335
336         /* TODO: smoke?, cloth? */
337 }
338
339 /* Copy CCG related data. Used to sync copy of mesh with reshaped original
340  * mesh.
341  */
342 static void copy_ccg_data(Mesh *mesh_destination,
343                           Mesh *mesh_source,
344                           int layer_type)
345 {
346         BLI_assert(mesh_destination->totloop == mesh_source->totloop);
347         CustomData *data_destination = &mesh_destination->ldata;
348         CustomData *data_source = &mesh_source->ldata;
349         const int num_elements = mesh_source->totloop;
350         if (!CustomData_has_layer(data_source, layer_type)) {
351                 return;
352         }
353         const int layer_index = CustomData_get_layer_index(
354                 data_destination, layer_type);
355         CustomData_free_layer(
356                 data_destination, layer_type, num_elements, layer_index);
357         BLI_assert(!CustomData_has_layer(data_destination, layer_type));
358         CustomData_add_layer(
359                 data_destination, layer_type, CD_CALLOC, NULL, num_elements);
360         BLI_assert(CustomData_has_layer(data_destination, layer_type));
361         CustomData_copy_layer_type_data(data_source, data_destination,
362                                         layer_type, 0, 0, num_elements);
363 }
364
365 static void object_update_from_subsurf_ccg(Object *object)
366 {
367         /* Currently CCG is only created for Mesh objects. */
368         if (object->type != OB_MESH) {
369                 return;
370         }
371         /* Object was never evaluated, so can not have CCG subdivision surface. */
372         Mesh *mesh_eval = object->runtime.mesh_eval;
373         if (mesh_eval == NULL) {
374                 return;
375         }
376         SubdivCCG *subdiv_ccg = mesh_eval->runtime.subdiv_ccg;
377         if (subdiv_ccg == NULL) {
378                 return;
379         }
380         /* Check whether there is anything to be reshaped. */
381         if (!subdiv_ccg->dirty.coords && !subdiv_ccg->dirty.hidden) {
382                 return;
383         }
384         const int tot_level = mesh_eval->runtime.subdiv_ccg_tot_level;
385         Object *object_orig = DEG_get_original_object(object);
386         Mesh *mesh_orig = (Mesh *)object_orig->data;
387         multiresModifier_reshapeFromCCG(tot_level, mesh_orig, subdiv_ccg);
388         /* NOTE: we need to reshape into an original mesh from main database,
389          * allowing:
390          *
391          *  - Update copies of that mesh at any moment.
392          *  - Save the file without doing extra reshape.
393          *  - All the users of the mesh have updated displacement.
394          *
395          * However, the tricky part here is that we only know about sculpted
396          * state of a mesh on an object level, and object is being updated after
397          * mesh datablock is updated. This forces us to:
398          *
399          *  - Update mesh datablock from object evaluation, which is technically
400          *    forbidden, but there is no other place for this yet.
401          *  - Reshape to the original mesh from main database, and then copy updated
402          *    layer to copy of that mesh (since copy of the mesh has decoupled
403          *    custom data layers).
404          *
405          * All this is defeating all the designs we need to follow to allow safe
406          * threaded evaluation, but this is as good as we can make it within the
407          * current sculpt//evaluated mesh design. This is also how we've survived
408          * with old DerivedMesh based solutions. So, while this is all wrong and
409          * needs reconsideration, doesn't seem to be a big stopper for real
410          * production artists.
411          */
412         /* TODO(sergey): Solve this somehow, to be fully stable for threaded
413          * evaluation environment.
414          */
415         /* NOTE: runtime.mesh_orig is what was before assigning mesh_eval,
416          * it is orig as in what was in object_eval->data before evaluating
417          * modifier stack.
418          *
419          * mesh_cow is a copy-on-written version od object_orig->data.
420          */
421         Mesh *mesh_cow = object->runtime.mesh_orig;
422         copy_ccg_data(mesh_cow, mesh_orig, CD_MDISPS);
423         copy_ccg_data(mesh_cow, mesh_orig, CD_GRID_PAINT_MASK);
424         /* Everything is now up-to-date. */
425         subdiv_ccg->dirty.coords = false;
426         subdiv_ccg->dirty.hidden = false;
427 }
428
429 /* free data derived from mesh, called when mesh changes or is freed */
430 void BKE_object_free_derived_caches(Object *ob)
431 {
432         /* Also serves as signal to remake texspace.
433          *
434          * NOTE: This function can be called from threads on different objects
435          * sharing same data datablock. So we need to ensure atomic nature of
436          * data modification here.
437          */
438         if (ob->type == OB_MESH) {
439                 Mesh *me = ob->data;
440
441                 if (me && me->bb) {
442                         atomic_fetch_and_or_int32(&me->bb->flag, BOUNDBOX_DIRTY);
443                 }
444         }
445         else if (ELEM(ob->type, OB_SURF, OB_CURVE, OB_FONT)) {
446                 Curve *cu = ob->data;
447
448                 if (cu && cu->bb) {
449                         atomic_fetch_and_or_int32(&cu->bb->flag, BOUNDBOX_DIRTY);
450                 }
451         }
452
453         MEM_SAFE_FREE(ob->runtime.bb);
454
455         object_update_from_subsurf_ccg(ob);
456         BKE_object_free_derived_mesh_caches(ob);
457         BKE_armature_cached_bbone_deformation_free(ob);
458
459         if (ob->runtime.mesh_eval != NULL) {
460                 Mesh *mesh_eval = ob->runtime.mesh_eval;
461                 /* Restore initial pointer. */
462                 if (ob->data == mesh_eval) {
463                         ob->data = ob->runtime.mesh_orig;
464                 }
465                 /* Evaluated mesh points to edit mesh, but does not own it. */
466                 mesh_eval->edit_mesh = NULL;
467                 BKE_mesh_free(mesh_eval);
468                 BKE_libblock_free_data(&mesh_eval->id, false);
469                 MEM_freeN(mesh_eval);
470                 ob->runtime.mesh_eval = NULL;
471         }
472         if (ob->runtime.mesh_deform_eval != NULL) {
473                 Mesh *mesh_deform_eval = ob->runtime.mesh_deform_eval;
474                 BKE_mesh_free(mesh_deform_eval);
475                 BKE_libblock_free_data(&mesh_deform_eval->id, false);
476                 MEM_freeN(mesh_deform_eval);
477                 ob->runtime.mesh_deform_eval = NULL;
478         }
479
480         BKE_object_free_curve_cache(ob);
481
482         /* clear grease pencil data */
483         DRW_gpencil_freecache(ob);
484 }
485
486 void BKE_object_free_derived_mesh_caches(struct Object *ob)
487 {
488         if (ob->derivedFinal) {
489                 ob->derivedFinal->needsFree = 1;
490                 ob->derivedFinal->release(ob->derivedFinal);
491                 ob->derivedFinal = NULL;
492         }
493         if (ob->derivedDeform) {
494                 ob->derivedDeform->needsFree = 1;
495                 ob->derivedDeform->release(ob->derivedDeform);
496                 ob->derivedDeform = NULL;
497         }
498 }
499
500 void BKE_object_free_caches(Object *object)
501 {
502         ModifierData *md;
503         short update_flag = 0;
504
505         /* Free particle system caches holding paths. */
506         if (object->particlesystem.first) {
507                 ParticleSystem *psys;
508                 for (psys = object->particlesystem.first;
509                      psys != NULL;
510                      psys = psys->next)
511                 {
512                         psys_free_path_cache(psys, psys->edit);
513                         update_flag |= ID_RECALC_PSYS_REDO;
514                 }
515         }
516
517         /* Free memory used by cached derived meshes in the particle system modifiers. */
518         for (md = object->modifiers.first; md != NULL; md = md->next) {
519                 if (md->type == eModifierType_ParticleSystem) {
520                         ParticleSystemModifierData *psmd = (ParticleSystemModifierData *) md;
521                         if (psmd->mesh_final) {
522                                 BKE_id_free(NULL, psmd->mesh_final);
523                                 psmd->mesh_final = NULL;
524                                 if (psmd->mesh_original) {
525                                         BKE_id_free(NULL, psmd->mesh_original);
526                                         psmd->mesh_original = NULL;
527                                 }
528                                 psmd->flag |= eParticleSystemFlag_file_loaded;
529                                 update_flag |= ID_RECALC_GEOMETRY;
530                         }
531                 }
532         }
533
534         /* NOTE: If object is coming from a duplicator, it might be a temporary
535          * object created by dependency graph, which shares pointers with original
536          * object. In this case we can not free anything.
537          */
538         if ((object->base_flag & BASE_FROM_DUPLI) == 0) {
539                 BKE_object_free_derived_caches(object);
540                 update_flag |= ID_RECALC_GEOMETRY;
541         }
542
543         /* Tag object for update, so once memory critical operation is over and
544          * scene update routines are back to it's business the object will be
545          * guaranteed to be in a known state.
546          */
547         if (update_flag != 0) {
548                 DEG_id_tag_update(&object->id, update_flag);
549         }
550 }
551
552 /** Free (or release) any data used by this object (does not free the object itself). */
553 void BKE_object_free(Object *ob)
554 {
555         BKE_animdata_free((ID *)ob, false);
556
557         DRW_drawdata_free((ID *)ob);
558
559         /* BKE_<id>_free shall never touch to ID->us. Never ever. */
560         BKE_object_free_modifiers(ob, LIB_ID_CREATE_NO_USER_REFCOUNT);
561         BKE_object_free_shaderfx(ob, LIB_ID_CREATE_NO_USER_REFCOUNT);
562
563         MEM_SAFE_FREE(ob->mat);
564         MEM_SAFE_FREE(ob->matbits);
565         MEM_SAFE_FREE(ob->iuser);
566         MEM_SAFE_FREE(ob->runtime.bb);
567
568         BLI_freelistN(&ob->defbase);
569         BLI_freelistN(&ob->fmaps);
570         if (ob->pose) {
571                 BKE_pose_free_ex(ob->pose, false);
572                 ob->pose = NULL;
573         }
574         if (ob->mpath) {
575                 animviz_free_motionpath(ob->mpath);
576                 ob->mpath = NULL;
577         }
578
579         BKE_constraints_free_ex(&ob->constraints, false);
580
581         BKE_partdeflect_free(ob->pd);
582         BKE_rigidbody_free_object(ob, NULL);
583         BKE_rigidbody_free_constraint(ob);
584
585         sbFree(ob);
586
587         BKE_sculptsession_free(ob);
588
589         BLI_freelistN(&ob->pc_ids);
590
591         BLI_freelistN(&ob->lodlevels);
592
593         /* Free runtime curves data. */
594         if (ob->runtime.curve_cache) {
595                 BKE_curve_bevelList_free(&ob->runtime.curve_cache->bev);
596                 if (ob->runtime.curve_cache->path)
597                         free_path(ob->runtime.curve_cache->path);
598                 MEM_freeN(ob->runtime.curve_cache);
599                 ob->runtime.curve_cache = NULL;
600         }
601
602         BKE_previewimg_free(&ob->preview);
603 }
604
605 /* actual check for internal data, not context or flags */
606 bool BKE_object_is_in_editmode(const Object *ob)
607 {
608         if (ob->data == NULL) {
609                 return false;
610         }
611
612         switch (ob->type) {
613                 case OB_MESH:
614                         return ((Mesh *)ob->data)->edit_mesh != NULL;
615                 case OB_ARMATURE:
616                         return ((bArmature *)ob->data)->edbo != NULL;
617                 case OB_FONT:
618                         return ((Curve *)ob->data)->editfont != NULL;
619                 case OB_MBALL:
620                         return ((MetaBall *)ob->data)->editelems != NULL;
621                 case OB_LATTICE:
622                         return ((Lattice *)ob->data)->editlatt != NULL;
623                 case OB_SURF:
624                 case OB_CURVE:
625                         return ((Curve *)ob->data)->editnurb != NULL;
626                 default:
627                         return false;
628         }
629 }
630
631 bool BKE_object_is_in_editmode_vgroup(const Object *ob)
632 {
633         return (OB_TYPE_SUPPORT_VGROUP(ob->type) &&
634                 BKE_object_is_in_editmode(ob));
635 }
636
637 bool BKE_object_data_is_in_editmode(const ID *id)
638 {
639         const short type = GS(id->name);
640         BLI_assert(OB_DATA_SUPPORT_EDITMODE(type));
641         switch (type) {
642                 case ID_ME:
643                         return ((const Mesh *)id)->edit_mesh != NULL;
644                 case ID_CU:
645                         return (
646                                 (((const Curve *)id)->editnurb != NULL) ||
647                                 (((const Curve *)id)->editfont != NULL)
648                         );
649                 case ID_MB:
650                         return ((const MetaBall *)id)->editelems != NULL;
651                 case ID_LT:
652                         return ((const Lattice *)id)->editlatt != NULL;
653                 case ID_AR:
654                         return ((const bArmature *)id)->edbo != NULL;
655                 default:
656                         BLI_assert(0);
657                         return false;
658         }
659 }
660
661 bool BKE_object_is_in_wpaint_select_vert(const Object *ob)
662 {
663         if (ob->type == OB_MESH) {
664                 Mesh *me = ob->data;
665                 return ((ob->mode & OB_MODE_WEIGHT_PAINT) &&
666                         (me->edit_mesh == NULL) &&
667                         (ME_EDIT_PAINT_SEL_MODE(me) == SCE_SELECT_VERTEX));
668         }
669
670         return false;
671 }
672
673 bool BKE_object_has_mode_data(const struct Object *ob, eObjectMode object_mode)
674 {
675         if (object_mode & OB_MODE_EDIT) {
676                 if (BKE_object_is_in_editmode(ob)) {
677                         return true;
678                 }
679         }
680         else if (object_mode & OB_MODE_VERTEX_PAINT) {
681                 if (ob->sculpt && (ob->sculpt->mode_type == OB_MODE_VERTEX_PAINT)) {
682                         return true;
683                 }
684         }
685         else if (object_mode & OB_MODE_WEIGHT_PAINT) {
686                 if (ob->sculpt && (ob->sculpt->mode_type == OB_MODE_WEIGHT_PAINT)) {
687                         return true;
688                 }
689         }
690         else if (object_mode & OB_MODE_SCULPT) {
691                 if (ob->sculpt && (ob->sculpt->mode_type == OB_MODE_SCULPT)) {
692                         return true;
693                 }
694         }
695         else if (object_mode & OB_MODE_POSE) {
696                 if (ob->pose != NULL) {
697                         return true;
698                 }
699         }
700         return false;
701 }
702
703 bool BKE_object_is_mode_compat(const struct Object *ob, eObjectMode object_mode)
704 {
705         return ((ob->mode == object_mode) ||
706                 (ob->mode & object_mode) != 0);
707 }
708
709 /**
710  * Return which parts of the object are visible, as evaluated by depsgraph
711  */
712 int BKE_object_visibility(const Object *ob, const int dag_eval_mode)
713 {
714         if ((ob->base_flag & BASE_VISIBLE) == 0) {
715                 return 0;
716         }
717
718         /* Test which components the object has. */
719         int visibility = OB_VISIBLE_SELF;
720         if (ob->particlesystem.first) {
721                 visibility |= OB_VISIBLE_INSTANCES | OB_VISIBLE_PARTICLES;
722         }
723         else if (ob->transflag & OB_DUPLI) {
724                 visibility |= OB_VISIBLE_INSTANCES;
725         }
726
727         /* Optional hiding of self if there are particles or instancers. */
728         if (visibility & (OB_VISIBLE_PARTICLES | OB_VISIBLE_INSTANCES)) {
729                 switch ((eEvaluationMode)dag_eval_mode) {
730                         case DAG_EVAL_VIEWPORT:
731                                 if (!(ob->duplicator_visibility_flag & OB_DUPLI_FLAG_VIEWPORT)) {
732                                         visibility &= ~OB_VISIBLE_SELF;
733                                 }
734                                 break;
735                         case DAG_EVAL_RENDER:
736                                 if (!(ob->duplicator_visibility_flag & OB_DUPLI_FLAG_RENDER)) {
737                                         visibility &= ~OB_VISIBLE_SELF;
738                                 }
739                                 break;
740                 }
741         }
742
743         return visibility;
744 }
745
746 bool BKE_object_exists_check(Main *bmain, const Object *obtest)
747 {
748         Object *ob;
749
750         if (obtest == NULL) return false;
751
752         ob = bmain->object.first;
753         while (ob) {
754                 if (ob == obtest) return true;
755                 ob = ob->id.next;
756         }
757         return false;
758 }
759
760 /* *************************************************** */
761
762 static const char *get_obdata_defname(int type)
763 {
764         switch (type) {
765                 case OB_MESH: return DATA_("Mesh");
766                 case OB_CURVE: return DATA_("Curve");
767                 case OB_SURF: return DATA_("Surf");
768                 case OB_FONT: return DATA_("Text");
769                 case OB_MBALL: return DATA_("Mball");
770                 case OB_CAMERA: return DATA_("Camera");
771                 case OB_LAMP: return CTX_DATA_(BLT_I18NCONTEXT_ID_LIGHT, "Light");
772                 case OB_LATTICE: return DATA_("Lattice");
773                 case OB_ARMATURE: return DATA_("Armature");
774                 case OB_SPEAKER: return DATA_("Speaker");
775                 case OB_EMPTY: return DATA_("Empty");
776                 case OB_GPENCIL: return DATA_("GPencil");
777                 default:
778                         CLOG_ERROR(&LOG, "Internal error, bad type: %d", type);
779                         return DATA_("Empty");
780         }
781 }
782
783 void *BKE_object_obdata_add_from_type(Main *bmain, int type, const char *name)
784 {
785         if (name == NULL) {
786                 name = get_obdata_defname(type);
787         }
788
789         switch (type) {
790                 case OB_MESH:      return BKE_mesh_add(bmain, name);
791                 case OB_CURVE:     return BKE_curve_add(bmain, name, OB_CURVE);
792                 case OB_SURF:      return BKE_curve_add(bmain, name, OB_SURF);
793                 case OB_FONT:      return BKE_curve_add(bmain, name, OB_FONT);
794                 case OB_MBALL:     return BKE_mball_add(bmain, name);
795                 case OB_CAMERA:    return BKE_camera_add(bmain, name);
796                 case OB_LAMP:      return BKE_light_add(bmain, name);
797                 case OB_LATTICE:   return BKE_lattice_add(bmain, name);
798                 case OB_ARMATURE:  return BKE_armature_add(bmain, name);
799                 case OB_SPEAKER:   return BKE_speaker_add(bmain, name);
800                 case OB_LIGHTPROBE:return BKE_lightprobe_add(bmain, name);
801                 case OB_GPENCIL:   return BKE_gpencil_data_addnew(bmain, name);
802                 case OB_EMPTY:     return NULL;
803                 default:
804                         CLOG_ERROR(&LOG, "Internal error, bad type: %d", type);
805                         return NULL;
806         }
807 }
808
809 void BKE_object_init(Object *ob)
810 {
811         /* BLI_assert(MEMCMP_STRUCT_OFS_IS_ZERO(ob, id)); */  /* ob->type is already initialized... */
812
813         copy_v4_fl(ob->color, 1.0f);
814
815         ob->scale[0] = ob->scale[1] = ob->scale[2] = 1.0;
816         ob->dscale[0] = ob->dscale[1] = ob->dscale[2] = 1.0;
817
818         /* objects should default to having Euler XYZ rotations,
819          * but rotations default to quaternions
820          */
821         ob->rotmode = ROT_MODE_EUL;
822
823         unit_axis_angle(ob->rotAxis, &ob->rotAngle);
824         unit_axis_angle(ob->drotAxis, &ob->drotAngle);
825
826         unit_qt(ob->quat);
827         unit_qt(ob->dquat);
828
829         /* rotation locks should be 4D for 4 component rotations by default... */
830         ob->protectflag = OB_LOCK_ROT4D;
831
832         unit_m4(ob->constinv);
833         unit_m4(ob->parentinv);
834         unit_m4(ob->obmat);
835         ob->dt = OB_TEXTURE;
836         ob->empty_drawtype = OB_PLAINAXES;
837         ob->empty_drawsize = 1.0;
838         ob->empty_image_depth = OB_EMPTY_IMAGE_DEPTH_DEFAULT;
839         if (ob->type == OB_EMPTY) {
840                 copy_v2_fl(ob->ima_ofs, -0.5f);
841         }
842
843         if (ELEM(ob->type, OB_LAMP, OB_CAMERA, OB_SPEAKER)) {
844                 ob->trackflag = OB_NEGZ;
845                 ob->upflag = OB_POSY;
846         }
847         else {
848                 ob->trackflag = OB_POSY;
849                 ob->upflag = OB_POSZ;
850         }
851
852         ob->instance_faces_scale = 1.0;
853
854         ob->col_group = 0x01;
855         ob->col_mask = 0xffff;
856         ob->preview = NULL;
857         ob->duplicator_visibility_flag = OB_DUPLI_FLAG_VIEWPORT | OB_DUPLI_FLAG_RENDER;
858
859         /* NT fluid sim defaults */
860         ob->fluidsimSettings = NULL;
861
862         BLI_listbase_clear(&ob->pc_ids);
863
864         /* Animation Visualization defaults */
865         animviz_settings_init(&ob->avs);
866 }
867
868 /* more general add: creates minimum required data, but without vertices etc. */
869 Object *BKE_object_add_only_object(Main *bmain, int type, const char *name)
870 {
871         Object *ob;
872
873         if (!name)
874                 name = get_obdata_defname(type);
875
876         ob = BKE_libblock_alloc(bmain, ID_OB, name, 0);
877
878         /* We increase object user count when linking to Collections. */
879         id_us_min(&ob->id);
880
881         /* default object vars */
882         ob->type = type;
883
884         BKE_object_init(ob);
885
886         return ob;
887 }
888
889
890 static Object *object_add_common(Main *bmain, ViewLayer *view_layer, int type, const char *name)
891 {
892         Object *ob;
893
894         ob = BKE_object_add_only_object(bmain, type, name);
895         ob->data = BKE_object_obdata_add_from_type(bmain, type, name);
896         BKE_view_layer_base_deselect_all(view_layer);
897
898         DEG_id_tag_update_ex(bmain, &ob->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY | ID_RECALC_ANIMATION);
899         return ob;
900 }
901
902 /**
903  * General add: to scene, with layer from area and default name
904  *
905  * Object is added to the active Collection.
906  * If there is no linked collection to the active ViewLayer we create a new one.
907  */
908 /* creates minimum required data, but without vertices etc. */
909 Object *BKE_object_add(
910         Main *bmain, Scene *UNUSED(scene), ViewLayer *view_layer,
911         int type, const char *name)
912 {
913         Object *ob;
914         Base *base;
915         LayerCollection *layer_collection;
916
917         ob = object_add_common(bmain, view_layer, type, name);
918
919         layer_collection = BKE_layer_collection_get_active(view_layer);
920         BKE_collection_object_add(bmain, layer_collection->collection, ob);
921
922         base = BKE_view_layer_base_find(view_layer, ob);
923         BKE_view_layer_base_select_and_set_active(view_layer, base);
924
925         return ob;
926 }
927
928 /**
929  * Add a new object, using another one as a reference
930  *
931  * \param ob_src: object to use to determine the collections of the new object.
932  */
933 Object *BKE_object_add_from(
934         Main *bmain, Scene *scene, ViewLayer *view_layer,
935         int type, const char *name, Object *ob_src)
936 {
937         Object *ob;
938         Base *base;
939
940         ob = object_add_common(bmain, view_layer, type, name);
941         BKE_collection_object_add_from(bmain, scene, ob_src, ob);
942
943         base = BKE_view_layer_base_find(view_layer, ob);
944         BKE_view_layer_base_select_and_set_active(view_layer, base);
945
946         return ob;
947 }
948
949 /**
950  * Add a new object, but assign the given datablock as the ob->data
951  * for the newly created object.
952  *
953  * \param data: The datablock to assign as ob->data for the new object.
954  *             This is assumed to be of the correct type.
955  * \param do_id_user: If true, id_us_plus() will be called on data when
956  *                 assigning it to the object.
957  */
958 Object *BKE_object_add_for_data(
959         Main *bmain, ViewLayer *view_layer,
960         int type, const char *name, ID *data, bool do_id_user)
961 {
962         Object *ob;
963         Base *base;
964         LayerCollection *layer_collection;
965
966         /* same as object_add_common, except we don't create new ob->data */
967         ob = BKE_object_add_only_object(bmain, type, name);
968         ob->data = data;
969         if (do_id_user) id_us_plus(data);
970
971         BKE_view_layer_base_deselect_all(view_layer);
972         DEG_id_tag_update_ex(bmain, &ob->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY | ID_RECALC_ANIMATION);
973
974         layer_collection = BKE_layer_collection_get_active(view_layer);
975         BKE_collection_object_add(bmain, layer_collection->collection, ob);
976
977         base = BKE_view_layer_base_find(view_layer, ob);
978         BKE_view_layer_base_select_and_set_active(view_layer, base);
979
980         return ob;
981 }
982
983
984 void BKE_object_copy_softbody(struct Object *ob_dst, const struct Object *ob_src, const int flag)
985 {
986         SoftBody *sb = ob_src->soft;
987         SoftBody *sbn;
988         bool tagged_no_main = ob_dst->id.tag & LIB_TAG_NO_MAIN;
989
990         ob_dst->softflag = ob_src->softflag;
991         if (sb == NULL) {
992                 ob_dst->soft = NULL;
993                 return;
994         }
995
996         sbn = MEM_dupallocN(sb);
997
998         if ((flag & LIB_ID_COPY_CACHES) == 0) {
999                 sbn->totspring = sbn->totpoint = 0;
1000                 sbn->bpoint = NULL;
1001                 sbn->bspring = NULL;
1002         }
1003         else {
1004                 sbn->totspring = sb->totspring;
1005                 sbn->totpoint = sb->totpoint;
1006
1007                 if (sbn->bpoint) {
1008                         int i;
1009
1010                         sbn->bpoint = MEM_dupallocN(sbn->bpoint);
1011
1012                         for (i = 0; i < sbn->totpoint; i++) {
1013                                 if (sbn->bpoint[i].springs)
1014                                         sbn->bpoint[i].springs = MEM_dupallocN(sbn->bpoint[i].springs);
1015                         }
1016                 }
1017
1018                 if (sb->bspring)
1019                         sbn->bspring = MEM_dupallocN(sb->bspring);
1020         }
1021
1022         sbn->keys = NULL;
1023         sbn->totkey = sbn->totpointkey = 0;
1024
1025         sbn->scratch = NULL;
1026
1027         if (tagged_no_main == 0) {
1028                 sbn->shared = MEM_dupallocN(sb->shared);
1029                 sbn->shared->pointcache = BKE_ptcache_copy_list(&sbn->shared->ptcaches, &sb->shared->ptcaches, flag);
1030         }
1031
1032         if (sb->effector_weights)
1033                 sbn->effector_weights = MEM_dupallocN(sb->effector_weights);
1034
1035         ob_dst->soft = sbn;
1036 }
1037
1038 ParticleSystem *BKE_object_copy_particlesystem(ParticleSystem *psys, const int flag)
1039 {
1040         ParticleSystem *psysn = MEM_dupallocN(psys);
1041
1042         psys_copy_particles(psysn, psys);
1043
1044         if (psys->clmd) {
1045                 psysn->clmd = (ClothModifierData *)modifier_new(eModifierType_Cloth);
1046                 modifier_copyData_ex((ModifierData *)psys->clmd, (ModifierData *)psysn->clmd, flag);
1047                 psys->hair_in_mesh = psys->hair_out_mesh = NULL;
1048         }
1049
1050         BLI_duplicatelist(&psysn->targets, &psys->targets);
1051
1052         psysn->pathcache = NULL;
1053         psysn->childcache = NULL;
1054         psysn->edit = NULL;
1055         psysn->pdd = NULL;
1056         psysn->effectors = NULL;
1057         psysn->tree = NULL;
1058         psysn->bvhtree = NULL;
1059         psysn->batch_cache = NULL;
1060
1061         BLI_listbase_clear(&psysn->pathcachebufs);
1062         BLI_listbase_clear(&psysn->childcachebufs);
1063
1064         if (flag & LIB_ID_CREATE_NO_MAIN) {
1065                 BLI_assert((psys->flag & PSYS_SHARED_CACHES) == 0);
1066                 psysn->flag |= PSYS_SHARED_CACHES;
1067                 BLI_assert(psysn->pointcache != NULL);
1068         }
1069         else {
1070                 psysn->pointcache = BKE_ptcache_copy_list(&psysn->ptcaches, &psys->ptcaches, flag);
1071         }
1072
1073         /* XXX - from reading existing code this seems correct but intended usage of
1074          * pointcache should /w cloth should be added in 'ParticleSystem' - campbell */
1075         if (psysn->clmd) {
1076                 psysn->clmd->point_cache = psysn->pointcache;
1077         }
1078
1079         if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) {
1080                 id_us_plus((ID *)psysn->part);
1081         }
1082
1083         return psysn;
1084 }
1085
1086 void BKE_object_copy_particlesystems(Object *ob_dst, const Object *ob_src, const int flag)
1087 {
1088         ParticleSystem *psys, *npsys;
1089         ModifierData *md;
1090
1091         if (ob_dst->type != OB_MESH) {
1092                 /* currently only mesh objects can have soft body */
1093                 return;
1094         }
1095
1096         BLI_listbase_clear(&ob_dst->particlesystem);
1097         for (psys = ob_src->particlesystem.first; psys; psys = psys->next) {
1098                 npsys = BKE_object_copy_particlesystem(psys, flag);
1099
1100                 BLI_addtail(&ob_dst->particlesystem, npsys);
1101
1102                 /* need to update particle modifiers too */
1103                 for (md = ob_dst->modifiers.first; md; md = md->next) {
1104                         if (md->type == eModifierType_ParticleSystem) {
1105                                 ParticleSystemModifierData *psmd = (ParticleSystemModifierData *)md;
1106                                 if (psmd->psys == psys)
1107                                         psmd->psys = npsys;
1108                         }
1109                         else if (md->type == eModifierType_DynamicPaint) {
1110                                 DynamicPaintModifierData *pmd = (DynamicPaintModifierData *)md;
1111                                 if (pmd->brush) {
1112                                         if (pmd->brush->psys == psys) {
1113                                                 pmd->brush->psys = npsys;
1114                                         }
1115                                 }
1116                         }
1117                         else if (md->type == eModifierType_Smoke) {
1118                                 SmokeModifierData *smd = (SmokeModifierData *) md;
1119
1120                                 if (smd->type == MOD_SMOKE_TYPE_FLOW) {
1121                                         if (smd->flow) {
1122                                                 if (smd->flow->psys == psys)
1123                                                         smd->flow->psys = npsys;
1124                                         }
1125                                 }
1126                         }
1127                 }
1128         }
1129 }
1130
1131 static void copy_object_pose(Object *obn, const Object *ob, const int flag)
1132 {
1133         bPoseChannel *chan;
1134
1135         /* note: need to clear obn->pose pointer first,
1136          * so that BKE_pose_copy_data works (otherwise there's a crash) */
1137         obn->pose = NULL;
1138         BKE_pose_copy_data_ex(&obn->pose, ob->pose, flag, true);  /* true = copy constraints */
1139
1140         for (chan = obn->pose->chanbase.first; chan; chan = chan->next) {
1141                 bConstraint *con;
1142
1143                 chan->flag &= ~(POSE_LOC | POSE_ROT | POSE_SIZE);
1144
1145                 /* XXX Remapping object pointing onto itself should be handled by generic BKE_library_remap stuff, but...
1146                  *     the flush_constraint_targets callback am not sure about, so will delay that for now. */
1147                 for (con = chan->constraints.first; con; con = con->next) {
1148                         const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con);
1149                         ListBase targets = {NULL, NULL};
1150                         bConstraintTarget *ct;
1151
1152                         if (cti && cti->get_constraint_targets) {
1153                                 cti->get_constraint_targets(con, &targets);
1154
1155                                 for (ct = targets.first; ct; ct = ct->next) {
1156                                         if (ct->tar == ob)
1157                                                 ct->tar = obn;
1158                                 }
1159
1160                                 if (cti->flush_constraint_targets)
1161                                         cti->flush_constraint_targets(con, &targets, 0);
1162                         }
1163                 }
1164         }
1165 }
1166
1167 static void copy_object_lod(Object *obn, const Object *ob, const int UNUSED(flag))
1168 {
1169         BLI_duplicatelist(&obn->lodlevels, &ob->lodlevels);
1170
1171         obn->currentlod = (LodLevel *)obn->lodlevels.first;
1172 }
1173
1174 bool BKE_object_pose_context_check(const Object *ob)
1175 {
1176         if ((ob) &&
1177             (ob->type == OB_ARMATURE) &&
1178             (ob->pose) &&
1179             (ob->mode & OB_MODE_POSE))
1180         {
1181                 return true;
1182         }
1183         else {
1184                 return false;
1185         }
1186 }
1187
1188 Object *BKE_object_pose_armature_get(Object *ob)
1189 {
1190         if (ob == NULL)
1191                 return NULL;
1192
1193         if (BKE_object_pose_context_check(ob))
1194                 return ob;
1195
1196         ob = modifiers_isDeformedByArmature(ob);
1197
1198         /* Only use selected check when non-active. */
1199         if (BKE_object_pose_context_check(ob))
1200                 return ob;
1201
1202         return NULL;
1203 }
1204
1205 Object *BKE_object_pose_armature_get_visible(Object *ob, ViewLayer *view_layer, View3D *v3d)
1206 {
1207         Object *ob_armature = BKE_object_pose_armature_get(ob);
1208         if (ob_armature) {
1209                 Base *base = BKE_view_layer_base_find(view_layer, ob_armature);
1210                 if (base) {
1211                         if (BASE_VISIBLE(v3d, base)) {
1212                                 return ob_armature;
1213                         }
1214                 }
1215         }
1216         return NULL;
1217 }
1218
1219 /**
1220  * Access pose array with special check to get pose object when in weight paint mode.
1221  */
1222 Object **BKE_object_pose_array_get_ex(ViewLayer *view_layer, View3D *v3d, uint *r_objects_len, bool unique)
1223 {
1224         Object *ob_active = OBACT(view_layer);
1225         Object *ob_pose = BKE_object_pose_armature_get(ob_active);
1226         Object **objects = NULL;
1227         if (ob_pose == ob_active) {
1228                 objects = BKE_view_layer_array_from_objects_in_mode(
1229                         view_layer, v3d, r_objects_len, {
1230                             .object_mode = OB_MODE_POSE,
1231                             .no_dup_data = unique,
1232                         });
1233         }
1234         else if (ob_pose != NULL) {
1235                 *r_objects_len = 1;
1236                 objects = MEM_mallocN(sizeof(*objects), __func__);
1237                 objects[0] = ob_pose;
1238         }
1239         else {
1240                 *r_objects_len = 0;
1241                 objects = MEM_mallocN(0, __func__);
1242         }
1243         return objects;
1244 }
1245 Object **BKE_object_pose_array_get_unique(ViewLayer *view_layer, View3D *v3d, uint *r_objects_len)
1246 {
1247         return BKE_object_pose_array_get_ex(view_layer, v3d, r_objects_len, true);
1248 }
1249 Object **BKE_object_pose_array_get(ViewLayer *view_layer, View3D *v3d, uint *r_objects_len)
1250 {
1251         return BKE_object_pose_array_get_ex(view_layer, v3d, r_objects_len, false);
1252 }
1253
1254 Base **BKE_object_pose_base_array_get_ex(ViewLayer *view_layer, View3D *v3d, uint *r_bases_len, bool unique)
1255 {
1256         Base *base_active = BASACT(view_layer);
1257         Object *ob_pose = base_active ? BKE_object_pose_armature_get(base_active->object) : NULL;
1258         Base *base_pose = NULL;
1259         Base **bases = NULL;
1260
1261         if (base_active) {
1262                 if (ob_pose == base_active->object) {
1263                         base_pose = base_active;
1264                 }
1265                 else {
1266                         base_pose = BKE_view_layer_base_find(view_layer, ob_pose);
1267                 }
1268         }
1269
1270         if (base_active && (base_pose == base_active)) {
1271                 bases = BKE_view_layer_array_from_bases_in_mode(
1272                         view_layer, v3d, r_bases_len, {
1273                             .object_mode = OB_MODE_POSE,
1274                             .no_dup_data = unique,
1275                         });
1276         }
1277         else if (base_pose != NULL) {
1278                 *r_bases_len = 1;
1279                 bases = MEM_mallocN(sizeof(*bases), __func__);
1280                 bases[0] = base_pose;
1281         }
1282         else {
1283                 *r_bases_len = 0;
1284                 bases = MEM_mallocN(0, __func__);
1285         }
1286         return bases;
1287 }
1288 Base **BKE_object_pose_base_array_get_unique(ViewLayer *view_layer, View3D *v3d, uint *r_bases_len)
1289 {
1290         return BKE_object_pose_base_array_get_ex(view_layer, v3d, r_bases_len, true);
1291 }
1292 Base **BKE_object_pose_base_array_get(ViewLayer *view_layer, View3D *v3d, uint *r_bases_len)
1293 {
1294         return BKE_object_pose_base_array_get_ex(view_layer, v3d, r_bases_len, false);
1295 }
1296
1297 void BKE_object_transform_copy(Object *ob_tar, const Object *ob_src)
1298 {
1299         copy_v3_v3(ob_tar->loc, ob_src->loc);
1300         copy_v3_v3(ob_tar->rot, ob_src->rot);
1301         copy_v3_v3(ob_tar->quat, ob_src->quat);
1302         copy_v3_v3(ob_tar->rotAxis, ob_src->rotAxis);
1303         ob_tar->rotAngle = ob_src->rotAngle;
1304         ob_tar->rotmode = ob_src->rotmode;
1305         copy_v3_v3(ob_tar->scale, ob_src->scale);
1306 }
1307
1308 /**
1309  * Only copy internal data of Object ID from source to already allocated/initialized destination.
1310  * You probably never want to use that directly, use BKE_id_copy or BKE_id_copy_ex for typical needs.
1311  *
1312  * WARNING! This function will not handle ID user count!
1313  *
1314  * \param flag: Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more).
1315  */
1316 void BKE_object_copy_data(Main *bmain, Object *ob_dst, const Object *ob_src, const int flag)
1317 {
1318         ModifierData *md;
1319         GpencilModifierData *gmd;
1320         ShaderFxData *fx;
1321
1322         /* Do not copy runtime data. */
1323         BKE_object_runtime_reset_on_copy(ob_dst, flag);
1324
1325         /* We never handle usercount here for own data. */
1326         const int flag_subdata = flag | LIB_ID_CREATE_NO_USER_REFCOUNT;
1327
1328         if (ob_src->totcol) {
1329                 ob_dst->mat = MEM_dupallocN(ob_src->mat);
1330                 ob_dst->matbits = MEM_dupallocN(ob_src->matbits);
1331                 ob_dst->totcol = ob_src->totcol;
1332         }
1333         else if (ob_dst->mat != NULL || ob_dst->matbits != NULL) {
1334                 /* This shall not be needed, but better be safe than sorry. */
1335                 BLI_assert(!"Object copy: non-NULL material pointers with zero counter, should not happen.");
1336                 ob_dst->mat = NULL;
1337                 ob_dst->matbits = NULL;
1338         }
1339
1340         if (ob_src->iuser) ob_dst->iuser = MEM_dupallocN(ob_src->iuser);
1341
1342         if (ob_src->runtime.bb) ob_dst->runtime.bb = MEM_dupallocN(ob_src->runtime.bb);
1343
1344         BLI_listbase_clear(&ob_dst->modifiers);
1345
1346         for (md = ob_src->modifiers.first; md; md = md->next) {
1347                 ModifierData *nmd = modifier_new(md->type);
1348                 BLI_strncpy(nmd->name, md->name, sizeof(nmd->name));
1349                 modifier_copyData_ex(md, nmd, flag_subdata);
1350                 BLI_addtail(&ob_dst->modifiers, nmd);
1351         }
1352
1353         BLI_listbase_clear(&ob_dst->greasepencil_modifiers);
1354
1355         for (gmd = ob_src->greasepencil_modifiers.first; gmd; gmd = gmd->next) {
1356                 GpencilModifierData *nmd = BKE_gpencil_modifier_new(gmd->type);
1357                 BLI_strncpy(nmd->name, gmd->name, sizeof(nmd->name));
1358                 BKE_gpencil_modifier_copyData_ex(gmd, nmd, flag_subdata);
1359                 BLI_addtail(&ob_dst->greasepencil_modifiers, nmd);
1360         }
1361
1362         BLI_listbase_clear(&ob_dst->shader_fx);
1363
1364         for (fx = ob_src->shader_fx.first; fx; fx = fx->next) {
1365                 ShaderFxData *nfx = BKE_shaderfx_new(fx->type);
1366                 BLI_strncpy(nfx->name, fx->name, sizeof(nfx->name));
1367                 BKE_shaderfx_copyData_ex(fx, nfx, flag_subdata);
1368                 BLI_addtail(&ob_dst->shader_fx, nfx);
1369         }
1370
1371         if (ob_src->pose) {
1372                 copy_object_pose(ob_dst, ob_src, flag_subdata);
1373                 /* backwards compat... non-armatures can get poses in older files? */
1374                 if (ob_src->type == OB_ARMATURE) {
1375                         const bool do_pose_id_user = (flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0;
1376                         BKE_pose_rebuild(bmain, ob_dst, ob_dst->data, do_pose_id_user);
1377                 }
1378         }
1379         defgroup_copy_list(&ob_dst->defbase, &ob_src->defbase);
1380         BKE_object_facemap_copy_list(&ob_dst->fmaps, &ob_src->fmaps);
1381         BKE_constraints_copy_ex(&ob_dst->constraints, &ob_src->constraints, flag_subdata, true);
1382
1383         ob_dst->mode = ob_dst->type != OB_GPENCIL ? OB_MODE_OBJECT : ob_dst->mode;
1384         ob_dst->sculpt = NULL;
1385
1386         if (ob_src->pd) {
1387                 ob_dst->pd = MEM_dupallocN(ob_src->pd);
1388                 if (ob_dst->pd->rng) {
1389                         ob_dst->pd->rng = MEM_dupallocN(ob_src->pd->rng);
1390                 }
1391         }
1392         BKE_object_copy_softbody(ob_dst, ob_src, flag_subdata);
1393         ob_dst->rigidbody_object = BKE_rigidbody_copy_object(ob_src, flag_subdata);
1394         ob_dst->rigidbody_constraint = BKE_rigidbody_copy_constraint(ob_src, flag_subdata);
1395
1396         BKE_object_copy_particlesystems(ob_dst, ob_src, flag_subdata);
1397
1398         ob_dst->derivedDeform = NULL;
1399         ob_dst->derivedFinal = NULL;
1400
1401         BLI_listbase_clear((ListBase *)&ob_dst->drawdata);
1402         BLI_listbase_clear(&ob_dst->pc_ids);
1403
1404         ob_dst->avs = ob_src->avs;
1405         ob_dst->mpath = animviz_copy_motionpath(ob_src->mpath);
1406
1407         copy_object_lod(ob_dst, ob_src, flag_subdata);
1408
1409         /* Do not copy object's preview (mostly due to the fact renderers create temp copy of objects). */
1410         if ((flag & LIB_ID_COPY_NO_PREVIEW) == 0 && false) {  /* XXX TODO temp hack */
1411                 BKE_previewimg_id_copy(&ob_dst->id, &ob_src->id);
1412         }
1413         else {
1414                 ob_dst->preview = NULL;
1415         }
1416 }
1417
1418 /* copy objects, will re-initialize cached simulation data */
1419 Object *BKE_object_copy(Main *bmain, const Object *ob)
1420 {
1421         Object *ob_copy;
1422         BKE_id_copy(bmain, &ob->id, (ID **)&ob_copy);
1423
1424         /* We increase object user count when linking to Collections. */
1425         id_us_min(&ob_copy->id);
1426
1427         return ob_copy;
1428 }
1429
1430 Object *BKE_object_duplicate(Main *bmain, const Object *ob, const int dupflag)
1431 {
1432         Material ***matarar;
1433         ID *id;
1434         int a, didit;
1435         Object *obn = BKE_object_copy(bmain, ob);
1436
1437         /* 0 == full linked. */
1438         if (dupflag == 0) {
1439                 return obn;
1440         }
1441
1442 #define ID_NEW_REMAP_US(a)      if (      (a)->id.newid) { (a) = (void *)(a)->id.newid;       (a)->id.us++; }
1443 #define ID_NEW_REMAP_US2(a)     if (((ID *)a)->newid)    { (a) = ((ID  *)a)->newid;     ((ID *)a)->us++;    }
1444
1445         /* duplicates using userflags */
1446         if (dupflag & USER_DUP_ACT) {
1447                 BKE_animdata_copy_id_action(bmain, &obn->id, true);
1448         }
1449
1450         if (dupflag & USER_DUP_MAT) {
1451                 for (a = 0; a < obn->totcol; a++) {
1452                         id = (ID *)obn->mat[a];
1453                         if (id) {
1454                                 ID_NEW_REMAP_US(obn->mat[a])
1455                                 else {
1456                                         obn->mat[a] = ID_NEW_SET(obn->mat[a], BKE_material_copy(bmain, obn->mat[a]));
1457                                 }
1458                                 id_us_min(id);
1459
1460                                 if (dupflag & USER_DUP_ACT) {
1461                                         BKE_animdata_copy_id_action(bmain, &obn->mat[a]->id, true);
1462                                 }
1463                         }
1464                 }
1465         }
1466         if (dupflag & USER_DUP_PSYS) {
1467                 ParticleSystem *psys;
1468                 for (psys = obn->particlesystem.first; psys; psys = psys->next) {
1469                         id = (ID *) psys->part;
1470                         if (id) {
1471                                 ID_NEW_REMAP_US(psys->part)
1472                                 else {
1473                                         psys->part = ID_NEW_SET(psys->part, BKE_particlesettings_copy(bmain, psys->part));
1474                                 }
1475
1476                                 if (dupflag & USER_DUP_ACT) {
1477                                         BKE_animdata_copy_id_action(bmain, &psys->part->id, true);
1478                                 }
1479
1480                                 id_us_min(id);
1481                         }
1482                 }
1483         }
1484
1485         id = obn->data;
1486         didit = 0;
1487
1488         switch (obn->type) {
1489                 case OB_MESH:
1490                         if (dupflag & USER_DUP_MESH) {
1491                                 ID_NEW_REMAP_US2(obn->data)
1492                                 else {
1493                                         obn->data = ID_NEW_SET(obn->data, BKE_mesh_copy(bmain, obn->data));
1494                                         didit = 1;
1495                                 }
1496                                 id_us_min(id);
1497                         }
1498                         break;
1499                 case OB_CURVE:
1500                         if (dupflag & USER_DUP_CURVE) {
1501                                 ID_NEW_REMAP_US2(obn->data)
1502                                 else {
1503                                         obn->data = ID_NEW_SET(obn->data, BKE_curve_copy(bmain, obn->data));
1504                                         didit = 1;
1505                                 }
1506                                 id_us_min(id);
1507                         }
1508                         break;
1509                 case OB_SURF:
1510                         if (dupflag & USER_DUP_SURF) {
1511                                 ID_NEW_REMAP_US2(obn->data)
1512                                 else {
1513                                         obn->data = ID_NEW_SET(obn->data, BKE_curve_copy(bmain, obn->data));
1514                                         didit = 1;
1515                                 }
1516                                 id_us_min(id);
1517                         }
1518                         break;
1519                 case OB_FONT:
1520                         if (dupflag & USER_DUP_FONT) {
1521                                 ID_NEW_REMAP_US2(obn->data)
1522                                 else {
1523                                         obn->data = ID_NEW_SET(obn->data, BKE_curve_copy(bmain, obn->data));
1524                                         didit = 1;
1525                                 }
1526                                 id_us_min(id);
1527                         }
1528                         break;
1529                 case OB_MBALL:
1530                         if (dupflag & USER_DUP_MBALL) {
1531                                 ID_NEW_REMAP_US2(obn->data)
1532                                 else {
1533                                         obn->data = ID_NEW_SET(obn->data, BKE_mball_copy(bmain, obn->data));
1534                                         didit = 1;
1535                                 }
1536                                 id_us_min(id);
1537                         }
1538                         break;
1539                 case OB_LAMP:
1540                         if (dupflag & USER_DUP_LAMP) {
1541                                 ID_NEW_REMAP_US2(obn->data)
1542                                 else {
1543                                         obn->data = ID_NEW_SET(obn->data, BKE_light_copy(bmain, obn->data));
1544                                         didit = 1;
1545                                 }
1546                                 id_us_min(id);
1547                         }
1548                         break;
1549                 case OB_ARMATURE:
1550                         DEG_id_tag_update(&obn->id, ID_RECALC_GEOMETRY);
1551                         if (obn->pose)
1552                                 BKE_pose_tag_recalc(bmain, obn->pose);
1553                         if (dupflag & USER_DUP_ARM) {
1554                                 ID_NEW_REMAP_US2(obn->data)
1555                                 else {
1556                                         obn->data = ID_NEW_SET(obn->data, BKE_armature_copy(bmain, obn->data));
1557                                         BKE_pose_rebuild(bmain, obn, obn->data, true);
1558                                         didit = 1;
1559                                 }
1560                                 id_us_min(id);
1561                         }
1562                         break;
1563                 case OB_LATTICE:
1564                         if (dupflag != 0) {
1565                                 ID_NEW_REMAP_US2(obn->data)
1566                                 else {
1567                                         obn->data = ID_NEW_SET(obn->data, BKE_lattice_copy(bmain, obn->data));
1568                                         didit = 1;
1569                                 }
1570                                 id_us_min(id);
1571                         }
1572                         break;
1573                 case OB_CAMERA:
1574                         if (dupflag != 0) {
1575                                 ID_NEW_REMAP_US2(obn->data)
1576                                 else {
1577                                         obn->data = ID_NEW_SET(obn->data, BKE_camera_copy(bmain, obn->data));
1578                                         didit = 1;
1579                                 }
1580                                 id_us_min(id);
1581                         }
1582                         break;
1583                 case OB_LIGHTPROBE:
1584                         if (dupflag != 0) {
1585                                 ID_NEW_REMAP_US2(obn->data)
1586                                 else {
1587                                         obn->data = ID_NEW_SET(obn->data, BKE_lightprobe_copy(bmain, obn->data));
1588                                         didit = 1;
1589                                 }
1590                                 id_us_min(id);
1591                         }
1592                         break;
1593                 case OB_SPEAKER:
1594                         if (dupflag != 0) {
1595                                 ID_NEW_REMAP_US2(obn->data)
1596                                 else {
1597                                         obn->data = ID_NEW_SET(obn->data, BKE_speaker_copy(bmain, obn->data));
1598                                         didit = 1;
1599                                 }
1600                                 id_us_min(id);
1601                         }
1602                         break;
1603                 case OB_GPENCIL:
1604                         if (dupflag != 0) {
1605                                 ID_NEW_REMAP_US2(obn->data)
1606                                 else {
1607                                         obn->data = ID_NEW_SET(obn->data, BKE_gpencil_copy(bmain, obn->data));
1608                                         didit = 1;
1609                                 }
1610                                 id_us_min(id);
1611                         }
1612                         break;
1613         }
1614
1615         /* Check if obdata is copied. */
1616         if (didit) {
1617                 Key *key = BKE_key_from_object(obn);
1618
1619                 Key *oldkey = BKE_key_from_object(ob);
1620                 if (oldkey != NULL) {
1621                         ID_NEW_SET(oldkey, key);
1622                 }
1623
1624                 if (dupflag & USER_DUP_ACT) {
1625                         BKE_animdata_copy_id_action(bmain, (ID *)obn->data, true);
1626                         if (key) {
1627                                 BKE_animdata_copy_id_action(bmain, (ID *)key, true);
1628                         }
1629                 }
1630
1631                 if (dupflag & USER_DUP_MAT) {
1632                         matarar = give_matarar(obn);
1633                         if (matarar) {
1634                                 for (a = 0; a < obn->totcol; a++) {
1635                                         id = (ID *)(*matarar)[a];
1636                                         if (id) {
1637                                                 ID_NEW_REMAP_US((*matarar)[a])
1638                                                 else {
1639                                                         (*matarar)[a] = ID_NEW_SET((*matarar)[a], BKE_material_copy(bmain, (*matarar)[a]));
1640                                                 }
1641                                                 id_us_min(id);
1642                                         }
1643                                 }
1644                         }
1645                 }
1646         }
1647
1648 #undef ID_NEW_REMAP_US
1649 #undef ID_NEW_REMAP_US2
1650
1651         BKE_libblock_relink_to_newid(&obn->id);
1652
1653         /* DAG_relations_tag_update(bmain); */ /* caller must do */
1654
1655         if (ob->data != NULL) {
1656                 DEG_id_tag_update_ex(bmain, (ID *)obn->data, ID_RECALC_EDITORS);
1657         }
1658
1659         /* BKE_main_id_clear_newpoins(bmain); */ /* Called must do. */
1660
1661         return obn;
1662 }
1663
1664 void BKE_object_make_local_ex(Main *bmain, Object *ob, const bool lib_local, const bool clear_proxy)
1665 {
1666         bool is_local = false, is_lib = false;
1667
1668         /* - only lib users: do nothing (unless force_local is set)
1669          * - only local users: set flag
1670          * - mixed: make copy
1671          * In case we make a whole lib's content local, we always want to localize, and we skip remapping (done later).
1672          */
1673
1674         if (!ID_IS_LINKED(ob)) {
1675                 return;
1676         }
1677
1678         BKE_library_ID_test_usages(bmain, ob, &is_local, &is_lib);
1679
1680         if (lib_local || is_local) {
1681                 if (!is_lib) {
1682                         id_clear_lib_data(bmain, &ob->id);
1683                         BKE_id_expand_local(bmain, &ob->id);
1684                         if (clear_proxy) {
1685                                 if (ob->proxy_from != NULL) {
1686                                         ob->proxy_from->proxy = NULL;
1687                                         ob->proxy_from->proxy_group = NULL;
1688                                 }
1689                                 ob->proxy = ob->proxy_from = ob->proxy_group = NULL;
1690                         }
1691                 }
1692                 else {
1693                         Object *ob_new = BKE_object_copy(bmain, ob);
1694
1695                         ob_new->id.us = 0;
1696                         ob_new->proxy = ob_new->proxy_from = ob_new->proxy_group = NULL;
1697
1698                         /* setting newid is mandatory for complex make_lib_local logic... */
1699                         ID_NEW_SET(ob, ob_new);
1700
1701                         if (!lib_local) {
1702                                 BKE_libblock_remap(bmain, ob, ob_new, ID_REMAP_SKIP_INDIRECT_USAGE);
1703                         }
1704                 }
1705         }
1706 }
1707
1708 void BKE_object_make_local(Main *bmain, Object *ob, const bool lib_local)
1709 {
1710         BKE_object_make_local_ex(bmain, ob, lib_local, true);
1711 }
1712
1713 /* Returns true if the Object is from an external blend file (libdata) */
1714 bool BKE_object_is_libdata(const Object *ob)
1715 {
1716         return (ob && ID_IS_LINKED(ob));
1717 }
1718
1719 /* Returns true if the Object data is from an external blend file (libdata) */
1720 bool BKE_object_obdata_is_libdata(const Object *ob)
1721 {
1722         /* Linked objects with local obdata are forbidden! */
1723         BLI_assert(!ob || !ob->data || (ID_IS_LINKED(ob) ? ID_IS_LINKED(ob->data) : true));
1724         return (ob && ob->data && ID_IS_LINKED(ob->data));
1725 }
1726
1727 /* *************** PROXY **************** */
1728
1729 /* when you make proxy, ensure the exposed layers are extern */
1730 static void armature_set_id_extern(Object *ob)
1731 {
1732         bArmature *arm = ob->data;
1733         bPoseChannel *pchan;
1734         unsigned int lay = arm->layer_protected;
1735
1736         for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
1737                 if (!(pchan->bone->layer & lay))
1738                         id_lib_extern((ID *)pchan->custom);
1739         }
1740
1741 }
1742
1743 void BKE_object_copy_proxy_drivers(Object *ob, Object *target)
1744 {
1745         if ((target->adt) && (target->adt->drivers.first)) {
1746                 FCurve *fcu;
1747
1748                 /* add new animdata block */
1749                 if (!ob->adt)
1750                         ob->adt = BKE_animdata_add_id(&ob->id);
1751
1752                 /* make a copy of all the drivers (for now), then correct any links that need fixing */
1753                 free_fcurves(&ob->adt->drivers);
1754                 copy_fcurves(&ob->adt->drivers, &target->adt->drivers);
1755
1756                 for (fcu = ob->adt->drivers.first; fcu; fcu = fcu->next) {
1757                         ChannelDriver *driver = fcu->driver;
1758                         DriverVar *dvar;
1759
1760                         for (dvar = driver->variables.first; dvar; dvar = dvar->next) {
1761                                 /* all drivers */
1762                                 DRIVER_TARGETS_LOOPER_BEGIN(dvar)
1763                                 {
1764                                         if (dtar->id) {
1765                                                 if ((Object *)dtar->id == target)
1766                                                         dtar->id = (ID *)ob;
1767                                                 else {
1768                                                         /* only on local objects because this causes indirect links
1769                                                          * 'a -> b -> c', blend to point directly to a.blend
1770                                                          * when a.blend has a proxy thats linked into c.blend  */
1771                                                         if (!ID_IS_LINKED(ob))
1772                                                                 id_lib_extern((ID *)dtar->id);
1773                                                 }
1774                                         }
1775                                 }
1776                                 DRIVER_TARGETS_LOOPER_END;
1777                         }
1778                 }
1779         }
1780 }
1781
1782 /* proxy rule: lib_object->proxy_from == the one we borrow from, set temporally while object_update */
1783 /*             local_object->proxy == pointer to library object, saved in files and read */
1784 /*             local_object->proxy_group == pointer to collection dupli-object, saved in files and read */
1785
1786 void BKE_object_make_proxy(Main *bmain, Object *ob, Object *target, Object *cob)
1787 {
1788         /* paranoia checks */
1789         if (ID_IS_LINKED(ob) || !ID_IS_LINKED(target)) {
1790                 CLOG_ERROR(&LOG, "cannot make proxy");
1791                 return;
1792         }
1793
1794         ob->proxy = target;
1795         ob->proxy_group = cob;
1796         id_lib_extern(&target->id);
1797
1798         DEG_id_tag_update(&ob->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY | ID_RECALC_ANIMATION);
1799         DEG_id_tag_update(&target->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY | ID_RECALC_ANIMATION);
1800
1801         /* copy transform
1802          * - cob means this proxy comes from a collection, just apply the matrix
1803          *   so the object wont move from its dupli-transform.
1804          *
1805          * - no cob means this is being made from a linked object,
1806          *   this is closer to making a copy of the object - in-place. */
1807         if (cob) {
1808                 ob->rotmode = target->rotmode;
1809                 mul_m4_m4m4(ob->obmat, cob->obmat, target->obmat);
1810                 if (cob->instance_collection) { /* should always be true */
1811                         float tvec[3];
1812                         mul_v3_mat3_m4v3(tvec, ob->obmat, cob->instance_collection->instance_offset);
1813                         sub_v3_v3(ob->obmat[3], tvec);
1814                 }
1815                 BKE_object_apply_mat4(ob, ob->obmat, false, true);
1816         }
1817         else {
1818                 BKE_object_transform_copy(ob, target);
1819                 ob->parent = target->parent; /* libdata */
1820                 copy_m4_m4(ob->parentinv, target->parentinv);
1821         }
1822
1823         /* copy animdata stuff - drivers only for now... */
1824         BKE_object_copy_proxy_drivers(ob, target);
1825
1826         /* skip constraints? */
1827         /* FIXME: this is considered by many as a bug */
1828
1829         /* set object type and link to data */
1830         ob->type = target->type;
1831         ob->data = target->data;
1832         id_us_plus((ID *)ob->data);     /* ensures lib data becomes LIB_TAG_EXTERN */
1833
1834         /* copy vertex groups */
1835         defgroup_copy_list(&ob->defbase, &target->defbase);
1836
1837         /* copy material and index information */
1838         ob->actcol = ob->totcol = 0;
1839         if (ob->mat) MEM_freeN(ob->mat);
1840         if (ob->matbits) MEM_freeN(ob->matbits);
1841         ob->mat = NULL;
1842         ob->matbits = NULL;
1843         if ((target->totcol) && (target->mat) && OB_TYPE_SUPPORT_MATERIAL(ob->type)) {
1844                 int i;
1845
1846                 ob->actcol = target->actcol;
1847                 ob->totcol = target->totcol;
1848
1849                 ob->mat = MEM_dupallocN(target->mat);
1850                 ob->matbits = MEM_dupallocN(target->matbits);
1851                 for (i = 0; i < target->totcol; i++) {
1852                         /* don't need to run test_object_materials
1853                          * since we know this object is new and not used elsewhere */
1854                         id_us_plus((ID *)ob->mat[i]);
1855                 }
1856         }
1857
1858         /* type conversions */
1859         if (target->type == OB_ARMATURE) {
1860                 copy_object_pose(ob, target, 0);   /* data copy, object pointers in constraints */
1861                 BKE_pose_rest(ob->pose);            /* clear all transforms in channels */
1862                 BKE_pose_rebuild(bmain, ob, ob->data, true); /* set all internal links */
1863
1864                 armature_set_id_extern(ob);
1865         }
1866         else if (target->type == OB_EMPTY) {
1867                 ob->empty_drawtype = target->empty_drawtype;
1868                 ob->empty_drawsize = target->empty_drawsize;
1869         }
1870
1871         /* copy IDProperties */
1872         if (ob->id.properties) {
1873                 IDP_FreeProperty(ob->id.properties);
1874                 MEM_freeN(ob->id.properties);
1875                 ob->id.properties = NULL;
1876         }
1877         if (target->id.properties) {
1878                 ob->id.properties = IDP_CopyProperty(target->id.properties);
1879         }
1880
1881         /* copy drawtype info */
1882         ob->dt = target->dt;
1883 }
1884
1885 /**
1886  * Use with newly created objects to set their size
1887  * (used to apply scene-scale).
1888  */
1889 void BKE_object_obdata_size_init(struct Object *ob, const float size)
1890 {
1891         /* apply radius as a scale to types that support it */
1892         switch (ob->type) {
1893                 case OB_EMPTY:
1894                 {
1895                         ob->empty_drawsize *= size;
1896                         break;
1897                 }
1898                 case OB_FONT:
1899                 {
1900                         Curve *cu = ob->data;
1901                         cu->fsize *= size;
1902                         break;
1903                 }
1904                 case OB_CAMERA:
1905                 {
1906                         Camera *cam = ob->data;
1907                         cam->drawsize *= size;
1908                         break;
1909                 }
1910                 case OB_LAMP:
1911                 {
1912                         Light *lamp = ob->data;
1913                         lamp->dist *= size;
1914                         lamp->area_size  *= size;
1915                         lamp->area_sizey *= size;
1916                         lamp->area_sizez *= size;
1917                         break;
1918                 }
1919                 /* Only lattice (not mesh, curve, mball...),
1920                  * because its got data when newly added */
1921                 case OB_LATTICE:
1922                 {
1923                         struct Lattice *lt = ob->data;
1924                         float mat[4][4];
1925
1926                         unit_m4(mat);
1927                         scale_m4_fl(mat, size);
1928
1929                         BKE_lattice_transform(lt, (float (*)[4])mat, false);
1930                         break;
1931                 }
1932         }
1933 }
1934
1935 /* *************** CALC ****************** */
1936
1937 void BKE_object_scale_to_mat3(Object *ob, float mat[3][3])
1938 {
1939         float vec[3];
1940         mul_v3_v3v3(vec, ob->scale, ob->dscale);
1941         size_to_mat3(mat, vec);
1942 }
1943
1944 void BKE_object_rot_to_mat3(Object *ob, float mat[3][3], bool use_drot)
1945 {
1946         float rmat[3][3], dmat[3][3];
1947
1948         /* 'dmat' is the delta-rotation matrix, which will get (pre)multiplied
1949          * with the rotation matrix to yield the appropriate rotation
1950          */
1951
1952         /* rotations may either be quats, eulers (with various rotation orders), or axis-angle */
1953         if (ob->rotmode > 0) {
1954                 /* euler rotations (will cause gimble lock, but this can be alleviated a bit with rotation orders) */
1955                 eulO_to_mat3(rmat, ob->rot, ob->rotmode);
1956                 eulO_to_mat3(dmat, ob->drot, ob->rotmode);
1957         }
1958         else if (ob->rotmode == ROT_MODE_AXISANGLE) {
1959                 /* axis-angle - not really that great for 3D-changing orientations */
1960                 axis_angle_to_mat3(rmat, ob->rotAxis, ob->rotAngle);
1961                 axis_angle_to_mat3(dmat, ob->drotAxis, ob->drotAngle);
1962         }
1963         else {
1964                 /* quats are normalized before use to eliminate scaling issues */
1965                 float tquat[4];
1966
1967                 normalize_qt_qt(tquat, ob->quat);
1968                 quat_to_mat3(rmat, tquat);
1969
1970                 normalize_qt_qt(tquat, ob->dquat);
1971                 quat_to_mat3(dmat, tquat);
1972         }
1973
1974         /* combine these rotations */
1975         if (use_drot)
1976                 mul_m3_m3m3(mat, dmat, rmat);
1977         else
1978                 copy_m3_m3(mat, rmat);
1979 }
1980
1981 void BKE_object_mat3_to_rot(Object *ob, float mat[3][3], bool use_compat)
1982 {
1983         BLI_ASSERT_UNIT_M3(mat);
1984
1985         switch (ob->rotmode) {
1986                 case ROT_MODE_QUAT:
1987                 {
1988                         float dquat[4];
1989                         mat3_normalized_to_quat(ob->quat, mat);
1990                         normalize_qt_qt(dquat, ob->dquat);
1991                         invert_qt_normalized(dquat);
1992                         mul_qt_qtqt(ob->quat, dquat, ob->quat);
1993                         break;
1994                 }
1995                 case ROT_MODE_AXISANGLE:
1996                 {
1997                         float quat[4];
1998                         float dquat[4];
1999
2000                         /* without drot we could apply 'mat' directly */
2001                         mat3_normalized_to_quat(quat, mat);
2002                         axis_angle_to_quat(dquat, ob->drotAxis, ob->drotAngle);
2003                         invert_qt_normalized(dquat);
2004                         mul_qt_qtqt(quat, dquat, quat);
2005                         quat_to_axis_angle(ob->rotAxis, &ob->rotAngle, quat);
2006                         break;
2007                 }
2008                 default: /* euler */
2009                 {
2010                         float quat[4];
2011                         float dquat[4];
2012
2013                         /* without drot we could apply 'mat' directly */
2014                         mat3_normalized_to_quat(quat, mat);
2015                         eulO_to_quat(dquat, ob->drot, ob->rotmode);
2016                         invert_qt_normalized(dquat);
2017                         mul_qt_qtqt(quat, dquat, quat);
2018                         /* end drot correction */
2019
2020                         if (use_compat) quat_to_compatible_eulO(ob->rot, ob->rot, ob->rotmode, quat);
2021                         else            quat_to_eulO(ob->rot, ob->rotmode, quat);
2022                         break;
2023                 }
2024         }
2025 }
2026
2027 void BKE_object_tfm_protected_backup(const Object *ob,
2028                                      ObjectTfmProtectedChannels *obtfm)
2029 {
2030
2031 #define TFMCPY(_v) (obtfm->_v = ob->_v)
2032 #define TFMCPY3D(_v) copy_v3_v3(obtfm->_v, ob->_v)
2033 #define TFMCPY4D(_v) copy_v4_v4(obtfm->_v, ob->_v)
2034
2035         TFMCPY3D(loc);
2036         TFMCPY3D(dloc);
2037         TFMCPY3D(scale);
2038         TFMCPY3D(dscale);
2039         TFMCPY3D(rot);
2040         TFMCPY3D(drot);
2041         TFMCPY4D(quat);
2042         TFMCPY4D(dquat);
2043         TFMCPY3D(rotAxis);
2044         TFMCPY3D(drotAxis);
2045         TFMCPY(rotAngle);
2046         TFMCPY(drotAngle);
2047
2048 #undef TFMCPY
2049 #undef TFMCPY3D
2050 #undef TFMCPY4D
2051
2052 }
2053
2054 void BKE_object_tfm_protected_restore(Object *ob,
2055                                       const ObjectTfmProtectedChannels *obtfm,
2056                                       const short protectflag)
2057 {
2058         unsigned int i;
2059
2060         for (i = 0; i < 3; i++) {
2061                 if (protectflag & (OB_LOCK_LOCX << i)) {
2062                         ob->loc[i] =  obtfm->loc[i];
2063                         ob->dloc[i] = obtfm->dloc[i];
2064                 }
2065
2066                 if (protectflag & (OB_LOCK_SCALEX << i)) {
2067                         ob->scale[i] =  obtfm->scale[i];
2068                         ob->dscale[i] = obtfm->dscale[i];
2069                 }
2070
2071                 if (protectflag & (OB_LOCK_ROTX << i)) {
2072                         ob->rot[i] =  obtfm->rot[i];
2073                         ob->drot[i] = obtfm->drot[i];
2074
2075                         ob->quat[i + 1] =  obtfm->quat[i + 1];
2076                         ob->dquat[i + 1] = obtfm->dquat[i + 1];
2077
2078                         ob->rotAxis[i] =  obtfm->rotAxis[i];
2079                         ob->drotAxis[i] = obtfm->drotAxis[i];
2080                 }
2081         }
2082
2083         if ((protectflag & OB_LOCK_ROT4D) && (protectflag & OB_LOCK_ROTW)) {
2084                 ob->quat[0] =  obtfm->quat[0];
2085                 ob->dquat[0] = obtfm->dquat[0];
2086
2087                 ob->rotAngle =  obtfm->rotAngle;
2088                 ob->drotAngle = obtfm->drotAngle;
2089         }
2090 }
2091
2092 void BKE_object_tfm_copy(Object *object_dst, const Object *object_src)
2093 {
2094 #define TFMCPY(_v) (object_dst->_v = object_src->_v)
2095 #define TFMCPY3D(_v) copy_v3_v3(object_dst->_v, object_src->_v)
2096 #define TFMCPY4D(_v) copy_v4_v4(object_dst->_v, object_src->_v)
2097
2098         TFMCPY3D(loc);
2099         TFMCPY3D(dloc);
2100         TFMCPY3D(scale);
2101         TFMCPY3D(dscale);
2102         TFMCPY3D(rot);
2103         TFMCPY3D(drot);
2104         TFMCPY4D(quat);
2105         TFMCPY4D(dquat);
2106         TFMCPY3D(rotAxis);
2107         TFMCPY3D(drotAxis);
2108         TFMCPY(rotAngle);
2109         TFMCPY(drotAngle);
2110
2111 #undef TFMCPY
2112 #undef TFMCPY3D
2113 #undef TFMCPY4D
2114 }
2115
2116 void BKE_object_to_mat3(Object *ob, float mat[3][3]) /* no parent */
2117 {
2118         float smat[3][3];
2119         float rmat[3][3];
2120         /*float q1[4];*/
2121
2122         /* scale */
2123         BKE_object_scale_to_mat3(ob, smat);
2124
2125         /* rot */
2126         BKE_object_rot_to_mat3(ob, rmat, true);
2127         mul_m3_m3m3(mat, rmat, smat);
2128 }
2129
2130 void BKE_object_to_mat4(Object *ob, float mat[4][4])
2131 {
2132         float tmat[3][3];
2133
2134         BKE_object_to_mat3(ob, tmat);
2135
2136         copy_m4_m3(mat, tmat);
2137
2138         add_v3_v3v3(mat[3], ob->loc, ob->dloc);
2139 }
2140
2141 void BKE_object_matrix_local_get(struct Object *ob, float mat[4][4])
2142 {
2143         if (ob->parent) {
2144                 float par_imat[4][4];
2145
2146                 BKE_object_get_parent_matrix(ob, ob->parent, par_imat);
2147                 invert_m4(par_imat);
2148                 mul_m4_m4m4(mat, par_imat, ob->obmat);
2149         }
2150         else {
2151                 copy_m4_m4(mat, ob->obmat);
2152         }
2153 }
2154
2155 /**
2156  * \param depsgraph: Used for dupli-frame time.
2157  * \return success if \a mat is set.
2158  */
2159 static bool ob_parcurve(Object *ob, Object *par, float mat[4][4])
2160 {
2161         Curve *cu = par->data;
2162         float vec[4], dir[3], quat[4], radius, ctime;
2163
2164         /* NOTE: Curve cache is supposed to be evaluated here already, however there
2165          * are cases where we can not guarantee that. This includes, for example,
2166          * dependency cycles. We can't correct anything from here, since that would
2167          * cause a threading conflicts.
2168          *
2169          * TODO(sergey): Somce of the legit looking cases like T56619 need to be
2170          * looked into, and maybe curve cache (and other dependencies) are to be
2171          * evaluated prior to conversion. */
2172         if (par->runtime.curve_cache == NULL) {
2173                 return false;
2174         }
2175         if (par->runtime.curve_cache->path == NULL) {
2176                 return false;
2177         }
2178
2179         /* ctime is now a proper var setting of Curve which gets set by Animato like any other var that's animated,
2180          * but this will only work if it actually is animated...
2181          *
2182          * we divide the curvetime calculated in the previous step by the length of the path, to get a time
2183          * factor, which then gets clamped to lie within 0.0 - 1.0 range
2184          */
2185         if (cu->pathlen) {
2186                 ctime = cu->ctime / cu->pathlen;
2187         }
2188         else {
2189                 ctime = cu->ctime;
2190         }
2191         CLAMP(ctime, 0.0f, 1.0f);
2192
2193         unit_m4(mat);
2194
2195         /* vec: 4 items! */
2196         if (where_on_path(par, ctime, vec, dir, (cu->flag & CU_FOLLOW) ? quat : NULL, &radius, NULL)) {
2197                 if (cu->flag & CU_FOLLOW) {
2198                         quat_apply_track(quat, ob->trackflag, ob->upflag);
2199                         normalize_qt(quat);
2200                         quat_to_mat4(mat, quat);
2201                 }
2202                 if (cu->flag & CU_PATH_RADIUS) {
2203                         float tmat[4][4], rmat[4][4];
2204                         scale_m4_fl(tmat, radius);
2205                         mul_m4_m4m4(rmat, tmat, mat);
2206                         copy_m4_m4(mat, rmat);
2207                 }
2208                 copy_v3_v3(mat[3], vec);
2209         }
2210
2211         return true;
2212 }
2213
2214 static void ob_parbone(Object *ob, Object *par, float mat[4][4])
2215 {
2216         bPoseChannel *pchan;
2217         float vec[3];
2218
2219         if (par->type != OB_ARMATURE) {
2220                 unit_m4(mat);
2221                 return;
2222         }
2223
2224         /* Make sure the bone is still valid */
2225         pchan = BKE_pose_channel_find_name(par->pose, ob->parsubstr);
2226         if (!pchan || !pchan->bone) {
2227                 CLOG_ERROR(&LOG, "Object %s with Bone parent: bone %s doesn't exist", ob->id.name + 2, ob->parsubstr);
2228                 unit_m4(mat);
2229                 return;
2230         }
2231
2232         /* get bone transform */
2233         if (pchan->bone->flag & BONE_RELATIVE_PARENTING) {
2234                 /* the new option uses the root - expected behavior, but differs from old... */
2235                 /* XXX check on version patching? */
2236                 copy_m4_m4(mat, pchan->chan_mat);
2237         }
2238         else {
2239                 copy_m4_m4(mat, pchan->pose_mat);
2240
2241                 /* but for backwards compatibility, the child has to move to the tail */
2242                 copy_v3_v3(vec, mat[1]);
2243                 mul_v3_fl(vec, pchan->bone->length);
2244                 add_v3_v3(mat[3], vec);
2245         }
2246 }
2247
2248 static void give_parvert(Object *par, int nr, float vec[3])
2249 {
2250         zero_v3(vec);
2251
2252         if (par->type == OB_MESH) {
2253                 Mesh *me = par->data;
2254                 BMEditMesh *em = me->edit_mesh;
2255                 Mesh *me_eval = (em) ? em->mesh_eval_final : par->runtime.mesh_eval;
2256
2257                 if (me_eval) {
2258                         int count = 0;
2259                         const int numVerts = me_eval->totvert;
2260
2261                         if (nr < numVerts) {
2262                                 if (em && me_eval->runtime.is_original) {
2263                                         if (em->bm->elem_table_dirty & BM_VERT) {
2264 #ifdef VPARENT_THREADING_HACK
2265                                                 BLI_mutex_lock(&vparent_lock);
2266                                                 if (em->bm->elem_table_dirty & BM_VERT) {
2267                                                         BM_mesh_elem_table_ensure(em->bm, BM_VERT);
2268                                                 }
2269                                                 BLI_mutex_unlock(&vparent_lock);
2270 #else
2271                                                 BLI_assert(!"Not safe for threading");
2272                                                 BM_mesh_elem_table_ensure(em->bm, BM_VERT);
2273 #endif
2274                                         }
2275                                 }
2276
2277                                 if (CustomData_has_layer(&me_eval->vdata, CD_ORIGINDEX) &&
2278                                          !(em && me_eval->runtime.is_original))
2279                                 {
2280                                         const int *index = CustomData_get_layer(&me_eval->vdata, CD_ORIGINDEX);
2281                                         /* Get the average of all verts with (original index == nr). */
2282                                         for (int i = 0; i < numVerts; i++) {
2283                                                 if (index[i] == nr) {
2284                                                         add_v3_v3(vec, me_eval->mvert[i].co);
2285                                                         count++;
2286                                                 }
2287                                         }
2288                                 }
2289                                 else {
2290                                         if (nr < numVerts) {
2291                                                 add_v3_v3(vec, me_eval->mvert[nr].co);
2292                                                 count++;
2293                                         }
2294                                 }
2295                         }
2296
2297                         if (count == 0) {
2298                                 /* keep as 0, 0, 0 */
2299                         }
2300                         else if (count > 0) {
2301                                 mul_v3_fl(vec, 1.0f / count);
2302                         }
2303                         else {
2304                                 /* use first index if its out of range */
2305                                 if (me_eval->totvert) {
2306                                         copy_v3_v3(vec, me_eval->mvert[0].co);
2307                                 }
2308                         }
2309                 }
2310                 else {
2311                         CLOG_ERROR(&LOG, "Evaluated mesh is needed to solve parenting, "
2312                                    "object position can be wrong now");
2313                 }
2314         }
2315         else if (ELEM(par->type, OB_CURVE, OB_SURF)) {
2316                 ListBase *nurb;
2317
2318                 /* Unless there's some weird depsgraph failure the cache should exist. */
2319                 BLI_assert(par->runtime.curve_cache != NULL);
2320
2321                 if (par->runtime.curve_cache->deformed_nurbs.first != NULL) {
2322                         nurb = &par->runtime.curve_cache->deformed_nurbs;
2323                 }
2324                 else {
2325                         Curve *cu = par->data;
2326                         nurb = BKE_curve_nurbs_get(cu);
2327                 }
2328
2329                 BKE_nurbList_index_get_co(nurb, nr, vec);
2330         }
2331         else if (par->type == OB_LATTICE) {
2332                 Lattice *latt  = par->data;
2333                 DispList *dl   = par->runtime.curve_cache ? BKE_displist_find(&par->runtime.curve_cache->disp, DL_VERTS) : NULL;
2334                 float (*co)[3] = dl ? (float (*)[3])dl->verts : NULL;
2335                 int tot;
2336
2337                 if (latt->editlatt) latt = latt->editlatt->latt;
2338
2339                 tot = latt->pntsu * latt->pntsv * latt->pntsw;
2340
2341                 /* ensure dl is correct size */
2342                 BLI_assert(dl == NULL || dl->nr == tot);
2343
2344                 if (nr < tot) {
2345                         if (co) {
2346                                 copy_v3_v3(vec, co[nr]);
2347                         }
2348                         else {
2349                                 copy_v3_v3(vec, latt->def[nr].vec);
2350                         }
2351                 }
2352         }
2353 }
2354
2355 static void ob_parvert3(Object *ob, Object *par, float mat[4][4])
2356 {
2357
2358         /* in local ob space */
2359         if (OB_TYPE_SUPPORT_PARVERT(par->type)) {
2360                 float cmat[3][3], v1[3], v2[3], v3[3], q[4];
2361
2362                 give_parvert(par, ob->par1, v1);
2363                 give_parvert(par, ob->par2, v2);
2364                 give_parvert(par, ob->par3, v3);
2365
2366                 tri_to_quat(q, v1, v2, v3);
2367                 quat_to_mat3(cmat, q);
2368                 copy_m4_m3(mat, cmat);
2369
2370                 mid_v3_v3v3v3(mat[3], v1, v2, v3);
2371         }
2372         else {
2373                 unit_m4(mat);
2374         }
2375 }
2376
2377 void BKE_object_get_parent_matrix(Object *ob, Object *par, float parentmat[4][4])
2378 {
2379         float tmat[4][4];
2380         float vec[3];
2381         bool ok;
2382
2383         switch (ob->partype & PARTYPE) {
2384                 case PAROBJECT:
2385                         ok = 0;
2386                         if (par->type == OB_CURVE) {
2387                                 if ((((Curve *)par->data)->flag & CU_PATH) &&
2388                                     (ob_parcurve(ob, par, tmat)))
2389                                 {
2390                                         ok = 1;
2391                                 }
2392                         }
2393
2394                         if (ok) mul_m4_m4m4(parentmat, par->obmat, tmat);
2395                         else copy_m4_m4(parentmat, par->obmat);
2396
2397                         break;
2398                 case PARBONE:
2399                         ob_parbone(ob, par, tmat);
2400                         mul_m4_m4m4(parentmat, par->obmat, tmat);
2401                         break;
2402
2403                 case PARVERT1:
2404                         unit_m4(parentmat);
2405                         give_parvert(par, ob->par1, vec);
2406                         mul_v3_m4v3(parentmat[3], par->obmat, vec);
2407                         break;
2408                 case PARVERT3:
2409                         ob_parvert3(ob, par, tmat);
2410
2411                         mul_m4_m4m4(parentmat, par->obmat, tmat);
2412                         break;
2413
2414                 case PARSKEL:
2415                         copy_m4_m4(parentmat, par->obmat);
2416                         break;
2417         }
2418 }
2419
2420 /**
2421  * \param r_originmat: Optional matrix that stores the space the object is in (without its own matrix applied)
2422  */
2423 static void solve_parenting(Object *ob, Object *par, float obmat[4][4],
2424                             float r_originmat[3][3], const bool set_origin)
2425 {
2426         float totmat[4][4];
2427         float tmat[4][4];
2428         float locmat[4][4];
2429
2430         BKE_object_to_mat4(ob, locmat);
2431
2432         BKE_object_get_parent_matrix(ob, par, totmat);
2433
2434         /* total */
2435         mul_m4_m4m4(tmat, totmat, ob->parentinv);
2436         mul_m4_m4m4(obmat, tmat, locmat);
2437
2438         if (r_originmat) {
2439                 /* usable originmat */
2440                 copy_m3_m4(r_originmat, tmat);
2441         }
2442
2443         /* origin, for help line */
2444         if (set_origin) {
2445                 if ((ob->partype & PARTYPE) == PARSKEL) {
2446                         copy_v3_v3(ob->runtime.parent_display_origin, par->obmat[3]);
2447                 }
2448                 else {
2449                         copy_v3_v3(ob->runtime.parent_display_origin, totmat[3]);
2450                 }
2451         }
2452 }
2453
2454 /* note, scene is the active scene while actual_scene is the scene the object resides in */
2455 static void object_where_is_calc_ex(
2456         Depsgraph *depsgraph, Scene *scene, Object *ob, float ctime,
2457         RigidBodyWorld *rbw, float r_originmat[3][3])
2458 {
2459         if (ob->parent) {
2460                 Object *par = ob->parent;
2461
2462                 /* calculate parent matrix */
2463                 solve_parenting(ob, par, ob->obmat, r_originmat, true);
2464         }
2465         else {
2466                 BKE_object_to_mat4(ob, ob->obmat);
2467         }
2468
2469         /* try to fall back to the scene rigid body world if none given */
2470         rbw = rbw ? rbw : scene->rigidbody_world;
2471         /* read values pushed into RBO from sim/cache... */
2472         BKE_rigidbody_sync_transforms(rbw, ob, ctime);
2473
2474         /* solve constraints */
2475         if (ob->constraints.first && !(ob->transflag & OB_NO_CONSTRAINTS)) {
2476                 bConstraintOb *cob;
2477                 cob = BKE_constraints_make_evalob(depsgraph, scene, ob, NULL, CONSTRAINT_OBTYPE_OBJECT);
2478                 BKE_constraints_solve(depsgraph, &ob->constraints, cob, ctime);
2479                 BKE_constraints_clear_evalob(cob);
2480         }
2481
2482         /* set negative scale flag in object */
2483         if (is_negative_m4(ob->obmat)) ob->transflag |= OB_NEG_SCALE;
2484         else ob->transflag &= ~OB_NEG_SCALE;
2485 }
2486
2487 void BKE_object_where_is_calc_time(Depsgraph *depsgraph, Scene *scene, Object *ob, float ctime)
2488 {
2489         /* Execute drivers and animation. */
2490         BKE_animsys_evaluate_animdata(depsgraph, scene, &ob->id, ob->adt, ctime, ADT_RECALC_ALL);
2491         object_where_is_calc_ex(depsgraph, scene, ob, ctime, NULL, NULL);
2492 }
2493
2494 /* get object transformation matrix without recalculating dependencies and
2495  * constraints -- assume dependencies are already solved by depsgraph.
2496  * no changes to object and it's parent would be done.
2497  * used for bundles orientation in 3d space relative to parented blender camera */
2498 void BKE_object_where_is_calc_mat4(Object *ob, float obmat[4][4])
2499 {
2500         if (ob->parent) {
2501                 Object *par = ob->parent;
2502                 solve_parenting(ob, par, obmat, NULL, false);
2503         }
2504         else {
2505                 BKE_object_to_mat4(ob, obmat);
2506         }
2507 }
2508
2509 void BKE_object_where_is_calc_ex(Depsgraph *depsgraph, Scene *scene, RigidBodyWorld *rbw, Object *ob, float r_originmat[3][3])
2510 {
2511         float ctime = DEG_get_ctime(depsgraph);
2512         object_where_is_calc_ex(depsgraph, scene, ob, ctime, rbw, r_originmat);
2513 }
2514 void BKE_object_where_is_calc(Depsgraph *depsgraph, Scene *scene, Object *ob)
2515 {
2516         float ctime = DEG_get_ctime(depsgraph);
2517         object_where_is_calc_ex(depsgraph, scene, ob, ctime, NULL, NULL);
2518 }
2519
2520 /**
2521  * For calculation of the inverse parent transform, only used for editor.
2522  *
2523  * It assumes the object parent is already in the depsgraph.
2524  * Otherwise, after changing ob->parent you need to call:
2525  * - #DEG_relations_tag_update(bmain);
2526  * - #BKE_scene_graph_update_tagged(depsgraph, bmain);
2527  */
2528 void BKE_object_workob_calc_parent(Depsgraph *depsgraph, Scene *scene, Object *ob, Object *workob)
2529 {
2530         BKE_object_workob_clear(workob);
2531
2532         unit_m4(workob->obmat);
2533         unit_m4(workob->parentinv);
2534         unit_m4(workob->constinv);
2535
2536         /* Since this is used while calculating parenting, at this moment ob_eval->parent is still NULL. */
2537         workob->parent = DEG_get_evaluated_object(depsgraph, ob->parent);
2538
2539         workob->trackflag = ob->trackflag;
2540         workob->upflag = ob->upflag;
2541
2542         workob->partype = ob->partype;
2543         workob->par1 = ob->par1;
2544         workob->par2 = ob->par2;
2545         workob->par3 = ob->par3;
2546
2547         workob->constraints = ob->constraints;
2548
2549         BLI_strncpy(workob->parsubstr, ob->parsubstr, sizeof(workob->parsubstr));
2550
2551         BKE_object_where_is_calc(depsgraph, scene, workob);
2552 }
2553
2554 /**
2555  * Applies the global transformation \a mat to the \a ob using a relative parent space if supplied.
2556  *
2557  * \param mat: the global transformation mat that the object should be set object to.
2558  * \param parent: the parent space in which this object will be set relative to (should probably always be parent_eval).
2559  * \param use_compat: true to ensure that rotations are set using the min difference between the old and new orientation.
2560  */
2561 void BKE_object_apply_mat4_ex(Object *ob, float mat[4][4], Object *parent, float parentinv[4][4], const bool use_compat)
2562 {
2563         /* see BKE_pchan_apply_mat4() for the equivalent 'pchan' function */
2564
2565         float rot[3][3];
2566
2567         if (parent != NULL) {
2568                 float rmat[4][4], diff_mat[4][4], imat[4][4], parent_mat[4][4];
2569
2570                 BKE_object_get_parent_matrix(ob, parent, parent_mat);
2571
2572                 mul_m4_m4m4(diff_mat, parent_mat, parentinv);
2573                 invert_m4_m4(imat, diff_mat);
2574                 mul_m4_m4m4(rmat, imat, mat); /* get the parent relative matrix */
2575
2576                 /* same as below, use rmat rather than mat */
2577                 mat4_to_loc_rot_size(ob->loc, rot, ob->scale, rmat);
2578         }
2579         else {
2580                 mat4_to_loc_rot_size(ob->loc, rot, ob->scale, mat);
2581         }
2582
2583         BKE_object_mat3_to_rot(ob, rot, use_compat);
2584
2585         sub_v3_v3(ob->loc, ob->dloc);
2586
2587         if (ob->dscale[0] != 0.0f) ob->scale[0] /= ob->dscale[0];
2588         if (ob->dscale[1] != 0.0f) ob->scale[1] /= ob->dscale[1];
2589         if (ob->dscale[2] != 0.0f) ob->scale[2] /= ob->dscale[2];
2590
2591         /* BKE_object_mat3_to_rot handles delta rotations */
2592 }
2593
2594 /* XXX: should be removed after COW operators port to use BKE_object_apply_mat4_ex directly */
2595 void BKE_object_apply_mat4(Object *ob, float mat[4][4], const bool use_compat, const bool use_parent)
2596 {
2597         BKE_object_apply_mat4_ex(ob, mat, use_parent ? ob->parent : NULL, ob->parentinv, use_compat);
2598 }
2599
2600 BoundBox *BKE_boundbox_alloc_unit(void)
2601 {
2602         BoundBox *bb;
2603         const float min[3] = {-1.0f, -1.0f, -1.0f}, max[3] = {1.0f, 1.0f, 1.0f};
2604
2605         bb = MEM_callocN(sizeof(BoundBox), "OB-BoundBox");
2606         BKE_boundbox_init_from_minmax(bb, min, max);
2607
2608         return bb;
2609 }
2610
2611 void BKE_boundbox_init_from_minmax(BoundBox *bb, const float min[3], const float max[3])
2612 {
2613         bb->vec[0][0] = bb->vec[1][0] = bb->vec[2][0] = bb->vec[3][0] = min[0];
2614         bb->vec[4][0] = bb->vec[5][0] = bb->vec[6][0] = bb->vec[7][0] = max[0];
2615
2616         bb->vec[0][1] = bb->vec[1][1] = bb->vec[4][1] = bb->vec[5][1] = min[1];
2617         bb->vec[2][1] = bb->vec[3][1] = bb->vec[6][1] = bb->vec[7][1] = max[1];
2618
2619         bb->vec[0][2] = bb->vec[3][2] = bb->vec[4][2] = bb->vec[7][2] = min[2];
2620         bb->vec[1][2] = bb->vec[2][2] = bb->vec[5][2] = bb->vec[6][2] = max[2];
2621 }
2622
2623 void BKE_boundbox_calc_center_aabb(const BoundBox *bb, float r_cent[3])
2624 {
2625         r_cent[0] = 0.5f * (bb->vec[0][0] + bb->vec[4][0]);
2626         r_cent[1] = 0.5f * (bb->vec[0][1] + bb->vec[2][1]);
2627         r_cent[2] = 0.5f * (bb->vec[0][2] + bb->vec[1][2]);
2628 }
2629
2630 void BKE_boundbox_calc_size_aabb(const BoundBox *bb, float r_size[3])
2631 {
2632         r_size[0] = 0.5f * fabsf(bb->vec[0][0] - bb->vec[4][0]);
2633         r_size[1] = 0.5f * fabsf(bb->vec[0][1] - bb->vec[2][1]);
2634         r_size[2] = 0.5f * fabsf(bb->vec[0][2] - bb->vec[1][2]);
2635 }
2636
2637 void BKE_boundbox_minmax(const BoundBox *bb, float obmat[4][4], float r_min[3], float r_max[3])
2638 {
2639         int i;
2640         for (i = 0; i < 8; i++) {
2641                 float vec[3];
2642                 mul_v3_m4v3(vec, obmat, bb->vec[i]);
2643                 minmax_v3v3_v3(r_min, r_max, vec);
2644         }
2645 }
2646
2647 BoundBox *BKE_object_boundbox_get(Object *ob)
2648 {
2649         BoundBox *bb = NULL;
2650
2651         switch (ob->type) {
2652                 case OB_MESH:
2653                         bb = BKE_mesh_boundbox_get(ob);
2654                         break;
2655                 case OB_CURVE:
2656                 case OB_SURF:
2657                 case OB_FONT:
2658                         bb = BKE_curve_boundbox_get(ob);
2659                         break;
2660                 case OB_MBALL:
2661                         bb = BKE_mball_boundbox_get(ob);
2662                         break;
2663                 case OB_LATTICE:
2664                         bb = BKE_lattice_boundbox_get(ob);
2665                         break;
2666                 case OB_ARMATURE:
2667                         bb = BKE_armature_boundbox_get(ob);
2668                         break;
2669                 case OB_GPENCIL:
2670                         bb = BKE_gpencil_boundbox_get(ob);
2671                         break;
2672                 default:
2673                         break;
2674         }
2675         return bb;
2676 }
2677
2678 /* used to temporally disable/enable boundbox */
2679 void BKE_object_boundbox_flag(Object *ob, int flag, const bool set)
2680 {
2681         BoundBox *bb = BKE_object_boundbox_get(ob);
2682         if (bb) {
2683                 if (set) bb->flag |= flag;
2684                 else bb->flag &= ~flag;
2685         }
2686 }
2687
2688 void BKE_object_boundbox_calc_from_mesh(struct Object *ob, struct Mesh *me_eval)
2689 {
2690         float min[3], max[3];
2691
2692         INIT_MINMAX(min, max);
2693
2694         if (!BKE_mesh_minmax(me_eval, min, max)) {
2695                 zero_v3(min);
2696                 zero_v3(max);
2697         }
2698
2699         if (ob->runtime.bb == NULL) {
2700                 ob->runtime.bb = MEM_callocN(sizeof(BoundBox), "DM-BoundBox");
2701         }
2702
2703         BKE_boundbox_init_from_minmax(ob->runtime.bb, min, max);
2704
2705         ob->runtime.bb->flag &= ~BOUNDBOX_DIRTY;
2706 }
2707
2708 void BKE_object_dimensions_get(Object *ob, float vec[3])
2709 {
2710         BoundBox *bb = NULL;
2711
2712         bb = BKE_object_boundbox_get(ob);
2713         if (bb) {
2714                 float scale[3];
2715
2716                 mat4_to_size(scale, ob->obmat);
2717
2718                 vec[0] = fabsf(scale[0]) * (bb->vec[4][0] - bb->vec[0][0]);
2719                 vec[1] = fabsf(scale[1]) * (bb->vec[2][1] - bb->vec[0][1]);
2720                 vec[2] = fabsf(scale[2]) * (bb->vec[1][2] - bb->vec[0][2]);
2721         }
2722         else {
2723                 zero_v3(vec);
2724         }
2725 }
2726
2727 void BKE_object_dimensions_set(Object *ob, const float value[3], int axis_mask)
2728 {
2729         BoundBox *bb = NULL;
2730
2731         bb = BKE_object_boundbox_get(ob);
2732         if (bb) {
2733                 float len[3];
2734
2735                 len[0] = bb->vec[4][0] - bb->vec[0][0];
2736                 len[1] = bb->vec[2][1] - bb->vec[0][1];
2737                 len[2] = bb->vec[1][2] - bb->vec[0][2];
2738
2739                 for (int i = 0; i < 3; i++) {
2740                         if (((1 << i) & axis_mask) == 0) {
2741                                 if (len[i] > 0.0f) {
2742                                         ob->scale[i] = copysignf(value[i] / len[i], ob->scale[i]);
2743                                 }
2744                         }
2745                 }
2746         }
2747 }
2748
2749 void BKE_object_minmax(Object *ob, float min_r[3], float max_r[3], const bool use_hidden)
2750 {
2751         BoundBox bb;
2752         float vec[3];
2753         bool changed = false;
2754
2755         switch (ob->type) {
2756                 case OB_CURVE:
2757                 case OB_FONT:
2758                 case OB_SURF:
2759                 {
2760                         bb = *BKE_curve_boundbox_get(ob);
2761                         BKE_boundbox_minmax(&bb, ob->obmat, min_r, max_r);
2762                         changed = true;
2763                         break;
2764                 }
2765                 case OB_LATTICE:
2766                 {
2767                         Lattice *lt = ob->data;
2768                         BPoint *bp = lt->def;
2769                         int u, v, w;
2770
2771                         for (w = 0; w < lt->pntsw; w++) {
2772                                 for (v = 0; v < lt->pntsv; v++) {
2773                                         for (u = 0; u < lt->pntsu; u++, bp++) {
2774                                                 mul_v3_m4v3(vec, ob->obmat, bp->vec);
2775                                                 minmax_v3v3_v3(min_r, max_r, vec);
2776                                         }
2777                                 }
2778                         }
2779                         changed = true;
2780                         break;
2781                 }
2782                 case OB_ARMATURE:
2783                 {
2784                         changed = BKE_pose_minmax(ob, min_r, max_r, use_hidden, false);
2785                         break;
2786                 }
2787                 case OB_MESH:
2788                 {
2789                         Mesh *me = BKE_mesh_from_object(ob);
2790
2791                         if (me) {
2792                                 bb = *BKE_mesh_boundbox_get(ob);
2793                                 BKE_boundbox_minmax(&bb, ob->obmat, min_r, max_r);
2794                                 changed = true;
2795                         }
2796                         break;
2797                 }
2798                 case OB_MBALL:
2799                 {
2800                         float ob_min[3], ob_max[3];
2801
2802                         changed = BKE_mball_minmax_ex(ob->data, ob_min, ob_max, ob->obmat, 0);
2803                         if (changed) {
2804                                 minmax_v3v3_v3(min_r, max_r, ob_min);
2805                                 minmax_v3v3_v3(min_r, max_r, ob_max);
2806                         }
2807                         break;
2808                 }
2809         }
2810
2811         if (changed == false) {
2812                 float size[3];
2813
2814                 copy_v3_v3(size, ob->scale);
2815                 if (ob->type == OB_EMPTY) {
2816                         mul_v3_fl(size, ob->empty_drawsize);
2817                 }
2818
2819                 minmax_v3v3_v3(min_r, max_r, ob->obmat[3]);
2820
2821                 copy_v3_v3(vec, ob->obmat[3]);
2822                 add_v3_v3(vec, size);
2823                 minmax_v3v3_v3(min_r, max_r, vec);
2824
2825                 copy_v3_v3(vec, ob->obmat[3]);
2826                 sub_v3_v3(vec, size);
2827                 minmax_v3v3_v3(min_r, max_r, vec);
2828         }
2829 }
2830
2831 void BKE_object_empty_draw_type_set(Object *ob, const int value)
2832 {
2833         ob->empty_drawtype = value;
2834
2835         if (ob->type == OB_EMPTY && ob->empty_drawtype == OB_EMPTY_IMAGE) {
2836                 if (!ob->iuser) {
2837                         ob->iuser = MEM_callocN(sizeof(ImageUser), "image user");
2838                         ob->iuser->ok = 1;
2839                         ob->iuser->flag |= IMA_ANIM_ALWAYS;
2840                         ob->iuser->frames = 100;
2841                         ob->iuser->sfra = 1;
2842                 }
2843         }
2844         else {
2845                 if (ob->iuser) {
2846                         MEM_freeN(ob->iuser);
2847                         ob->iuser = NULL;
2848                 }
2849         }
2850 }
2851
2852 bool BKE_object_empty_image_is_visible_in_view3d(const Object *ob, const RegionView3D *rv3d)
2853 {
2854         char visibility_flag = ob->empty_image_visibility_flag;
2855
2856         if ((visibility_flag & (OB_EMPTY_IMAGE_HIDE_BACK | OB_EMPTY_IMAGE_HIDE_FRONT)) != 0) {
2857                 float eps, dot;
2858                 if (rv3d->is_persp) {
2859                         /* Note, we could normalize the 'view_dir' then use 'eps'
2860                          * however the issue with empty objects being visible when viewed from the side
2861                          * is only noticeable in orthographic views. */
2862                         float view_dir[3];
2863                         sub_v3_v3v3(view_dir, rv3d->viewinv[3], ob->obmat[3]);
2864                         dot = dot_v3v3(ob->obmat[2], view_dir);
2865                         eps = 0.0f;
2866                 }
2867                 else {
2868                         dot = dot_v3v3(ob->obmat[2], rv3d->viewinv[2]);
2869                         eps = 1e-5f;
2870                 }
2871                 if (visibility_flag & OB_EMPTY_IMAGE_HIDE_BACK) {
2872                         if (dot < eps) {
2873                                 return false;
2874                         }
2875                 }
2876                 if (visibility_flag & OB_EMPTY_IMAGE_HIDE_FRONT) {
2877                         if (dot > -eps) {
2878                                 return false;
2879                         }
2880                 }
2881         }
2882
2883         if (rv3d->is_persp) {
2884                 return (visibility_flag & OB_EMPTY_IMAGE_HIDE_PERSPECTIVE) == 0;
2885         }
2886         else {
2887                 return (visibility_flag & OB_EMPTY_IMAGE_HIDE_ORTHOGRAPHIC) == 0;
2888         }
2889 }
2890
2891 bool BKE_object_minmax_dupli(Depsgraph *depsgraph, Scene *scene, Object *ob, float r_min[3], float r_max[3], const bool use_hidden)
2892 {
2893         bool ok = false;
2894         if ((ob->transflag & OB_DUPLI) == 0) {
2895                 return ok;
2896         }
2897         else {
2898                 ListBase *lb;
2899                 DupliObject *dob;
2900                 lb = object_duplilist(depsgraph, scene, ob);
2901                 for (dob = lb->first; dob; dob = dob->next) {
2902                         if ((use_hidden == false) && (dob->no_draw != 0)) {
2903                                 /* pass */
2904                         }
2905                         else {
2906                                 BoundBox *bb = BKE_object_boundbox_get(dob->ob);
2907
2908                                 if (bb) {
2909                                         int i;
2910                                         for (i = 0; i < 8; i++) {
2911                                                 float vec[3];
2912                                                 mul_v3_m4v3(vec, dob->mat, bb->vec[i]);
2913                                                 minmax_v3v3_v3(r_min, r_max, vec);
2914                                         }
2915
2916                                         ok = true;
2917                                 }
2918                         }
2919                 }
2920                 free_object_duplilist(lb);  /* does restore */
2921         }
2922
2923         return ok;
2924 }
2925
2926 void BKE_object_foreach_display_point(
2927         Object *ob, float obmat[4][4],
2928         void (*func_cb)(const float[3], void *), void *user_data)
2929 {
2930         float co[3];
2931
2932         if (ob->runtime.mesh_eval) {
2933                 const Mesh *me = ob->runtime.mesh_eval;
2934                 const MVert *mv = me->mvert;
2935                 const int totvert = me->totvert;
2936                 for (int i = 0; i < totvert; i++, mv++) {
2937                         mul_v3_m4v3(co, obmat, mv->co);
2938                         func_cb(co, user_data);
2939                 }
2940         }
2941         else if (ob->runtime.curve_cache && ob->runtime.curve_cache->disp.first) {
2942                 DispList *dl;
2943
2944                 for (dl = ob->runtime.curve_cache->disp.first; dl; dl = dl->next) {
2945                         const float *v3 = dl->verts;
2946                         int totvert = dl->nr;
2947                         int i;
2948
2949                         for (i = 0; i < totvert; i++, v3 += 3) {
2950                                 mul_v3_m4v3(co, obmat, v3);
2951                                 func_cb(co, user_data);
2952                         }
2953                 }
2954         }
2955 }
2956
2957 void BKE_scene_foreach_display_point(
2958         Depsgraph *depsgraph,
2959         void (*func_cb)(const float[3], void *), void *user_data)
2960 {
2961         DEG_OBJECT_ITER_BEGIN(
2962                 depsgraph, ob,
2963                 DEG_ITER_OBJECT_FLAG_LINKED_DIRECTLY |
2964                 DEG_ITER_OBJECT_FLAG_VISIBLE |
2965                 DEG_ITER_OBJECT_FLAG_DUPLI)
2966         {
2967                 if ((ob->base_flag & BASE_SELECTED) != 0) {
2968                         BKE_object_foreach_display_point(ob, ob->obmat, func_cb, user_data);
2969                 }
2970         }
2971         DEG_OBJECT_ITER_END;
2972 }
2973
2974 /* copied from DNA_object_types.h */
2975 typedef struct ObTfmBack {
2976         float loc[3], dloc[3];
2977         /** scale and delta scale. */
2978         float scale[3], dscale[3];
2979         /** euler rotation. */
2980         float rot[3], drot[3];
2981         /** quaternion rotation. */
2982         float quat[4], dquat[4];
2983         /** axis angle rotation - axis part. */
2984         float rotAxis[3], drotAxis[3];
2985         /** axis angle rotation - angle part. */
2986         float rotAngle, drotAngle;
2987         /** final worldspace matrix with constraints & animsys applied. */
2988         float obmat[4][4];
2989         /** inverse result of parent, so that object doesn't 'stick' to parent. */
2990         float parentinv[4][4];
2991         /** inverse result of constraints. doesn't include effect of parent or object local transform. */
2992         float constinv[4][4];
2993         /** inverse matrix of 'obmat' for during render, temporally: ipokeys of transform. */
2994         float imat[4][4];
2995 } ObTfmBack;
2996
2997 void *BKE_object_tfm_backup(Object *ob)
2998 {
2999         ObTfmBack *obtfm = MEM_mallocN(sizeof(ObTfmBack), "ObTfmBack");
3000         copy_v3_v3(obtfm->loc, ob->loc);
3001         copy_v3_v3(obtfm->dloc, ob->dloc);
3002         copy_v3_v3(obtfm->scale, ob->scale);
3003         copy_v3_v3(obtfm->dscale, ob->dscale);
3004         copy_v3_v3(obtfm->rot, ob->rot);
3005         copy_v3_v3(obtfm->drot, ob->drot);
3006         copy_qt_qt(obtfm->quat, ob->quat);
3007         copy_qt_qt(obtfm->dquat, ob->dquat);
3008         copy_v3_v3(obtfm->rotAxis, ob->rotAxis);
3009         copy_v3_v3(obtfm->drotAxis, ob->drotAxis);
3010         obtfm->rotAngle = ob->rotAngle;
3011         obtfm->drotAngle = ob->drotAngle;
3012         copy_m4_m4(obtfm->obmat, ob->obmat);
3013         copy_m4_m4(obtfm->parentinv, ob->parentinv);
3014         copy_m4_m4(obtfm->constinv, ob->constinv);
3015         copy_m4_m4(obtfm->imat, ob->imat);
3016
3017         return (void *)obtfm;
3018 }
3019
3020 void BKE_object_tfm_restore(Object *ob, void *obtfm_pt)
3021 {
3022         ObTfmBack *obtfm = (ObTfmBack *)obtfm_pt;
3023         copy_v3_v3(ob->loc, obtfm->loc);
3024         copy_v3_v3(ob->dloc, obtfm->dloc);
3025         copy_v3_v3(ob->scale, obtfm->scale);
3026         copy_v3_v3(ob->dscale, obtfm->dscale);
3027         copy_v3_v3(ob->rot, obtfm->rot);
3028         copy_v3_v3(ob->drot, obtfm->drot);
3029         copy_qt_qt(ob->quat, obtfm->quat);
3030         copy_qt_qt(ob->dquat, obtfm->dquat);
3031         copy_v3_v3(ob->rotAxis, obtfm->rotAxis);
3032         copy_v3_v3(ob->drotAxis, obtfm->drotAxis);
3033         ob->rotAngle = obtfm->rotAngle;
3034         ob->drotAngle = obtfm->drotAngle;
3035         copy_m4_m4(ob->obmat, obtfm->obmat);
3036         copy_m4_m4(ob->parentinv, obtfm->parentinv);
3037         copy_m4_m4(ob->constinv, obtfm->constinv);
3038         copy_m4_m4(ob->imat, obtfm->imat);
3039 }
3040
3041 bool BKE_object_parent_loop_check(const Object *par, const Object *ob)
3042 {
3043         /* test if 'ob' is a parent somewhere in par's parents */
3044         if (par == NULL) return false;
3045         if (ob == par) return true;
3046         return BKE_object_parent_loop_check(par->parent, ob);
3047 }
3048
3049 static void object_handle_update_proxy(Depsgraph *depsgraph,
3050                                        Scene *scene,
3051                                        Object *object,
3052                                        const bool do_proxy_update)
3053 {
3054         /* The case when this is a collection proxy, object_update is called in collection.c */
3055         if (object->proxy == NULL) {
3056                 return;
3057         }
3058         /* set pointer in library proxy target, for copying, but restore it */
3059         object->proxy->proxy_from = object;
3060         // printf("set proxy pointer for later collection stuff %s\n", ob->id.name);
3061
3062         /* the no-group proxy case, we call update */
3063         if (object->proxy_group == NULL) {
3064                 if (do_proxy_update) {
3065                         // printf("call update, lib ob %s proxy %s\n", ob->proxy->id.name, ob->id.name);
3066                         BKE_object_handle_update(depsgraph, scene, object->proxy);
3067                 }
3068         }
3069 }
3070
3071 /* proxy rule: lib_object->proxy_from == the one we borrow from, only set temporal and cleared here */
3072 /*           local_object->proxy      == pointer to library object, saved in files and read */
3073
3074 /* function below is polluted with proxy exceptions, cleanup will follow! */
3075
3076 /* the main object update call, for object matrix, constraints, keys and displist (modifiers) */
3077 /* requires flags to be set! */
3078 /* Ideally we shouldn't have to pass the rigid body world, but need bigger restructuring to avoid id */
3079 void BKE_object_handle_update_ex(Depsgraph *depsgraph,
3080                                  Scene *scene, Object *ob,
3081                                  RigidBodyWorld *rbw,
3082                                  const bool do_proxy_update)
3083 {
3084         const ID *object_data = ob->data;
3085         const bool recalc_object = (ob->id.recalc & ID_RECALC_ALL) != 0;
3086         const bool recalc_data =
3087                 (object_data != NULL) ? ((object_data->recalc & ID_RECALC_ALL) != 0)
3088                                       : 0;
3089         if (!recalc_object && ! recalc_data) {
3090                 object_handle_update_proxy(depsgraph, scene, ob, do_proxy_update);
3091                 return;
3092         }
3093         /* Speed optimization for animation lookups. */
3094         if (ob->pose != NULL) {
3095                 BKE_pose_channels_hash_make(ob->pose);
3096                 if (ob->pose->flag & POSE_CONSTRAINTS_NEED_UPDATE_FLAGS) {
3097                         BKE_pose_update_constraint_flags(ob->pose);
3098                 }
3099         }
3100         if (recalc_data) {
3101                 if (ob->type == OB_ARMATURE) {
3102                         /* this happens for reading old files and to match library armatures
3103                          * with poses we do it ahead of BKE_object_where_is_calc to ensure animation
3104                          * is evaluated on the rebuilt pose, otherwise we get incorrect poses
3105                          * on file load */
3106                         if (ob->pose == NULL || (ob->pose->flag & POSE_RECALC)) {
3107                                 /* No need to pass bmain here, we assume we do not need to rebuild DEG from here... */
3108                                 BKE_pose_rebuild(NULL, ob, ob->data, true);
3109                         }
3110                 }
3111         }
3112         /* XXX new animsys warning: depsgraph tag ID_RECALC_GEOMETRY should not skip drivers,
3113          * which is only in BKE_object_where_is_calc now */
3114         /* XXX: should this case be ID_RECALC_TRANSFORM instead? */
3115         if (recalc_object || recalc_data) {
3116                 if (G.debug & G_DEBUG_DEPSGRAPH_EVAL) {
3117                         printf("recalcob %s\n", ob->id.name + 2);
3118                 }
3119                 /* Handle proxy copy for target. */
3120                 if (!BKE_object_eval_proxy_copy(depsgraph, ob)) {
3121                         BKE_object_where_is_calc_ex(depsgraph, scene, rbw, ob, NULL);
3122                 }
3123         }
3124
3125         if (recalc_data) {
3126                 BKE_object_handle_data_update(depsgraph, scene, ob);
3127         }
3128
3129         ob->id.recalc &= ID_RECALC_ALL;
3130
3131         object_handle_update_proxy(depsgraph, scene, ob, do_proxy_update);
3132 }
3133
3134 /* WARNING: "scene" here may not be the scene object actually resides in.
3135  * When dealing with background-sets, "scene" is actually the active scene.
3136  * e.g. "scene" <-- set 1 <-- set 2 ("ob" lives here) <-- set 3 <-- ... <-- set n
3137  * rigid bodies depend on their world so use BKE_object_handle_update_ex() to also pass along the current rigid body world
3138  */
3139 void BKE_object_handle_update(Depsgraph *depsgraph, Scene *scene, Object *ob)
3140 {
3141         BKE_object_handle_update_ex(depsgraph, scene, ob, NULL, true);
3142 }
3143
3144 void BKE_object_sculpt_data_create(Object *ob)
3145 {
3146         BLI_assert((ob->sculpt == NULL) && (ob->mode & OB_MODE_ALL_SCULPT));
3147         ob->sculpt = MEM_callocN(sizeof(SculptSession), __func__);
3148         ob->sculpt->mode_type = ob->mode;
3149 }
3150
3151 void BKE_object_sculpt_modifiers_changed(Object *ob)
3152 {
3153         SculptSession *ss = ob->sculpt;
3154
3155         if (ss && ss->building_vp_handle == false) {
3156                 if (!ss->cache) {
3157                         /* we free pbvh on changes, except during sculpt since it can't deal with
3158                          * changing PVBH node organization, we hope topology does not change in
3159                          * the meantime .. weak */
3160                         if (ss->pbvh) {
3161                                 BKE_pbvh_free(ss->pbvh);
3162                                 ss->pbvh = NULL;
3163                         }
3164
3165                         BKE_sculptsession_free_deformMats(ob->sculpt);
3166
3167                         /* In vertex/weight paint, force maps to be rebuilt. */
3168                         BKE_sculptsession_free_vwpaint_data(ob->sculpt);
3169                 }
3170                 else {
3171                         PBVHNode **nodes;
3172                         int n, totnode;
3173
3174                         BKE_pbvh_search_gather(ss->pbvh, NULL, NULL, &nodes, &totnode);
3175
3176                         for (n = 0; n < totnode; n++)
3177                                 BKE_pbvh_node_mark_update(nodes[n]);
3178
3179                         MEM_freeN(nodes);
3180                 }
3181         }
3182 }
3183
3184 int BKE_object_obdata_texspace_get(Object *ob, short **r_texflag, float **r_loc, float **r_size, float **r_rot)
3185 {
3186
3187         if (ob->data == NULL)
3188                 return 0;
3189
3190         switch (GS(((ID *)ob->data)->name)) {
3191                 case ID_ME:
3192                 {
3193                         BKE_mesh_texspace_get_reference((Mesh *)ob->data, r_texflag, r_loc, r_rot, r_size);
3194                         break;
3195                 }
3196                 case ID_CU:
3197                 {
3198                         Curve *cu = ob->data;
3199                         if (cu->bb == NULL || (cu->bb->flag & BOUNDBOX_DIRTY)) {
3200                                 BKE_curve_texspace_calc(cu);
3201                         }
3202                         if (r_texflag) *r_texflag = &cu->texflag;
3203                         if (r_loc) *r_loc = cu->loc;
3204                         if (r_size) *r_size = cu->size;
3205                         if (r_rot) *r_rot = cu->rot;
3206                         break;
3207                 }
3208                 case ID_MB:
3209                 {
3210                         MetaBall *mb = ob->data;
3211                         if (r_texflag) *r_texflag = &mb->texflag;
3212                         if (r_loc) *r_loc = mb->loc;
3213                         if (r_size) *r_size = mb->size;
3214                         if (r_rot) *r_rot = mb->rot;
3215                         break;
3216                 }
3217                 default:
3218                         return 0;
3219         }
3220         return 1;
3221 }
3222
3223 /** Get evaluated mesh for given (main, original) object and depsgraph. */
3224 Mesh *BKE_object_get_evaluated_mesh(const Depsgraph *depsgraph, Object *ob)
3225 {
3226         Object *ob_eval = DEG_get_evaluated_object(depsgraph, ob);
3227         return ob_eval->runtime.mesh_eval;
3228 }
3229
3230 /* Get object's mesh with all modifiers applied. */
3231 Mesh *BKE_object_get_final_mesh(Object *object)
3232 {
3233         if (object->runtime.mesh_eval != NULL) {
3234                 BLI_assert((object->id.tag & LIB_TAG_COPIED_ON_WRITE) != 0);
3235                 BLI_assert(object->runtime.mesh_eval == object->data);
3236                 BLI_assert((object->runtime.mesh_eval->id.tag & LIB_TAG_COPIED_ON_WRITE_EVAL_RESULT) != 0);
3237                 return object->runtime.mesh_eval;
3238         }