Fix T58739: Camera Location, keyframe Bug
[blender.git] / source / blender / editors / object / object_relations.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * Contributor(s): Blender Foundation, 2002-2008 full recode
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/editors/object/object_relations.c
27  *  \ingroup edobj
28  */
29
30
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34
35 #include "MEM_guardedalloc.h"
36
37 #include "DNA_anim_types.h"
38 #include "DNA_armature_types.h"
39 #include "DNA_mesh_types.h"
40 #include "DNA_collection_types.h"
41 #include "DNA_constraint_types.h"
42 #include "DNA_lamp_types.h"
43 #include "DNA_lattice_types.h"
44 #include "DNA_material_types.h"
45 #include "DNA_meta_types.h"
46 #include "DNA_particle_types.h"
47 #include "DNA_scene_types.h"
48 #include "DNA_world_types.h"
49 #include "DNA_object_types.h"
50 #include "DNA_vfont_types.h"
51 #include "DNA_gpencil_types.h"
52
53 #include "BLI_math.h"
54 #include "BLI_listbase.h"
55 #include "BLI_linklist.h"
56 #include "BLI_string.h"
57 #include "BLI_kdtree.h"
58 #include "BLI_utildefines.h"
59
60 #include "BLT_translation.h"
61
62 #include "BKE_action.h"
63 #include "BKE_animsys.h"
64 #include "BKE_armature.h"
65 #include "BKE_camera.h"
66 #include "BKE_collection.h"
67 #include "BKE_context.h"
68 #include "BKE_constraint.h"
69 #include "BKE_curve.h"
70 #include "BKE_DerivedMesh.h"
71 #include "BKE_displist.h"
72 #include "BKE_editmesh.h"
73 #include "BKE_global.h"
74 #include "BKE_gpencil.h"
75 #include "BKE_fcurve.h"
76 #include "BKE_idprop.h"
77 #include "BKE_lamp.h"
78 #include "BKE_lattice.h"
79 #include "BKE_layer.h"
80 #include "BKE_library.h"
81 #include "BKE_library_override.h"
82 #include "BKE_library_query.h"
83 #include "BKE_library_remap.h"
84 #include "BKE_lightprobe.h"
85 #include "BKE_main.h"
86 #include "BKE_material.h"
87 #include "BKE_mball.h"
88 #include "BKE_mesh.h"
89 #include "BKE_modifier.h"
90 #include "BKE_node.h"
91 #include "BKE_object.h"
92 #include "BKE_report.h"
93 #include "BKE_scene.h"
94 #include "BKE_speaker.h"
95 #include "BKE_texture.h"
96
97 #include "DEG_depsgraph.h"
98 #include "DEG_depsgraph_build.h"
99
100 #include "WM_api.h"
101 #include "WM_types.h"
102
103 #include "UI_interface.h"
104 #include "UI_resources.h"
105
106 #include "RNA_access.h"
107 #include "RNA_define.h"
108 #include "RNA_enum_types.h"
109
110 #include "ED_armature.h"
111 #include "ED_curve.h"
112 #include "ED_gpencil.h"
113 #include "ED_keyframing.h"
114 #include "ED_object.h"
115 #include "ED_mesh.h"
116 #include "ED_screen.h"
117 #include "ED_view3d.h"
118
119 #include "object_intern.h"
120
121 /*********************** Make Vertex Parent Operator ************************/
122
123 static bool vertex_parent_set_poll(bContext *C)
124 {
125         return ED_operator_editmesh(C) || ED_operator_editsurfcurve(C) || ED_operator_editlattice(C);
126 }
127
128 static int vertex_parent_set_exec(bContext *C, wmOperator *op)
129 {
130         Main *bmain = CTX_data_main(C);
131         Scene *scene = CTX_data_scene(C);
132         View3D *v3d = CTX_wm_view3d(C);
133         Depsgraph *depsgraph = CTX_data_depsgraph(C);
134         ViewLayer *view_layer = CTX_data_view_layer(C);
135         Object *obedit = CTX_data_edit_object(C);
136         BMVert *eve;
137         BMIter iter;
138         Nurb *nu;
139         BezTriple *bezt;
140         BPoint *bp;
141         Object *par;
142         int a, v1 = 0, v2 = 0, v3 = 0, v4 = 0, nr = 1;
143
144         /* we need 1 to 3 selected vertices */
145
146         if (obedit->type == OB_MESH) {
147                 Mesh *me = obedit->data;
148                 BMEditMesh *em;
149
150                 EDBM_mesh_load(bmain, obedit);
151                 EDBM_mesh_make(obedit, scene->toolsettings->selectmode, true);
152
153                 DEG_id_tag_update(obedit->data, 0);
154
155                 em = me->edit_btmesh;
156
157                 EDBM_mesh_normals_update(em);
158                 BKE_editmesh_tessface_calc(em);
159
160                 /* derivedMesh might be needed for solving parenting,
161                  * so re-create it here */
162                 makeDerivedMesh(depsgraph, scene, obedit, em, CD_MASK_BAREMESH | CD_MASK_ORIGINDEX, false);
163
164                 BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
165                         if (BM_elem_flag_test(eve, BM_ELEM_SELECT)) {
166                                 if (v1 == 0) v1 = nr;
167                                 else if (v2 == 0) v2 = nr;
168                                 else if (v3 == 0) v3 = nr;
169                                 else if (v4 == 0) v4 = nr;
170                                 else break;
171                         }
172                         nr++;
173                 }
174         }
175         else if (ELEM(obedit->type, OB_SURF, OB_CURVE)) {
176                 ListBase *editnurb = object_editcurve_get(obedit);
177
178                 nu = editnurb->first;
179                 while (nu) {
180                         if (nu->type == CU_BEZIER) {
181                                 bezt = nu->bezt;
182                                 a = nu->pntsu;
183                                 while (a--) {
184                                         if (BEZT_ISSEL_ANY_HIDDENHANDLES(v3d, bezt)) {
185                                                 if (v1 == 0) v1 = nr;
186                                                 else if (v2 == 0) v2 = nr;
187                                                 else if (v3 == 0) v3 = nr;
188                                                 else if (v4 == 0) v4 = nr;
189                                                 else break;
190                                         }
191                                         nr++;
192                                         bezt++;
193                                 }
194                         }
195                         else {
196                                 bp = nu->bp;
197                                 a = nu->pntsu * nu->pntsv;
198                                 while (a--) {
199                                         if (bp->f1 & SELECT) {
200                                                 if (v1 == 0) v1 = nr;
201                                                 else if (v2 == 0) v2 = nr;
202                                                 else if (v3 == 0) v3 = nr;
203                                                 else if (v4 == 0) v4 = nr;
204                                                 else break;
205                                         }
206                                         nr++;
207                                         bp++;
208                                 }
209                         }
210                         nu = nu->next;
211                 }
212         }
213         else if (obedit->type == OB_LATTICE) {
214                 Lattice *lt = obedit->data;
215
216                 a = lt->editlatt->latt->pntsu * lt->editlatt->latt->pntsv * lt->editlatt->latt->pntsw;
217                 bp = lt->editlatt->latt->def;
218                 while (a--) {
219                         if (bp->f1 & SELECT) {
220                                 if (v1 == 0) v1 = nr;
221                                 else if (v2 == 0) v2 = nr;
222                                 else if (v3 == 0) v3 = nr;
223                                 else if (v4 == 0) v4 = nr;
224                                 else break;
225                         }
226                         nr++;
227                         bp++;
228                 }
229         }
230
231         if (v4 || !((v1 && v2 == 0 && v3 == 0) || (v1 && v2 && v3))) {
232                 BKE_report(op->reports, RPT_ERROR, "Select either 1 or 3 vertices to parent to");
233                 return OPERATOR_CANCELLED;
234         }
235
236         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
237         {
238                 if (ob != obedit) {
239                         DEG_id_tag_update(&ob->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY | ID_RECALC_ANIMATION);
240                         par = obedit->parent;
241
242                         if (BKE_object_parent_loop_check(par, ob)) {
243                                 BKE_report(op->reports, RPT_ERROR, "Loop in parents");
244                         }
245                         else {
246                                 Object workob;
247
248                                 ob->parent = BASACT(view_layer)->object;
249                                 if (v3) {
250                                         ob->partype = PARVERT3;
251                                         ob->par1 = v1 - 1;
252                                         ob->par2 = v2 - 1;
253                                         ob->par3 = v3 - 1;
254
255                                         /* inverse parent matrix */
256                                         BKE_object_workob_calc_parent(depsgraph, scene, ob, &workob);
257                                         invert_m4_m4(ob->parentinv, workob.obmat);
258                                 }
259                                 else {
260                                         ob->partype = PARVERT1;
261                                         ob->par1 = v1 - 1;
262
263                                         /* inverse parent matrix */
264                                         BKE_object_workob_calc_parent(depsgraph, scene, ob, &workob);
265                                         invert_m4_m4(ob->parentinv, workob.obmat);
266                                 }
267                         }
268                 }
269         }
270         CTX_DATA_END;
271
272         DEG_relations_tag_update(bmain);
273
274         WM_event_add_notifier(C, NC_OBJECT, NULL);
275
276         return OPERATOR_FINISHED;
277 }
278
279 void OBJECT_OT_vertex_parent_set(wmOperatorType *ot)
280 {
281         /* identifiers */
282         ot->name = "Make Vertex Parent";
283         ot->description = "Parent selected objects to the selected vertices";
284         ot->idname = "OBJECT_OT_vertex_parent_set";
285
286         /* api callbacks */
287         ot->invoke = WM_operator_confirm;
288         ot->poll = vertex_parent_set_poll;
289         ot->exec = vertex_parent_set_exec;
290
291         /* flags */
292         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
293 }
294
295 /********************** Make Proxy Operator *************************/
296
297 /* set the object to proxify */
298 static int make_proxy_invoke(bContext *C, wmOperator *op, const wmEvent *event)
299 {
300         Scene *scene = CTX_data_scene(C);
301         Object *ob = ED_object_active_context(C);
302
303         /* sanity checks */
304         if (!scene || ID_IS_LINKED(scene) || !ob)
305                 return OPERATOR_CANCELLED;
306
307         /* Get object to work on - use a menu if we need to... */
308         if (ob->dup_group && ID_IS_LINKED(ob->dup_group)) {
309                 /* gives menu with list of objects in group */
310                 /* proxy_group_objects_menu(C, op, ob, ob->dup_group); */
311                 WM_enum_search_invoke(C, op, event);
312                 return OPERATOR_CANCELLED;
313         }
314         else if (ID_IS_LINKED(ob)) {
315                 uiPopupMenu *pup = UI_popup_menu_begin(C, IFACE_("OK?"), ICON_QUESTION);
316                 uiLayout *layout = UI_popup_menu_layout(pup);
317
318                 /* create operator menu item with relevant properties filled in */
319                 PointerRNA opptr_dummy;
320                 uiItemFullO_ptr(layout, op->type, op->type->name, ICON_NONE, NULL,
321                                 WM_OP_EXEC_REGION_WIN, 0, &opptr_dummy);
322
323                 /* present the menu and be done... */
324                 UI_popup_menu_end(C, pup);
325
326                 /* this invoke just calls another instance of this operator... */
327                 return OPERATOR_INTERFACE;
328         }
329         else {
330                 /* error.. cannot continue */
331                 BKE_report(op->reports, RPT_ERROR, "Can only make proxy for a referenced object or collection");
332                 return OPERATOR_CANCELLED;
333         }
334
335 }
336
337 static int make_proxy_exec(bContext *C, wmOperator *op)
338 {
339         Main *bmain = CTX_data_main(C);
340         Object *ob, *gob = ED_object_active_context(C);
341         Scene *scene = CTX_data_scene(C);
342         ViewLayer *view_layer = CTX_data_view_layer(C);
343
344         if (gob->dup_group != NULL) {
345                 const ListBase dup_group_objects = BKE_collection_object_cache_get(gob->dup_group);
346                 Base *base = BLI_findlink(&dup_group_objects, RNA_enum_get(op->ptr, "object"));
347                 ob = base->object;
348         }
349         else {
350                 ob = gob;
351         }
352
353         if (ob) {
354                 Object *newob;
355                 char name[MAX_ID_NAME + 4];
356
357                 BLI_snprintf(name, sizeof(name), "%s_proxy", ((ID *)(gob ? gob : ob))->name + 2);
358
359                 /* Add new object for the proxy */
360                 newob = BKE_object_add_from(bmain, scene, view_layer, OB_EMPTY, name, gob ? gob : ob);
361
362                 /* set layers OK */
363                 BKE_object_make_proxy(bmain, newob, ob, gob);
364
365                 /* Set back pointer immediately so dependency graph knows that this is
366                  * is a proxy and will act accordingly. Otherwise correctness of graph
367                  * will depend on order of bases.
368                  *
369                  * TODO(sergey): We really need to get rid of this bi-directional links
370                  * in proxies with something like static overrides.
371                  */
372                 newob->proxy->proxy_from = newob;
373
374                 /* depsgraph flushes are needed for the new data */
375                 DEG_relations_tag_update(bmain);
376                 DEG_id_tag_update(&newob->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY | ID_RECALC_ANIMATION);
377                 WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, newob);
378         }
379         else {
380                 BKE_report(op->reports, RPT_ERROR, "No object to make proxy for");
381                 return OPERATOR_CANCELLED;
382         }
383
384         return OPERATOR_FINISHED;
385 }
386
387 /* Generic itemf's for operators that take library args */
388 static const EnumPropertyItem *proxy_collection_object_itemf(bContext *C, PointerRNA *UNUSED(ptr),
389                                                              PropertyRNA *UNUSED(prop), bool *r_free)
390 {
391         EnumPropertyItem item_tmp = {0}, *item = NULL;
392         int totitem = 0;
393         int i = 0;
394         Object *ob = ED_object_active_context(C);
395
396         if (!ob || !ob->dup_group)
397                 return DummyRNA_DEFAULT_items;
398
399         /* find the object to affect */
400         FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(ob->dup_group, object)
401         {
402                 item_tmp.identifier = item_tmp.name = object->id.name + 2;
403                 item_tmp.value = i++;
404                 RNA_enum_item_add(&item, &totitem, &item_tmp);
405         }
406         FOREACH_COLLECTION_OBJECT_RECURSIVE_END;
407
408         RNA_enum_item_end(&item, &totitem);
409         *r_free = true;
410
411         return item;
412 }
413
414 void OBJECT_OT_proxy_make(wmOperatorType *ot)
415 {
416         PropertyRNA *prop;
417
418         /* identifiers */
419         ot->name = "Make Proxy";
420         ot->idname = "OBJECT_OT_proxy_make";
421         ot->description = "Add empty object to become local replacement data of a library-linked object";
422
423         /* callbacks */
424         ot->invoke = make_proxy_invoke;
425         ot->exec = make_proxy_exec;
426         ot->poll = ED_operator_object_active;
427
428         /* flags */
429         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
430
431         /* properties */
432         /* XXX, relies on hard coded ID at the moment */
433         prop = RNA_def_enum(ot->srna, "object", DummyRNA_DEFAULT_items, 0, "Proxy Object",
434                             "Name of lib-linked/collection object to make a proxy for");
435         RNA_def_enum_funcs(prop, proxy_collection_object_itemf);
436         RNA_def_property_flag(prop, PROP_ENUM_NO_TRANSLATE);
437         ot->prop = prop;
438 }
439
440 /********************** Clear Parent Operator ******************* */
441
442 typedef enum eObClearParentTypes {
443         CLEAR_PARENT_ALL = 0,
444         CLEAR_PARENT_KEEP_TRANSFORM,
445         CLEAR_PARENT_INVERSE
446 } eObClearParentTypes;
447
448 EnumPropertyItem prop_clear_parent_types[] = {
449         {CLEAR_PARENT_ALL, "CLEAR", 0, "Clear Parent",
450          "Completely clear the parenting relationship, including involved modifiers if any"},
451         {CLEAR_PARENT_KEEP_TRANSFORM, "CLEAR_KEEP_TRANSFORM", 0, "Clear and Keep Transformation",
452          "As 'Clear Parent', but keep the current visual transformations of the object"},
453         {CLEAR_PARENT_INVERSE, "CLEAR_INVERSE", 0, "Clear Parent Inverse",
454          "Reset the transform corrections applied to the parenting relationship, does not remove parenting itself"},
455         {0, NULL, 0, NULL, NULL}
456 };
457
458 /* Helper for ED_object_parent_clear() - Remove deform-modifiers associated with parent */
459 static void object_remove_parent_deform_modifiers(Object *ob, const Object *par)
460 {
461         if (ELEM(par->type, OB_ARMATURE, OB_LATTICE, OB_CURVE)) {
462                 ModifierData *md, *mdn;
463
464                 /* assume that we only need to remove the first instance of matching deform modifier here */
465                 for (md = ob->modifiers.first; md; md = mdn) {
466                         bool free = false;
467
468                         mdn = md->next;
469
470                         /* need to match types (modifier + parent) and references */
471                         if ((md->type == eModifierType_Armature) && (par->type == OB_ARMATURE)) {
472                                 ArmatureModifierData *amd = (ArmatureModifierData *)md;
473                                 if (amd->object == par) {
474                                         free = true;
475                                 }
476                         }
477                         else if ((md->type == eModifierType_Lattice) && (par->type == OB_LATTICE)) {
478                                 LatticeModifierData *lmd = (LatticeModifierData *)md;
479                                 if (lmd->object == par) {
480                                         free = true;
481                                 }
482                         }
483                         else if ((md->type == eModifierType_Curve) && (par->type == OB_CURVE)) {
484                                 CurveModifierData *cmd = (CurveModifierData *)md;
485                                 if (cmd->object == par) {
486                                         free = true;
487                                 }
488                         }
489
490                         /* free modifier if match */
491                         if (free) {
492                                 BLI_remlink(&ob->modifiers, md);
493                                 modifier_free(md);
494                         }
495                 }
496         }
497 }
498
499 void ED_object_parent_clear(Object *ob, const int type)
500 {
501         if (ob->parent == NULL)
502                 return;
503
504         switch (type) {
505                 case CLEAR_PARENT_ALL:
506                 {
507                         /* for deformers, remove corresponding modifiers to prevent a large number of modifiers building up */
508                         object_remove_parent_deform_modifiers(ob, ob->parent);
509
510                         /* clear parenting relationship completely */
511                         ob->parent = NULL;
512                         break;
513                 }
514                 case CLEAR_PARENT_KEEP_TRANSFORM:
515                 {
516                         /* remove parent, and apply the parented transform result as object's local transforms */
517                         ob->parent = NULL;
518                         BKE_object_apply_mat4(ob, ob->obmat, true, false);
519                         break;
520                 }
521                 case CLEAR_PARENT_INVERSE:
522                 {
523                         /* object stays parented, but the parent inverse (i.e. offset from parent to retain binding state)
524                          * is cleared. In other words: nothing to do here! */
525                         break;
526                 }
527         }
528
529         /* Always clear parentinv matrix for sake of consistency, see T41950. */
530         unit_m4(ob->parentinv);
531
532         DEG_id_tag_update(&ob->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY | ID_RECALC_ANIMATION);
533 }
534
535 /* note, poll should check for editable scene */
536 static int parent_clear_exec(bContext *C, wmOperator *op)
537 {
538         Main *bmain = CTX_data_main(C);
539         const int type = RNA_enum_get(op->ptr, "type");
540
541         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
542         {
543                 ED_object_parent_clear(ob, type);
544         }
545         CTX_DATA_END;
546
547         DEG_relations_tag_update(bmain);
548         WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL);
549         WM_event_add_notifier(C, NC_OBJECT | ND_PARENT, NULL);
550         return OPERATOR_FINISHED;
551 }
552
553 void OBJECT_OT_parent_clear(wmOperatorType *ot)
554 {
555         /* identifiers */
556         ot->name = "Clear Parent";
557         ot->description = "Clear the object's parenting";
558         ot->idname = "OBJECT_OT_parent_clear";
559
560         /* api callbacks */
561         ot->invoke = WM_menu_invoke;
562         ot->exec = parent_clear_exec;
563
564         ot->poll = ED_operator_object_active_editable;
565
566         /* flags */
567         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
568
569         ot->prop = RNA_def_enum(ot->srna, "type", prop_clear_parent_types, CLEAR_PARENT_ALL, "Type", "");
570 }
571
572 /* ******************** Make Parent Operator *********************** */
573
574 void ED_object_parent(Object *ob, Object *par, const int type, const char *substr)
575 {
576         /* Always clear parentinv matrix for sake of consistency, see T41950. */
577         unit_m4(ob->parentinv);
578
579         if (!par || BKE_object_parent_loop_check(par, ob)) {
580                 ob->parent = NULL;
581                 ob->partype = PAROBJECT;
582                 ob->parsubstr[0] = 0;
583                 return;
584         }
585
586         /* Other partypes are deprecated, do not use here! */
587         BLI_assert(ELEM(type & PARTYPE, PAROBJECT, PARSKEL, PARVERT1, PARVERT3, PARBONE));
588
589         /* this could use some more checks */
590
591         ob->parent = par;
592         ob->partype &= ~PARTYPE;
593         ob->partype |= type;
594         BLI_strncpy(ob->parsubstr, substr, sizeof(ob->parsubstr));
595 }
596
597 /* Operator Property */
598 EnumPropertyItem prop_make_parent_types[] = {
599         {PAR_OBJECT, "OBJECT", 0, "Object", ""},
600         {PAR_ARMATURE, "ARMATURE", 0, "Armature Deform", ""},
601         {PAR_ARMATURE_NAME, "ARMATURE_NAME", 0, "   With Empty Groups", ""},
602         {PAR_ARMATURE_AUTO, "ARMATURE_AUTO", 0, "   With Automatic Weights", ""},
603         {PAR_ARMATURE_ENVELOPE, "ARMATURE_ENVELOPE", 0, "   With Envelope Weights", ""},
604         {PAR_BONE, "BONE", 0, "Bone", ""},
605         {PAR_BONE_RELATIVE, "BONE_RELATIVE", 0, "Bone Relative", ""},
606         {PAR_CURVE, "CURVE", 0, "Curve Deform", ""},
607         {PAR_FOLLOW, "FOLLOW", 0, "Follow Path", ""},
608         {PAR_PATH_CONST, "PATH_CONST", 0, "Path Constraint", ""},
609         {PAR_LATTICE, "LATTICE", 0, "Lattice Deform", ""},
610         {PAR_VERTEX, "VERTEX", 0, "Vertex", ""},
611         {PAR_VERTEX_TRI, "VERTEX_TRI", 0, "Vertex (Triangle)", ""},
612         {0, NULL, 0, NULL, NULL}
613 };
614
615 bool ED_object_parent_set(ReportList *reports, const bContext *C, Scene *scene, Object *ob, Object *par,
616                           int partype, const bool xmirror, const bool keep_transform, const int vert_par[3])
617 {
618         Main *bmain = CTX_data_main(C);
619         Depsgraph *depsgraph = CTX_data_depsgraph(C);
620         bPoseChannel *pchan = NULL;
621         const bool pararm = ELEM(partype, PAR_ARMATURE, PAR_ARMATURE_NAME, PAR_ARMATURE_ENVELOPE, PAR_ARMATURE_AUTO);
622
623         DEG_id_tag_update(&par->id, ID_RECALC_TRANSFORM);
624
625         /* preconditions */
626         if (partype == PAR_FOLLOW || partype == PAR_PATH_CONST) {
627                 if (par->type != OB_CURVE)
628                         return 0;
629                 else {
630                         Curve *cu = par->data;
631
632                         if ((cu->flag & CU_PATH) == 0) {
633                                 cu->flag |= CU_PATH | CU_FOLLOW;
634                                 BKE_displist_make_curveTypes(depsgraph, scene, par, false, false);  /* force creation of path data */
635                         }
636                         else {
637                                 cu->flag |= CU_FOLLOW;
638                         }
639
640                         /* if follow, add F-Curve for ctime (i.e. "eval_time") so that path-follow works */
641                         if (partype == PAR_FOLLOW) {
642                                 /* get or create F-Curve */
643                                 bAction *act = verify_adt_action(bmain, &cu->id, 1);
644                                 FCurve *fcu = verify_fcurve(bmain, act, NULL, NULL, "eval_time", 0, 1);
645
646                                 /* setup dummy 'generator' modifier here to get 1-1 correspondence still working */
647                                 if (!fcu->bezt && !fcu->fpt && !fcu->modifiers.first)
648                                         add_fmodifier(&fcu->modifiers, FMODIFIER_TYPE_GENERATOR, fcu);
649                         }
650
651                         /* fall back on regular parenting now (for follow only) */
652                         if (partype == PAR_FOLLOW)
653                                 partype = PAR_OBJECT;
654                 }
655         }
656         else if (ELEM(partype, PAR_BONE, PAR_BONE_RELATIVE)) {
657                 pchan = BKE_pose_channel_active(par);
658
659                 if (pchan == NULL) {
660                         BKE_report(reports, RPT_ERROR, "No active bone");
661                         return false;
662                 }
663         }
664
665         if (ob != par) {
666                 if (BKE_object_parent_loop_check(par, ob)) {
667                         BKE_report(reports, RPT_ERROR, "Loop in parents");
668                         return false;
669                 }
670                 else {
671                         Object workob;
672
673                         /* apply transformation of previous parenting */
674                         if (keep_transform) {
675                                 /* was removed because of bug [#23577],
676                                  * but this can be handy in some cases too [#32616], so make optional */
677                                 BKE_object_apply_mat4(ob, ob->obmat, false, false);
678                         }
679
680                         /* set the parent (except for follow-path constraint option) */
681                         if (partype != PAR_PATH_CONST) {
682                                 ob->parent = par;
683                                 /* Always clear parentinv matrix for sake of consistency, see T41950. */
684                                 unit_m4(ob->parentinv);
685                         }
686
687                         /* handle types */
688                         if (pchan)
689                                 BLI_strncpy(ob->parsubstr, pchan->name, sizeof(ob->parsubstr));
690                         else
691                                 ob->parsubstr[0] = 0;
692
693                         if (partype == PAR_PATH_CONST) {
694                                 /* don't do anything here, since this is not technically "parenting" */
695                         }
696                         else if (ELEM(partype, PAR_CURVE, PAR_LATTICE) || (pararm)) {
697                                 /* partype is now set to PAROBJECT so that invisible 'virtual' modifiers don't need to be created
698                                  * NOTE: the old (2.4x) method was to set ob->partype = PARSKEL, creating the virtual modifiers
699                                  */
700                                 ob->partype = PAROBJECT;  /* note, dna define, not operator property */
701                                 /* ob->partype = PARSKEL; */  /* note, dna define, not operator property */
702
703                                 /* BUT, to keep the deforms, we need a modifier, and then we need to set the object that it uses
704                                  * - We need to ensure that the modifier we're adding doesn't already exist, so we check this by
705                                  *   assuming that the parent is selected too...
706                                  */
707                                 /* XXX currently this should only happen for meshes, curves, surfaces,
708                                  * and lattices - this stuff isn't available for metas yet */
709                                 if (ELEM(ob->type, OB_MESH, OB_CURVE, OB_SURF, OB_FONT, OB_LATTICE)) {
710                                         ModifierData *md;
711
712                                         switch (partype) {
713                                                 case PAR_CURVE: /* curve deform */
714                                                         if (modifiers_isDeformedByCurve(ob) != par) {
715                                                                 md = ED_object_modifier_add(reports, bmain, scene, ob, NULL, eModifierType_Curve);
716                                                                 if (md) {
717                                                                         ((CurveModifierData *)md)->object = par;
718                                                                 }
719                                                                 if (par->runtime.curve_cache && par->runtime.curve_cache->path == NULL) {
720                                                                         DEG_id_tag_update(&par->id, ID_RECALC_GEOMETRY);
721                                                                 }
722                                                         }
723                                                         break;
724                                                 case PAR_LATTICE: /* lattice deform */
725                                                         if (modifiers_isDeformedByLattice(ob) != par) {
726                                                                 md = ED_object_modifier_add(reports, bmain, scene, ob, NULL, eModifierType_Lattice);
727                                                                 if (md) {
728                                                                         ((LatticeModifierData *)md)->object = par;
729                                                                 }
730                                                         }
731                                                         break;
732                                                 default: /* armature deform */
733                                                         if (modifiers_isDeformedByArmature(ob) != par) {
734                                                                 md = ED_object_modifier_add(reports, bmain, scene, ob, NULL, eModifierType_Armature);
735                                                                 if (md) {
736                                                                         ((ArmatureModifierData *)md)->object = par;
737                                                                 }
738                                                         }
739                                                         break;
740                                         }
741                                 }
742                         }
743                         else if (partype == PAR_BONE) {
744                                 ob->partype = PARBONE;  /* note, dna define, not operator property */
745                                 if (pchan->bone)
746                                         pchan->bone->flag &= ~BONE_RELATIVE_PARENTING;
747                         }
748                         else if (partype == PAR_BONE_RELATIVE) {
749                                 ob->partype = PARBONE;  /* note, dna define, not operator property */
750                                 if (pchan->bone)
751                                         pchan->bone->flag |= BONE_RELATIVE_PARENTING;
752                         }
753                         else if (partype == PAR_VERTEX) {
754                                 ob->partype = PARVERT1;
755                                 ob->par1 = vert_par[0];
756                         }
757                         else if (partype == PAR_VERTEX_TRI) {
758                                 ob->partype = PARVERT3;
759                                 copy_v3_v3_int(&ob->par1, vert_par);
760                         }
761                         else {
762                                 ob->partype = PAROBJECT;  /* note, dna define, not operator property */
763                         }
764
765                         /* constraint */
766                         if (partype == PAR_PATH_CONST) {
767                                 bConstraint *con;
768                                 bFollowPathConstraint *data;
769                                 float cmat[4][4], vec[3];
770
771                                 con = BKE_constraint_add_for_object(ob, "AutoPath", CONSTRAINT_TYPE_FOLLOWPATH);
772
773                                 data = con->data;
774                                 data->tar = par;
775
776                                 BKE_constraint_target_matrix_get(depsgraph, scene, con, 0, CONSTRAINT_OBTYPE_OBJECT, NULL, cmat, scene->r.cfra);
777                                 sub_v3_v3v3(vec, ob->obmat[3], cmat[3]);
778
779                                 copy_v3_v3(ob->loc, vec);
780                         }
781                         else if (pararm && (ob->type == OB_MESH) && (par->type == OB_ARMATURE)) {
782                                 if (partype == PAR_ARMATURE_NAME) {
783                                         ED_object_vgroup_calc_from_armature(reports, depsgraph, scene, ob, par, ARM_GROUPS_NAME, false);
784                                 }
785                                 else if (partype == PAR_ARMATURE_ENVELOPE) {
786                                         ED_object_vgroup_calc_from_armature(reports, depsgraph, scene, ob, par, ARM_GROUPS_ENVELOPE, xmirror);
787                                 }
788                                 else if (partype == PAR_ARMATURE_AUTO) {
789                                         WM_cursor_wait(1);
790                                         ED_object_vgroup_calc_from_armature(reports, depsgraph, scene, ob, par, ARM_GROUPS_AUTO, xmirror);
791                                         WM_cursor_wait(0);
792                                 }
793                                 /* get corrected inverse */
794                                 ob->partype = PAROBJECT;
795                                 BKE_object_workob_calc_parent(depsgraph, scene, ob, &workob);
796
797                                 invert_m4_m4(ob->parentinv, workob.obmat);
798                         }
799                         else if (pararm && (ob->type == OB_GPENCIL) && (par->type == OB_ARMATURE)) {
800                                 if (partype == PAR_ARMATURE_NAME) {
801                                         ED_gpencil_add_armature_weights(C, reports, ob, par, GP_PAR_ARMATURE_NAME);
802                                 }
803                                 else if ((partype == PAR_ARMATURE_AUTO) ||
804                                          (partype == PAR_ARMATURE_ENVELOPE))
805                                 {
806                                         WM_cursor_wait(1);
807                                         ED_gpencil_add_armature_weights(C, reports, ob, par, GP_PAR_ARMATURE_AUTO);
808                                         WM_cursor_wait(0);
809                                 }
810                                 /* get corrected inverse */
811                                 ob->partype = PAROBJECT;
812                                 BKE_object_workob_calc_parent(depsgraph, scene, ob, &workob);
813
814                                 invert_m4_m4(ob->parentinv, workob.obmat);
815                         }
816                         else {
817                                 /* calculate inverse parent matrix */
818                                 BKE_object_workob_calc_parent(depsgraph, scene, ob, &workob);
819                                 invert_m4_m4(ob->parentinv, workob.obmat);
820                         }
821
822                         DEG_id_tag_update(&ob->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY);
823                 }
824         }
825
826         return true;
827 }
828
829
830
831 static void parent_set_vert_find(KDTree *tree, Object *child, int vert_par[3], bool is_tri)
832 {
833         const float *co_find = child->obmat[3];
834         if (is_tri) {
835                 KDTreeNearest nearest[3];
836                 int tot;
837
838                 tot = BLI_kdtree_find_nearest_n(tree, co_find, nearest, 3);
839                 BLI_assert(tot == 3);
840                 UNUSED_VARS(tot);
841
842                 vert_par[0] = nearest[0].index;
843                 vert_par[1] = nearest[1].index;
844                 vert_par[2] = nearest[2].index;
845
846                 BLI_assert(min_iii(UNPACK3(vert_par)) >= 0);
847         }
848         else {
849                 vert_par[0] = BLI_kdtree_find_nearest(tree, co_find, NULL);
850                 BLI_assert(vert_par[0] >= 0);
851                 vert_par[1] = 0;
852                 vert_par[2] = 0;
853         }
854 }
855
856 static int parent_set_exec(bContext *C, wmOperator *op)
857 {
858         Main *bmain = CTX_data_main(C);
859         Scene *scene = CTX_data_scene(C);
860         Object *par = ED_object_active_context(C);
861         int partype = RNA_enum_get(op->ptr, "type");
862         const bool xmirror = RNA_boolean_get(op->ptr, "xmirror");
863         const bool keep_transform = RNA_boolean_get(op->ptr, "keep_transform");
864         bool ok = true;
865
866         /* vertex parent (kdtree) */
867         const bool is_vert_par = ELEM(partype, PAR_VERTEX, PAR_VERTEX_TRI);
868         const bool is_tri = partype == PAR_VERTEX_TRI;
869         int tree_tot;
870         struct KDTree *tree = NULL;
871         int vert_par[3] = {0, 0, 0};
872         const int *vert_par_p = is_vert_par ? vert_par : NULL;
873
874
875         if (is_vert_par) {
876                 tree = BKE_object_as_kdtree(par, &tree_tot);
877                 BLI_assert(tree != NULL);
878
879                 if (tree_tot < (is_tri ? 3 : 1)) {
880                         BKE_report(op->reports, RPT_ERROR, "Not enough vertices for vertex-parent");
881                         ok = false;
882                 }
883         }
884
885         if (ok) {
886                 /* Non vertex-parent */
887                 CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
888                 {
889                         if (is_vert_par) {
890                                 parent_set_vert_find(tree, ob, vert_par, is_tri);
891                         }
892
893                         if (!ED_object_parent_set(op->reports, C, scene, ob, par, partype, xmirror, keep_transform, vert_par_p)) {
894                                 ok = false;
895                                 break;
896                         }
897                 }
898                 CTX_DATA_END;
899         }
900
901         if (is_vert_par) {
902                 BLI_kdtree_free(tree);
903         }
904
905         if (!ok)
906                 return OPERATOR_CANCELLED;
907
908         DEG_relations_tag_update(bmain);
909         WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL);
910         WM_event_add_notifier(C, NC_OBJECT | ND_PARENT, NULL);
911
912         return OPERATOR_FINISHED;
913 }
914
915
916 static int parent_set_invoke(bContext *C, wmOperator *UNUSED(op), const wmEvent *UNUSED(event))
917 {
918         Object *ob = ED_object_active_context(C);
919         uiPopupMenu *pup = UI_popup_menu_begin(C, IFACE_("Set Parent To"), ICON_NONE);
920         uiLayout *layout = UI_popup_menu_layout(pup);
921
922         wmOperatorType *ot = WM_operatortype_find("OBJECT_OT_parent_set", true);
923         PointerRNA opptr;
924
925 #if 0
926         uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_OBJECT);
927 #else
928         uiItemFullO_ptr(layout, ot, IFACE_("Object"), ICON_NONE, NULL, WM_OP_EXEC_DEFAULT, 0, &opptr);
929         RNA_enum_set(&opptr, "type", PAR_OBJECT);
930         RNA_boolean_set(&opptr, "keep_transform", false);
931
932         uiItemFullO_ptr(
933                 layout, ot, IFACE_("Object (Keep Transform)"), ICON_NONE,
934                 NULL, WM_OP_EXEC_DEFAULT, 0, &opptr);
935         RNA_enum_set(&opptr, "type", PAR_OBJECT);
936         RNA_boolean_set(&opptr, "keep_transform", true);
937 #endif
938         /* ob becomes parent, make the associated menus */
939         if (ob->type == OB_ARMATURE) {
940                 uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_ARMATURE);
941                 uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_ARMATURE_NAME);
942                 uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_ARMATURE_ENVELOPE);
943                 uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_ARMATURE_AUTO);
944                 uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_BONE);
945                 uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_BONE_RELATIVE);
946         }
947         else if (ob->type == OB_CURVE) {
948                 uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_CURVE);
949                 uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_FOLLOW);
950                 uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_PATH_CONST);
951         }
952         else if (ob->type == OB_LATTICE) {
953                 uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_LATTICE);
954         }
955
956         /* vertex parenting */
957         if (OB_TYPE_SUPPORT_PARVERT(ob->type)) {
958                 uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_VERTEX);
959                 uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_VERTEX_TRI);
960         }
961
962         UI_popup_menu_end(C, pup);
963
964         return OPERATOR_INTERFACE;
965 }
966
967 static bool parent_set_poll_property(const bContext *UNUSED(C), wmOperator *op, const PropertyRNA *prop)
968 {
969         const char *prop_id = RNA_property_identifier(prop);
970
971         /* Only show XMirror for PAR_ARMATURE_ENVELOPE and PAR_ARMATURE_AUTO! */
972         if (STREQ(prop_id, "xmirror")) {
973                 const int type = RNA_enum_get(op->ptr, "type");
974                 if (ELEM(type, PAR_ARMATURE_ENVELOPE, PAR_ARMATURE_AUTO))
975                         return true;
976                 else
977                         return false;
978         }
979
980         return true;
981 }
982
983 void OBJECT_OT_parent_set(wmOperatorType *ot)
984 {
985         /* identifiers */
986         ot->name = "Make Parent";
987         ot->description = "Set the object's parenting";
988         ot->idname = "OBJECT_OT_parent_set";
989
990         /* api callbacks */
991         ot->invoke = parent_set_invoke;
992         ot->exec = parent_set_exec;
993         ot->poll = ED_operator_object_active;
994         ot->poll_property = parent_set_poll_property;
995
996         /* flags */
997         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
998
999         ot->prop = RNA_def_enum(ot->srna, "type", prop_make_parent_types, 0, "Type", "");
1000         RNA_def_boolean(ot->srna, "xmirror", false, "X Mirror",
1001                         "Apply weights symmetrically along X axis, for Envelope/Automatic vertex groups creation");
1002         RNA_def_boolean(ot->srna, "keep_transform", false, "Keep Transform",
1003                         "Apply transformation before parenting");
1004 }
1005
1006 /* ************ Make Parent Without Inverse Operator ******************* */
1007
1008 static int parent_noinv_set_exec(bContext *C, wmOperator *op)
1009 {
1010         Main *bmain = CTX_data_main(C);
1011         Object *par = ED_object_active_context(C);
1012
1013         DEG_id_tag_update(&par->id, ID_RECALC_TRANSFORM);
1014
1015         /* context iterator */
1016         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
1017         {
1018                 if (ob != par) {
1019                         if (BKE_object_parent_loop_check(par, ob)) {
1020                                 BKE_report(op->reports, RPT_ERROR, "Loop in parents");
1021                         }
1022                         else {
1023                                 /* clear inverse matrix and also the object location */
1024                                 unit_m4(ob->parentinv);
1025                                 memset(ob->loc, 0, 3 * sizeof(float));
1026
1027                                 /* set recalc flags */
1028                                 DEG_id_tag_update(&ob->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY);
1029
1030                                 /* set parenting type for object - object only... */
1031                                 ob->parent = par;
1032                                 ob->partype = PAROBJECT; /* note, dna define, not operator property */
1033                         }
1034                 }
1035         }
1036         CTX_DATA_END;
1037
1038         DEG_relations_tag_update(bmain);
1039         WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL);
1040
1041         return OPERATOR_FINISHED;
1042 }
1043
1044 void OBJECT_OT_parent_no_inverse_set(wmOperatorType *ot)
1045 {
1046         /* identifiers */
1047         ot->name = "Make Parent without Inverse";
1048         ot->description = "Set the object's parenting without setting the inverse parent correction";
1049         ot->idname = "OBJECT_OT_parent_no_inverse_set";
1050
1051         /* api callbacks */
1052         ot->invoke = WM_operator_confirm;
1053         ot->exec = parent_noinv_set_exec;
1054         ot->poll = ED_operator_object_active_editable;
1055
1056         /* flags */
1057         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1058 }
1059
1060 /************************ Clear Slow Parent Operator *********************/
1061
1062 static int object_slow_parent_clear_exec(bContext *C, wmOperator *UNUSED(op))
1063 {
1064         Depsgraph *depsgraph = CTX_data_depsgraph(C);
1065         Scene *scene = CTX_data_scene(C);
1066
1067         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
1068         {
1069                 if (ob->parent) {
1070                         if (ob->partype & PARSLOW) {
1071                                 ob->partype -= PARSLOW;
1072                                 BKE_object_where_is_calc(depsgraph, scene, ob);
1073                                 ob->partype |= PARSLOW;
1074                                 DEG_id_tag_update(&ob->id, ID_RECALC_TRANSFORM);
1075                         }
1076                 }
1077         }
1078         CTX_DATA_END;
1079
1080         WM_event_add_notifier(C, NC_SCENE, scene);
1081
1082         return OPERATOR_FINISHED;
1083 }
1084
1085 void OBJECT_OT_slow_parent_clear(wmOperatorType *ot)
1086 {
1087         /* identifiers */
1088         ot->name = "Clear Slow Parent";
1089         ot->description = "Clear the object's slow parent";
1090         ot->idname = "OBJECT_OT_slow_parent_clear";
1091
1092         /* api callbacks */
1093         ot->invoke = WM_operator_confirm;
1094         ot->exec = object_slow_parent_clear_exec;
1095         ot->poll = ED_operator_view3d_active;
1096
1097         /* flags */
1098         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1099 }
1100
1101 /********************** Make Slow Parent Operator *********************/
1102
1103 static int object_slow_parent_set_exec(bContext *C, wmOperator *UNUSED(op))
1104 {
1105         Scene *scene = CTX_data_scene(C);
1106
1107         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
1108         {
1109                 if (ob->parent)
1110                         ob->partype |= PARSLOW;
1111
1112                 DEG_id_tag_update(&ob->id, ID_RECALC_TRANSFORM);
1113         }
1114         CTX_DATA_END;
1115
1116         WM_event_add_notifier(C, NC_SCENE, scene);
1117
1118         return OPERATOR_FINISHED;
1119 }
1120
1121 void OBJECT_OT_slow_parent_set(wmOperatorType *ot)
1122 {
1123         /* identifiers */
1124         ot->name = "Set Slow Parent";
1125         ot->description = "Set the object's slow parent";
1126         ot->idname = "OBJECT_OT_slow_parent_set";
1127
1128         /* api callbacks */
1129         ot->invoke = WM_operator_confirm;
1130         ot->exec = object_slow_parent_set_exec;
1131         ot->poll = ED_operator_view3d_active;
1132
1133         /* flags */
1134         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1135 }
1136
1137 /* ******************** Clear Track Operator ******************* */
1138
1139 enum {
1140         CLEAR_TRACK                = 1,
1141         CLEAR_TRACK_KEEP_TRANSFORM = 2,
1142 };
1143
1144 static const EnumPropertyItem prop_clear_track_types[] = {
1145         {CLEAR_TRACK, "CLEAR", 0, "Clear Track", ""},
1146         {CLEAR_TRACK_KEEP_TRANSFORM, "CLEAR_KEEP_TRANSFORM", 0, "Clear and Keep Transformation (Clear Track)", ""},
1147         {0, NULL, 0, NULL, NULL}
1148 };
1149
1150 /* note, poll should check for editable scene */
1151 static int object_track_clear_exec(bContext *C, wmOperator *op)
1152 {
1153         Main *bmain = CTX_data_main(C);
1154         const int type = RNA_enum_get(op->ptr, "type");
1155
1156         if (CTX_data_edit_object(C)) {
1157                 BKE_report(op->reports, RPT_ERROR, "Operation cannot be performed in edit mode");
1158                 return OPERATOR_CANCELLED;
1159         }
1160         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
1161         {
1162                 bConstraint *con, *pcon;
1163
1164                 /* remove track-object for old track */
1165                 ob->track = NULL;
1166                 DEG_id_tag_update(&ob->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY | ID_RECALC_ANIMATION);
1167
1168                 /* also remove all tracking constraints */
1169                 for (con = ob->constraints.last; con; con = pcon) {
1170                         pcon = con->prev;
1171                         if (ELEM(con->type, CONSTRAINT_TYPE_TRACKTO, CONSTRAINT_TYPE_LOCKTRACK, CONSTRAINT_TYPE_DAMPTRACK))
1172                                 BKE_constraint_remove(&ob->constraints, con);
1173                 }
1174
1175                 if (type == CLEAR_TRACK_KEEP_TRANSFORM)
1176                         BKE_object_apply_mat4(ob, ob->obmat, true, true);
1177         }
1178         CTX_DATA_END;
1179
1180         DEG_relations_tag_update(bmain);
1181         WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL);
1182
1183         return OPERATOR_FINISHED;
1184 }
1185
1186 void OBJECT_OT_track_clear(wmOperatorType *ot)
1187 {
1188         /* identifiers */
1189         ot->name = "Clear Track";
1190         ot->description = "Clear tracking constraint or flag from object";
1191         ot->idname = "OBJECT_OT_track_clear";
1192
1193         /* api callbacks */
1194         ot->invoke = WM_menu_invoke;
1195         ot->exec = object_track_clear_exec;
1196
1197         ot->poll = ED_operator_objectmode;
1198
1199         /* flags */
1200         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1201
1202         ot->prop = RNA_def_enum(ot->srna, "type", prop_clear_track_types, 0, "Type", "");
1203 }
1204
1205 /************************** Make Track Operator *****************************/
1206
1207 enum {
1208         CREATE_TRACK_DAMPTRACK = 1,
1209         CREATE_TRACK_TRACKTO   = 2,
1210         CREATE_TRACK_LOCKTRACK = 3,
1211 };
1212
1213 static const EnumPropertyItem prop_make_track_types[] = {
1214         {CREATE_TRACK_DAMPTRACK, "DAMPTRACK", 0, "Damped Track Constraint", ""},
1215         {CREATE_TRACK_TRACKTO, "TRACKTO", 0, "Track To Constraint", ""},
1216         {CREATE_TRACK_LOCKTRACK, "LOCKTRACK", 0, "Lock Track Constraint", ""},
1217         {0, NULL, 0, NULL, NULL}
1218 };
1219
1220 static int track_set_exec(bContext *C, wmOperator *op)
1221 {
1222         Main *bmain = CTX_data_main(C);
1223         Object *obact = ED_object_active_context(C);
1224
1225         const int type = RNA_enum_get(op->ptr, "type");
1226
1227         switch (type) {
1228                 case CREATE_TRACK_DAMPTRACK:
1229                 {
1230                         bConstraint *con;
1231                         bDampTrackConstraint *data;
1232
1233                         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
1234                         {
1235                                 if (ob != obact) {
1236                                         con = BKE_constraint_add_for_object(ob, "AutoTrack", CONSTRAINT_TYPE_DAMPTRACK);
1237
1238                                         data = con->data;
1239                                         data->tar = obact;
1240                                         DEG_id_tag_update(&ob->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY | ID_RECALC_ANIMATION);
1241
1242                                         /* Lamp, Camera and Speaker track differently by default */
1243                                         if (ELEM(ob->type, OB_LAMP, OB_CAMERA, OB_SPEAKER)) {
1244                                                 data->trackflag = TRACK_nZ;
1245                                         }
1246                                 }
1247                         }
1248                         CTX_DATA_END;
1249                         break;
1250                 }
1251                 case CREATE_TRACK_TRACKTO:
1252                 {
1253                         bConstraint *con;
1254                         bTrackToConstraint *data;
1255
1256                         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
1257                         {
1258                                 if (ob != obact) {
1259                                         con = BKE_constraint_add_for_object(ob, "AutoTrack", CONSTRAINT_TYPE_TRACKTO);
1260
1261                                         data = con->data;
1262                                         data->tar = obact;
1263                                         DEG_id_tag_update(&ob->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY | ID_RECALC_ANIMATION);
1264
1265                                         /* Lamp, Camera and Speaker track differently by default */
1266                                         if (ELEM(ob->type, OB_LAMP, OB_CAMERA, OB_SPEAKER)) {
1267                                                 data->reserved1 = TRACK_nZ;
1268                                                 data->reserved2 = UP_Y;
1269                                         }
1270                                 }
1271                         }
1272                         CTX_DATA_END;
1273                         break;
1274                 }
1275                 case CREATE_TRACK_LOCKTRACK:
1276                 {
1277                         bConstraint *con;
1278                         bLockTrackConstraint *data;
1279
1280                         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
1281                         {
1282                                 if (ob != obact) {
1283                                         con = BKE_constraint_add_for_object(ob, "AutoTrack", CONSTRAINT_TYPE_LOCKTRACK);
1284
1285                                         data = con->data;
1286                                         data->tar = obact;
1287                                         DEG_id_tag_update(&ob->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY | ID_RECALC_ANIMATION);
1288
1289                                         /* Lamp, Camera and Speaker track differently by default */
1290                                         if (ELEM(ob->type, OB_LAMP, OB_CAMERA, OB_SPEAKER)) {
1291                                                 data->trackflag = TRACK_nZ;
1292                                                 data->lockflag = LOCK_Y;
1293                                         }
1294                                 }
1295                         }
1296                         CTX_DATA_END;
1297                         break;
1298                 }
1299         }
1300
1301         DEG_relations_tag_update(bmain);
1302         WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL);
1303
1304         return OPERATOR_FINISHED;
1305 }
1306
1307 void OBJECT_OT_track_set(wmOperatorType *ot)
1308 {
1309         /* identifiers */
1310         ot->name = "Make Track";
1311         ot->description = "Make the object track another object, using various methods/constraints";
1312         ot->idname = "OBJECT_OT_track_set";
1313
1314         /* api callbacks */
1315         ot->invoke = WM_menu_invoke;
1316         ot->exec = track_set_exec;
1317
1318         ot->poll = ED_operator_objectmode;
1319
1320         /* flags */
1321         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1322
1323         /* properties */
1324         ot->prop = RNA_def_enum(ot->srna, "type", prop_make_track_types, 0, "Type", "");
1325 }
1326
1327 /************************** Link to Scene Operator *****************************/
1328
1329 #if 0
1330 static void link_to_scene(Main *UNUSED(bmain), unsigned short UNUSED(nr))
1331 {
1332         Scene *sce = (Scene *) BLI_findlink(&bmain->scene, G.curscreen->scenenr - 1);
1333         Base *base, *nbase;
1334
1335         if (sce == NULL) return;
1336         if (sce->id.lib) return;
1337
1338         for (base = FIRSTBASE; base; base = base->next) {
1339                 if (TESTBASE(v3d, base)) {
1340                         nbase = MEM_mallocN(sizeof(Base), "newbase");
1341                         *nbase = *base;
1342                         BLI_addhead(&(sce->base), nbase);
1343                         id_us_plus((ID *)base->object);
1344                 }
1345         }
1346 }
1347 #endif
1348
1349 static int make_links_scene_exec(bContext *C, wmOperator *op)
1350 {
1351         Main *bmain = CTX_data_main(C);
1352         Scene *scene_to = BLI_findlink(&bmain->scene, RNA_enum_get(op->ptr, "scene"));
1353
1354         if (scene_to == NULL) {
1355                 BKE_report(op->reports, RPT_ERROR, "Could not find scene");
1356                 return OPERATOR_CANCELLED;
1357         }
1358
1359         if (scene_to == CTX_data_scene(C)) {
1360                 BKE_report(op->reports, RPT_ERROR, "Cannot link objects into the same scene");
1361                 return OPERATOR_CANCELLED;
1362         }
1363
1364         if (ID_IS_LINKED(scene_to)) {
1365                 BKE_report(op->reports, RPT_ERROR, "Cannot link objects into a linked scene");
1366                 return OPERATOR_CANCELLED;
1367         }
1368
1369         Collection *collection_to = BKE_collection_master(scene_to);
1370         CTX_DATA_BEGIN (C, Base *, base, selected_bases)
1371         {
1372                 BKE_collection_object_add(bmain, collection_to, base->object);
1373         }
1374         CTX_DATA_END;
1375
1376         /* redraw the 3D view because the object center points are colored differently */
1377         WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, NULL);
1378
1379         /* one day multiple scenes will be visible, then we should have some update function for them */
1380         return OPERATOR_FINISHED;
1381 }
1382
1383 enum {
1384         MAKE_LINKS_OBDATA     = 1,
1385         MAKE_LINKS_MATERIALS  = 2,
1386         MAKE_LINKS_ANIMDATA   = 3,
1387         MAKE_LINKS_GROUP      = 4,
1388         MAKE_LINKS_DUPLICOLLECTION = 5,
1389         MAKE_LINKS_MODIFIERS  = 6,
1390         MAKE_LINKS_FONTS      = 7,
1391 };
1392
1393 /* Return true if make link data is allowed, false otherwise */
1394 static bool allow_make_links_data(const int type, Object *ob_src, Object *ob_dst)
1395 {
1396         switch (type) {
1397                 case MAKE_LINKS_OBDATA:
1398                         if (ob_src->type == ob_dst->type && ob_src->type != OB_EMPTY) {
1399                                 return true;
1400                         }
1401                         break;
1402                 case MAKE_LINKS_MATERIALS:
1403                         if (OB_TYPE_SUPPORT_MATERIAL(ob_src->type) && OB_TYPE_SUPPORT_MATERIAL(ob_dst->type)) {
1404                                 return true;
1405                         }
1406                         break;
1407                 case MAKE_LINKS_ANIMDATA:
1408                 case MAKE_LINKS_GROUP:
1409                 case MAKE_LINKS_DUPLICOLLECTION:
1410                         return true;
1411                 case MAKE_LINKS_MODIFIERS:
1412                         if (!ELEM(OB_EMPTY, ob_src->type, ob_dst->type)) {
1413                                 return true;
1414                         }
1415                         break;
1416                 case MAKE_LINKS_FONTS:
1417                         if ((ob_src->data != ob_dst->data) && (ob_src->type == OB_FONT) && (ob_dst->type == OB_FONT)) {
1418                                 return true;
1419                         }
1420                         break;
1421         }
1422         return false;
1423 }
1424
1425 static int make_links_data_exec(bContext *C, wmOperator *op)
1426 {
1427         Scene *scene = CTX_data_scene(C);
1428         Main *bmain = CTX_data_main(C);
1429         const int type = RNA_enum_get(op->ptr, "type");
1430         Object *ob_src;
1431         ID *obdata_id;
1432         int a;
1433
1434         /* collection */
1435         LinkNode *ob_collections = NULL;
1436         bool is_cycle = false;
1437         bool is_lib = false;
1438
1439         ob_src = ED_object_active_context(C);
1440
1441         /* avoid searching all collections in source object each time */
1442         if (type == MAKE_LINKS_GROUP) {
1443                 ob_collections = BKE_object_groups(bmain, ob_src);
1444         }
1445
1446         CTX_DATA_BEGIN (C, Base *, base_dst, selected_editable_bases)
1447         {
1448                 Object *ob_dst = base_dst->object;
1449
1450                 if (ob_src != ob_dst) {
1451                         if (allow_make_links_data(type, ob_src, ob_dst)) {
1452                                 obdata_id = ob_dst->data;
1453
1454                                 switch (type) {
1455                                         case MAKE_LINKS_OBDATA: /* obdata */
1456                                                 id_us_min(obdata_id);
1457
1458                                                 obdata_id = ob_src->data;
1459                                                 id_us_plus(obdata_id);
1460                                                 ob_dst->data = obdata_id;
1461
1462                                                 /* if amount of material indices changed: */
1463                                                 test_object_materials(bmain, ob_dst, ob_dst->data);
1464
1465                                                 DEG_id_tag_update(&ob_dst->id, ID_RECALC_GEOMETRY);
1466                                                 break;
1467                                         case MAKE_LINKS_MATERIALS:
1468                                                 /* new approach, using functions from kernel */
1469                                                 for (a = 0; a < ob_src->totcol; a++) {
1470                                                         Material *ma = give_current_material(ob_src, a + 1);
1471                                                         assign_material(bmain, ob_dst, ma, a + 1, BKE_MAT_ASSIGN_USERPREF); /* also works with ma==NULL */
1472                                                 }
1473                                                 DEG_id_tag_update(&ob_dst->id, ID_RECALC_GEOMETRY);
1474                                                 break;
1475                                         case MAKE_LINKS_ANIMDATA:
1476                                                 BKE_animdata_copy_id(bmain, (ID *)ob_dst, (ID *)ob_src, 0);
1477                                                 if (ob_dst->data && ob_src->data) {
1478                                                         if (ID_IS_LINKED(obdata_id)) {
1479                                                                 is_lib = true;
1480                                                                 break;
1481                                                         }
1482                                                         BKE_animdata_copy_id(bmain, (ID *)ob_dst->data, (ID *)ob_src->data, 0);
1483                                                 }
1484                                                 DEG_id_tag_update(&ob_dst->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY | ID_RECALC_ANIMATION);
1485                                                 break;
1486                                         case MAKE_LINKS_GROUP:
1487                                         {
1488                                                 LinkNode *collection_node;
1489
1490                                                 /* first clear collections */
1491                                                 BKE_object_groups_clear(bmain, ob_dst);
1492
1493                                                 /* now add in the collections from the link nodes */
1494                                                 for (collection_node = ob_collections; collection_node; collection_node = collection_node->next) {
1495                                                         if (ob_dst->dup_group != collection_node->link) {
1496                                                                 BKE_collection_object_add(bmain, collection_node->link, ob_dst);
1497                                                         }
1498                                                         else {
1499                                                                 is_cycle = true;
1500                                                         }
1501                                                 }
1502                                                 break;
1503                                         }
1504                                         case MAKE_LINKS_DUPLICOLLECTION:
1505                                                 ob_dst->dup_group = ob_src->dup_group;
1506                                                 if (ob_dst->dup_group) {
1507                                                         id_us_plus(&ob_dst->dup_group->id);
1508                                                         ob_dst->transflag |= OB_DUPLICOLLECTION;
1509                                                 }
1510                                                 break;
1511                                         case MAKE_LINKS_MODIFIERS:
1512                                                 BKE_object_link_modifiers(scene, ob_dst, ob_src);
1513                                                 DEG_id_tag_update(&ob_dst->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY | ID_RECALC_ANIMATION);
1514                                                 break;
1515                                         case MAKE_LINKS_FONTS:
1516                                         {
1517                                                 Curve *cu_src = ob_src->data;
1518                                                 Curve *cu_dst = ob_dst->data;
1519
1520                                                 if (ID_IS_LINKED(obdata_id)) {
1521                                                         is_lib = true;
1522                                                         break;
1523                                                 }
1524
1525                                                 if (cu_dst->vfont)
1526                                                         id_us_min(&cu_dst->vfont->id);
1527                                                 cu_dst->vfont = cu_src->vfont;
1528                                                 id_us_plus((ID *)cu_dst->vfont);
1529                                                 if (cu_dst->vfontb)
1530                                                         id_us_min(&cu_dst->vfontb->id);
1531                                                 cu_dst->vfontb = cu_src->vfontb;
1532                                                 id_us_plus((ID *)cu_dst->vfontb);
1533                                                 if (cu_dst->vfonti)
1534                                                         id_us_min(&cu_dst->vfonti->id);
1535                                                 cu_dst->vfonti = cu_src->vfonti;
1536                                                 id_us_plus((ID *)cu_dst->vfonti);
1537                                                 if (cu_dst->vfontbi)
1538                                                         id_us_min(&cu_dst->vfontbi->id);
1539                                                 cu_dst->vfontbi = cu_src->vfontbi;
1540                                                 id_us_plus((ID *)cu_dst->vfontbi);
1541
1542                                                 DEG_id_tag_update(&ob_dst->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY | ID_RECALC_ANIMATION);
1543                                                 break;
1544                                         }
1545                                 }
1546                         }
1547                 }
1548         }
1549         CTX_DATA_END;
1550
1551         if (type == MAKE_LINKS_GROUP) {
1552                 if (ob_collections) {
1553                         BLI_linklist_free(ob_collections, NULL);
1554                 }
1555
1556                 if (is_cycle) {
1557                         BKE_report(op->reports, RPT_WARNING, "Skipped some collections because of cycle detected");
1558                 }
1559         }
1560
1561         if (is_lib) {
1562                 BKE_report(op->reports, RPT_WARNING, "Skipped editing library object data");
1563         }
1564
1565         DEG_relations_tag_update(bmain);
1566         WM_event_add_notifier(C, NC_SPACE | ND_SPACE_VIEW3D, CTX_wm_view3d(C));
1567         WM_event_add_notifier(C, NC_ANIMATION | ND_NLA_ACTCHANGE, CTX_wm_view3d(C));
1568         WM_event_add_notifier(C, NC_OBJECT, NULL);
1569
1570         return OPERATOR_FINISHED;
1571 }
1572
1573
1574 void OBJECT_OT_make_links_scene(wmOperatorType *ot)
1575 {
1576         PropertyRNA *prop;
1577
1578         /* identifiers */
1579         ot->name = "Link Objects to Scene";
1580         ot->description = "Link selection to another scene";
1581         ot->idname = "OBJECT_OT_make_links_scene";
1582
1583         /* api callbacks */
1584         ot->invoke = WM_enum_search_invoke;
1585         ot->exec = make_links_scene_exec;
1586         /* better not run the poll check */
1587
1588         /* flags */
1589         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1590
1591         /* properties */
1592         prop = RNA_def_enum(ot->srna, "scene", DummyRNA_NULL_items, 0, "Scene", "");
1593         RNA_def_enum_funcs(prop, RNA_scene_local_itemf);
1594         RNA_def_property_flag(prop, PROP_ENUM_NO_TRANSLATE);
1595         ot->prop = prop;
1596 }
1597
1598 void OBJECT_OT_make_links_data(wmOperatorType *ot)
1599 {
1600         static const EnumPropertyItem make_links_items[] = {
1601                 {MAKE_LINKS_OBDATA,     "OBDATA", 0, "Object Data", ""},
1602                 {MAKE_LINKS_MATERIALS,  "MATERIAL", 0, "Materials", ""},
1603                 {MAKE_LINKS_ANIMDATA,   "ANIMATION", 0, "Animation Data", ""},
1604                 {MAKE_LINKS_GROUP,      "GROUPS", 0, "Group", ""},
1605                 {MAKE_LINKS_DUPLICOLLECTION, "DUPLICOLLECTION", 0, "DupliGroup", ""},
1606                 {MAKE_LINKS_MODIFIERS,  "MODIFIERS", 0, "Modifiers", ""},
1607                 {MAKE_LINKS_FONTS,      "FONTS", 0, "Fonts", ""},
1608                 {0, NULL, 0, NULL, NULL}};
1609
1610         /* identifiers */
1611         ot->name = "Link Data";
1612         ot->description = "Apply active object links to other selected objects";
1613         ot->idname = "OBJECT_OT_make_links_data";
1614
1615         /* api callbacks */
1616         ot->exec = make_links_data_exec;
1617         ot->poll = ED_operator_object_active;
1618
1619         /* flags */
1620         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1621
1622         /* properties */
1623         ot->prop = RNA_def_enum(ot->srna, "type", make_links_items, 0, "Type", "");
1624 }
1625
1626
1627 /**************************** Make Single User ********************************/
1628
1629 static void libblock_relink_collection(Collection *collection)
1630 {
1631         BKE_libblock_relink_to_newid(&collection->id);
1632
1633         for (CollectionObject *cob = collection->gobject.first; cob != NULL; cob = cob->next) {
1634                 BKE_libblock_relink_to_newid(&cob->ob->id);
1635         }
1636
1637         for (CollectionChild *child = collection->children.first; child; child = child->next) {
1638                 libblock_relink_collection(child->collection);
1639         }
1640 }
1641
1642 static void single_object_users_collection(
1643         Main *bmain, Scene *scene, Collection *collection,
1644         const int flag, const bool copy_collections, const bool is_master_collection)
1645 {
1646         /* Generate new copies for objects in given collection and all its children,
1647          * and optionnaly also copy collections themselves. */
1648         if (copy_collections && !is_master_collection) {
1649                 collection = ID_NEW_SET(collection, BKE_collection_copy(bmain, NULL, collection));
1650         }
1651
1652         /* We do not remap to new objects here, this is done in separate step. */
1653         for (CollectionObject *cob = collection->gobject.first; cob; cob = cob->next) {
1654                 Object *ob = cob->ob;
1655                 /* an object may be in more than one collection */
1656                 if ((ob->id.newid == NULL) && ((ob->flag & flag) == flag)) {
1657                         if (!ID_IS_LINKED(ob) && ob->id.us > 1) {
1658                                 ID_NEW_SET(ob, BKE_object_copy(bmain, ob));
1659                         }
1660                 }
1661         }
1662
1663         for (CollectionChild *child = collection->children.first; child; child = child->next) {
1664                 single_object_users_collection(bmain, scene, child->collection, flag, copy_collections, false);
1665         }
1666 }
1667
1668 /* Warning, sets ID->newid pointers of objects and collections, but does not clear them. */
1669 static void single_object_users(Main *bmain, Scene *scene, View3D *v3d, const int flag, const bool copy_collections)
1670 {
1671         /* duplicate all the objects of the scene (and matching collections, if required). */
1672         Collection *master_collection = BKE_collection_master(scene);
1673         single_object_users_collection(bmain, scene, master_collection, flag, copy_collections, true);
1674
1675         /* duplicate collections that consist entirely of duplicated objects */
1676         /* XXX I guess that was designed for calls from 'make single user' operator... But since copy_collection is
1677          *     always false then, was not doing anything. And that kind of behavior should be added at operator level,
1678          *     not in a utility function also used by rather different code... */
1679 #if 0
1680         if (copy_collections) {
1681                 Collection *collection, *collectionn;
1682                 for (collection = bmain->collection.first; collection; collection = collection->id.next) {
1683                         bool all_duplicated = true;
1684                         bool any_duplicated = false;
1685
1686                         for (CollectionObject *cob = collection->gobject.first; cob; cob = cob->next) {
1687                                 any_duplicated = true;
1688                                 if (cob->ob->id.newid == NULL) {
1689                                         all_duplicated = false;
1690                                         break;
1691                                 }
1692                         }
1693
1694                         if (any_duplicated && all_duplicated) {
1695                                 // TODO: test if this works, with child collections ..
1696                                 collectionn = ID_NEW_SET(collection, BKE_collection_copy(bmain, NULL, collection));
1697
1698                                 for (CollectionObject *cob = collectionn->gobject.first; cob; cob = cob->next) {
1699                                         cob->ob = (Object *)cob->ob->id.newid;
1700                                 }
1701                         }
1702                 }
1703         }
1704 #endif
1705
1706         /* Collection and object pointers in collections */
1707         libblock_relink_collection(master_collection);
1708
1709         /* collection pointers in scene */
1710         BKE_scene_groups_relink(scene);
1711
1712         /* active camera */
1713         ID_NEW_REMAP(scene->camera);
1714         if (v3d) ID_NEW_REMAP(v3d->camera);
1715
1716         BKE_scene_collection_sync(scene);
1717 }
1718
1719 /* not an especially efficient function, only added so the single user
1720  * button can be functional.*/
1721 void ED_object_single_user(Main *bmain, Scene *scene, Object *ob)
1722 {
1723         FOREACH_SCENE_OBJECT_BEGIN(scene, ob_iter)
1724         {
1725                 ob_iter->flag &= ~OB_DONE;
1726         }
1727         FOREACH_SCENE_OBJECT_END;
1728
1729         /* tag only the one object */
1730         ob->flag |= OB_DONE;
1731
1732         single_object_users(bmain, scene, NULL, OB_DONE, false);
1733         BKE_main_id_clear_newpoins(bmain);
1734 }
1735
1736 static void new_id_matar(Main *bmain, Material **matar, const int totcol)
1737 {
1738         ID *id;
1739         int a;
1740
1741         for (a = 0; a < totcol; a++) {
1742                 id = (ID *)matar[a];
1743                 if (id && !ID_IS_LINKED(id)) {
1744                         if (id->newid) {
1745                                 matar[a] = (Material *)id->newid;
1746                                 id_us_plus(id->newid);
1747                                 id_us_min(id);
1748                         }
1749                         else if (id->us > 1) {
1750                                 matar[a] = ID_NEW_SET(id, BKE_material_copy(bmain, matar[a]));
1751                                 id_us_min(id);
1752                         }
1753                 }
1754         }
1755 }
1756
1757 static void single_obdata_users(Main *bmain, Scene *scene, ViewLayer *view_layer, View3D *v3d, const int flag)
1758 {
1759         Lamp *la;
1760         Curve *cu;
1761         /* Camera *cam; */
1762         Mesh *me;
1763         Lattice *lat;
1764         ID *id;
1765
1766         FOREACH_OBJECT_FLAG_BEGIN(scene, view_layer, v3d, flag, ob)
1767         {
1768                 if (!ID_IS_LINKED(ob)) {
1769                         id = ob->data;
1770
1771                         if (id && id->us > 1 && !ID_IS_LINKED(id)) {
1772                                 DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY);
1773
1774                                 switch (ob->type) {
1775                                         case OB_LAMP:
1776                                                 ob->data = la = ID_NEW_SET(ob->data, BKE_lamp_copy(bmain, ob->data));
1777                                                 break;
1778                                         case OB_CAMERA:
1779                                                 ob->data = ID_NEW_SET(ob->data, BKE_camera_copy(bmain, ob->data));
1780                                                 break;
1781                                         case OB_MESH:
1782                                                 /* Needed to remap texcomesh below. */
1783                                                 me = ob->data = ID_NEW_SET(ob->data, BKE_mesh_copy(bmain, ob->data));
1784                                                 if (me->key)  /* We do not need to set me->key->id.newid here... */
1785                                                         BKE_animdata_copy_id_action(bmain, (ID *)me->key, false);
1786                                                 break;
1787                                         case OB_MBALL:
1788                                                 ob->data = ID_NEW_SET(ob->data, BKE_mball_copy(bmain, ob->data));
1789                                                 break;
1790                                         case OB_CURVE:
1791                                         case OB_SURF:
1792                                         case OB_FONT:
1793                                                 ob->data = cu = ID_NEW_SET(ob->data, BKE_curve_copy(bmain, ob->data));
1794                                                 ID_NEW_REMAP(cu->bevobj);
1795                                                 ID_NEW_REMAP(cu->taperobj);
1796                                                 if (cu->key)  /* We do not need to set cu->key->id.newid here... */
1797                                                         BKE_animdata_copy_id_action(bmain, (ID *)cu->key, false);
1798                                                 break;
1799                                         case OB_LATTICE:
1800                                                 ob->data = lat = ID_NEW_SET(ob->data, BKE_lattice_copy(bmain, ob->data));
1801                                                 if (lat->key)  /* We do not need to set lat->key->id.newid here... */
1802                                                         BKE_animdata_copy_id_action(bmain, (ID *)lat->key, false);
1803                                                 break;
1804                                         case OB_ARMATURE:
1805                                                 DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY);
1806                                                 ob->data = ID_NEW_SET(ob->data, BKE_armature_copy(bmain, ob->data));
1807                                                 BKE_pose_rebuild(bmain, ob, ob->data, true);
1808                                                 break;
1809                                         case OB_SPEAKER:
1810                                                 ob->data = ID_NEW_SET(ob->data, BKE_speaker_copy(bmain, ob->data));
1811                                                 break;
1812                                         case OB_LIGHTPROBE:
1813                                                 ob->data = ID_NEW_SET(ob->data, BKE_lightprobe_copy(bmain, ob->data));
1814                                                 break;
1815                                         case OB_GPENCIL:
1816                                                 ob->data = ID_NEW_SET(ob->data, BKE_gpencil_copy(bmain, ob->data));
1817                                                 break;
1818                                         default:
1819                                                 printf("ERROR %s: can't copy %s\n", __func__, id->name);
1820                                                 BLI_assert(!"This should never happen.");
1821
1822                                                 /* We need to end the FOREACH_OBJECT_FLAG_BEGIN iterator to prevent memory leak. */
1823                                                 BKE_scene_objects_iterator_end(&iter_macro);
1824                                                 return;
1825                                 }
1826
1827                                 /* Copy animation data after object data became local,
1828                                  * otherwise old and new object data will share the same
1829                                  * AnimData structure, which is not what we want.
1830                                  *                                             (sergey)
1831                                  */
1832                                 BKE_animdata_copy_id_action(bmain, (ID *)ob->data, false);
1833
1834                                 id_us_min(id);
1835                         }
1836                 }
1837         }
1838         FOREACH_OBJECT_FLAG_END;
1839
1840         me = bmain->mesh.first;
1841         while (me) {
1842                 ID_NEW_REMAP(me->texcomesh);
1843                 me = me->id.next;
1844         }
1845 }
1846
1847 static void single_object_action_users(Main *bmain, Scene *scene, ViewLayer *view_layer, View3D *v3d, const int flag)
1848 {
1849         FOREACH_OBJECT_FLAG_BEGIN(scene, view_layer, v3d, flag, ob)
1850         {
1851                 if (!ID_IS_LINKED(ob)) {
1852                         DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY);
1853                         BKE_animdata_copy_id_action(bmain, &ob->id, false);
1854                 }
1855         }
1856         FOREACH_OBJECT_FLAG_END;
1857 }
1858
1859 static void single_mat_users(Main *bmain, Scene *scene, ViewLayer *view_layer, View3D *v3d, const int flag)
1860 {
1861         Material *ma, *man;
1862         int a;
1863
1864         FOREACH_OBJECT_FLAG_BEGIN(scene, view_layer, v3d, flag, ob)
1865         {
1866                 if (!ID_IS_LINKED(ob)) {
1867                         for (a = 1; a <= ob->totcol; a++) {
1868                                 ma = give_current_material(ob, a);
1869                                 if (ma) {
1870                                         /* do not test for LIB_TAG_NEW or use newid: this functions guaranteed delivers single_users! */
1871
1872                                         if (ma->id.us > 1) {
1873                                                 man = BKE_material_copy(bmain, ma);
1874                                                 BKE_animdata_copy_id_action(bmain, &man->id, false);
1875
1876                                                 man->id.us = 0;
1877                                                 assign_material(bmain, ob, man, a, BKE_MAT_ASSIGN_USERPREF);
1878                                         }
1879                                 }
1880                         }
1881                 }
1882         }
1883         FOREACH_OBJECT_FLAG_END;
1884 }
1885
1886 static void single_mat_users_expand(Main *bmain)
1887 {
1888         /* only when 'parent' blocks are LIB_TAG_NEW */
1889         Object *ob;
1890         Mesh *me;
1891         Curve *cu;
1892         MetaBall *mb;
1893         bGPdata *gpd;
1894
1895         for (ob = bmain->object.first; ob; ob = ob->id.next)
1896                 if (ob->id.tag & LIB_TAG_NEW)
1897                         new_id_matar(bmain, ob->mat, ob->totcol);
1898
1899         for (me = bmain->mesh.first; me; me = me->id.next)
1900                 if (me->id.tag & LIB_TAG_NEW)
1901                         new_id_matar(bmain, me->mat, me->totcol);
1902
1903         for (cu = bmain->curve.first; cu; cu = cu->id.next)
1904                 if (cu->id.tag & LIB_TAG_NEW)
1905                         new_id_matar(bmain, cu->mat, cu->totcol);
1906
1907         for (mb = bmain->mball.first; mb; mb = mb->id.next)
1908                 if (mb->id.tag & LIB_TAG_NEW)
1909                         new_id_matar(bmain, mb->mat, mb->totcol);
1910
1911         for (gpd = bmain->gpencil.first; gpd; gpd = gpd->id.next)
1912                 if (gpd->id.tag & LIB_TAG_NEW)
1913                         new_id_matar(bmain, gpd->mat, gpd->totcol);
1914 }
1915
1916 /* used for copying scenes */
1917 void ED_object_single_users(Main *bmain, Scene *scene, const bool full, const bool copy_collections)
1918 {
1919         single_object_users(bmain, scene, NULL, 0, copy_collections);
1920
1921         if (full) {
1922                 single_obdata_users(bmain, scene, NULL, NULL, 0);
1923                 single_object_action_users(bmain, scene, NULL, NULL, 0);
1924                 single_mat_users_expand(bmain);
1925         }
1926
1927         /* Relink nodetrees' pointers that have been duplicated. */
1928         FOREACH_NODETREE_BEGIN(bmain, ntree, id)
1929         {
1930                 /* This is a bit convoluted, we want to root ntree of copied IDs and only those,
1931                  * so we first check that old ID has been copied and that ntree is root tree of old ID,
1932                  * then get root tree of new ID and remap its pointers to new ID... */
1933                 if (id->newid && (&ntree->id != id)) {
1934                         ntree = ntreeFromID(id->newid);
1935                         BKE_libblock_relink_to_newid(&ntree->id);
1936                 }
1937         } FOREACH_NODETREE_END;
1938
1939         /* Relink datablock pointer properties */
1940         {
1941                 IDP_RelinkProperty(scene->id.properties);
1942
1943                 FOREACH_SCENE_OBJECT_BEGIN(scene, ob)
1944                 {
1945                         if (!ID_IS_LINKED(ob)) {
1946                                 IDP_RelinkProperty(ob->id.properties);
1947                         }
1948                 }
1949                 FOREACH_SCENE_OBJECT_END;
1950
1951                 if (scene->nodetree) {
1952                         IDP_RelinkProperty(scene->nodetree->id.properties);
1953                         for (bNode *node = scene->nodetree->nodes.first; node; node = node->next) {
1954                                 IDP_RelinkProperty(node->prop);
1955                         }
1956                 }
1957
1958                 if (scene->world) {
1959                         IDP_RelinkProperty(scene->world->id.properties);
1960                 }
1961
1962                 if (scene->clip) {
1963                         IDP_RelinkProperty(scene->clip->id.properties);
1964                 }
1965         }
1966         BKE_main_id_clear_newpoins(bmain);
1967         DEG_relations_tag_update(bmain);
1968 }
1969
1970 /******************************* Make Local ***********************************/
1971
1972 enum {
1973         MAKE_LOCAL_SELECT_OB              = 1,
1974         MAKE_LOCAL_SELECT_OBDATA          = 2,
1975         MAKE_LOCAL_SELECT_OBDATA_MATERIAL = 3,
1976         MAKE_LOCAL_ALL                    = 4,
1977 };
1978
1979 static int tag_localizable_looper(
1980         void *UNUSED(user_data), ID *UNUSED(self_id), ID **id_pointer, const int UNUSED(cb_flag))
1981 {
1982         if (*id_pointer) {
1983                 (*id_pointer)->tag &= ~LIB_TAG_DOIT;
1984         }
1985
1986         return IDWALK_RET_NOP;
1987 }
1988
1989 static void tag_localizable_objects(bContext *C, const int mode)
1990 {
1991         Main *bmain = CTX_data_main(C);
1992
1993         BKE_main_id_tag_all(bmain, LIB_TAG_DOIT, false);
1994
1995         /* Set LIB_TAG_DOIT flag for all selected objects, so next we can check whether
1996          * object is gonna to become local or not.
1997          */
1998         CTX_DATA_BEGIN (C, Object *, object, selected_objects)
1999         {
2000                 object->id.tag |= LIB_TAG_DOIT;
2001
2002                 /* If data is also gonna to become local, mark data we're interested in
2003                  * as gonna-to-be-local.
2004                  */
2005                 if (mode == MAKE_LOCAL_SELECT_OBDATA && object->data) {
2006                         ID *data_id = (ID *) object->data;
2007                         data_id->tag |= LIB_TAG_DOIT;
2008                 }
2009         }
2010         CTX_DATA_END;
2011
2012         /* Also forbid making objects local if other library objects are using
2013          * them for modifiers or constraints.
2014          */
2015         for (Object *object = bmain->object.first; object; object = object->id.next) {
2016                 if ((object->id.tag & LIB_TAG_DOIT) == 0) {
2017                         BKE_library_foreach_ID_link(NULL, &object->id, tag_localizable_looper, NULL, IDWALK_READONLY);
2018                 }
2019                 if (object->data) {
2020                         ID *data_id = (ID *) object->data;
2021                         if ((data_id->tag & LIB_TAG_DOIT) == 0) {
2022                                 BKE_library_foreach_ID_link(NULL, data_id, tag_localizable_looper, NULL, IDWALK_READONLY);
2023                         }
2024                 }
2025         }
2026
2027         /* TODO(sergey): Drivers targets? */
2028 }
2029
2030 /**
2031  * Instance indirectly referenced zero user objects,
2032  * otherwise they're lost on reload, see T40595.
2033  */
2034 static bool make_local_all__instance_indirect_unused(Main *bmain, ViewLayer *view_layer, Collection *collection)
2035 {
2036         Object *ob;
2037         bool changed = false;
2038
2039         for (ob = bmain->object.first; ob; ob = ob->id.next) {
2040                 if (ID_IS_LINKED(ob) && (ob->id.us == 0)) {
2041                         Base *base;
2042
2043                         id_us_plus(&ob->id);
2044
2045                         BKE_collection_object_add(bmain, collection, ob);
2046                         base = BKE_view_layer_base_find(view_layer, ob);
2047                         base->flag |= BASE_SELECTED;
2048                         BKE_scene_object_base_flag_sync_from_base(base);
2049                         DEG_id_tag_update(&ob->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY | ID_RECALC_ANIMATION);
2050
2051                         changed = true;
2052                 }
2053         }
2054
2055         return changed;
2056 }
2057
2058 static void make_local_animdata_tag_strips(ListBase *strips)
2059 {
2060         NlaStrip *strip;
2061
2062         for (strip = strips->first; strip; strip = strip->next) {
2063                 if (strip->act) {
2064                         strip->act->id.tag &= ~LIB_TAG_PRE_EXISTING;
2065                 }
2066
2067                 make_local_animdata_tag_strips(&strip->strips);
2068         }
2069 }
2070
2071 /* Tag all actions used by given animdata to be made local. */
2072 static void make_local_animdata_tag(AnimData *adt)
2073 {
2074         if (adt) {
2075                 /* Actions - Active and Temp */
2076                 if (adt->action) {
2077                         adt->action->id.tag &= ~LIB_TAG_PRE_EXISTING;
2078                 }
2079                 if (adt->tmpact) {
2080                         adt->tmpact->id.tag &= ~LIB_TAG_PRE_EXISTING;
2081                 }
2082
2083                 /* Drivers */
2084                 /* TODO: need to handle the ID-targets too? */
2085
2086                 /* NLA Data */
2087                 for (NlaTrack *nlt = adt->nla_tracks.first; nlt; nlt = nlt->next) {
2088                         make_local_animdata_tag_strips(&nlt->strips);
2089                 }
2090         }
2091 }
2092
2093 static void make_local_material_tag(Material *ma)
2094 {
2095         if (ma) {
2096                 ma->id.tag &= ~LIB_TAG_PRE_EXISTING;
2097                 make_local_animdata_tag(BKE_animdata_from_id(&ma->id));
2098
2099                 /* About nodetrees: root one is made local together with material, others we keep linked for now... */
2100         }
2101 }
2102
2103 static int make_local_exec(bContext *C, wmOperator *op)
2104 {
2105         Main *bmain = CTX_data_main(C);
2106         ParticleSystem *psys;
2107         Material *ma, ***matarar;
2108         const int mode = RNA_enum_get(op->ptr, "type");
2109         int a;
2110
2111         /* Note: we (ab)use LIB_TAG_PRE_EXISTING to cherry pick which ID to make local... */
2112         if (mode == MAKE_LOCAL_ALL) {
2113                 ViewLayer *view_layer = CTX_data_view_layer(C);
2114                 Collection *collection = CTX_data_collection(C);
2115
2116                 BKE_main_id_tag_all(bmain, LIB_TAG_PRE_EXISTING, false);
2117
2118                 /* De-select so the user can differentiate newly instanced from existing objects. */
2119                 BKE_view_layer_base_deselect_all(view_layer);
2120
2121                 if (make_local_all__instance_indirect_unused(bmain, view_layer, collection)) {
2122                         BKE_report(op->reports, RPT_INFO, "Orphan library objects added to the current scene to avoid loss");
2123                 }
2124         }
2125         else {
2126                 BKE_main_id_tag_all(bmain, LIB_TAG_PRE_EXISTING, true);
2127                 tag_localizable_objects(C, mode);
2128
2129                 CTX_DATA_BEGIN (C, Object *, ob, selected_objects)
2130                 {
2131                         if ((ob->id.tag & LIB_TAG_DOIT) == 0) {
2132                                 continue;
2133                         }
2134
2135                         ob->id.tag &= ~LIB_TAG_PRE_EXISTING;
2136                         make_local_animdata_tag(BKE_animdata_from_id(&ob->id));
2137                         for (psys = ob->particlesystem.first; psys; psys = psys->next) {
2138                                 psys->part->id.tag &= ~LIB_TAG_PRE_EXISTING;
2139                         }
2140
2141                         if (mode == MAKE_LOCAL_SELECT_OBDATA_MATERIAL) {
2142                                 for (a = 0; a < ob->totcol; a++) {
2143                                         ma = ob->mat[a];
2144                                         if (ma) {
2145                                                 make_local_material_tag(ma);
2146                                         }
2147                                 }
2148
2149                                 matarar = (Material ***)give_matarar(ob);
2150                                 if (matarar) {
2151                                         for (a = 0; a < ob->totcol; a++) {
2152                                                 ma = (*matarar)[a];
2153                                                 if (ma) {
2154                                                         make_local_material_tag(ma);
2155                                                 }
2156                                         }
2157                                 }
2158                         }
2159
2160                         if (ELEM(mode, MAKE_LOCAL_SELECT_OBDATA, MAKE_LOCAL_SELECT_OBDATA_MATERIAL) && ob->data != NULL) {
2161                                 ID *ob_data = ob->data;
2162                                 ob_data->tag &= ~LIB_TAG_PRE_EXISTING;
2163                                 make_local_animdata_tag(BKE_animdata_from_id(ob_data));
2164                         }
2165                 }
2166                 CTX_DATA_END;
2167         }
2168
2169         BKE_library_make_local(bmain, NULL, NULL, true, false); /* NULL is all libs */
2170
2171         WM_event_add_notifier(C, NC_WINDOW, NULL);
2172         return OPERATOR_FINISHED;
2173 }
2174
2175 void OBJECT_OT_make_local(wmOperatorType *ot)
2176 {
2177         static const EnumPropertyItem type_items[] = {
2178                 {MAKE_LOCAL_SELECT_OB, "SELECT_OBJECT", 0, "Selected Objects", ""},
2179                 {MAKE_LOCAL_SELECT_OBDATA, "SELECT_OBDATA", 0, "Selected Objects and Data", ""},
2180                 {MAKE_LOCAL_SELECT_OBDATA_MATERIAL, "SELECT_OBDATA_MATERIAL", 0, "Selected Objects, Data and Materials", ""},
2181                 {MAKE_LOCAL_ALL, "ALL", 0, "All", ""},
2182                 {0, NULL, 0, NULL, NULL}
2183         };
2184
2185         /* identifiers */
2186         ot->name = "Make Local";
2187         ot->description = "Make library linked data-blocks local to this file";
2188         ot->idname = "OBJECT_OT_make_local";
2189
2190         /* api callbacks */
2191         ot->invoke = WM_menu_invoke;
2192         ot->exec = make_local_exec;
2193         ot->poll = ED_operator_objectmode;
2194
2195         /* flags */
2196         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2197
2198         /* properties */
2199         ot->prop = RNA_def_enum(ot->srna, "type", type_items, 0, "Type", "");
2200 }
2201
2202
2203 static void make_override_static_tag_object(Object *obact, Object *ob)
2204 {
2205         if (ob == obact) {
2206                 return;
2207         }
2208
2209         if (!ID_IS_LINKED(ob)) {
2210                 return;
2211         }
2212
2213         /* Note: all this is very case-by-case bad handling, ultimately we'll want a real full 'automatic', generic
2214          * handling of all this, will probably require adding some override-aware stuff to library_query code... */
2215
2216         if (obact->type == OB_ARMATURE && ob->modifiers.first != NULL) {
2217                 for (ModifierData *md = ob->modifiers.first; md != NULL; md = md->next) {
2218                         if (md->type == eModifierType_Armature) {
2219                                 ArmatureModifierData *amd = (ArmatureModifierData *)md;
2220                                 if (amd->object == obact) {
2221                                         ob->id.tag |= LIB_TAG_DOIT;
2222                                         break;
2223                                 }
2224                         }
2225                 }
2226         }
2227         else if (ob->parent == obact) {
2228                 ob->id.tag |= LIB_TAG_DOIT;
2229         }
2230
2231         if (ob->id.tag & LIB_TAG_DOIT) {
2232                 printf("Indirectly overriding %s for %s\n", ob->id.name, obact->id.name);
2233         }
2234 }
2235
2236 static void make_override_static_tag_collections(Collection *collection)
2237 {
2238         collection->id.tag |= LIB_TAG_DOIT;
2239         for (CollectionChild *coll_child = collection->children.first; coll_child != NULL; coll_child = coll_child->next) {
2240                 make_override_static_tag_collections(coll_child->collection);
2241         }
2242 }
2243
2244 /* Set the object to override. */
2245 static int make_override_static_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2246 {
2247         Scene *scene = CTX_data_scene(C);
2248         Object *obact = ED_object_active_context(C);
2249
2250         /* Sanity checks. */
2251         if (!scene || ID_IS_LINKED(scene) || !obact) {
2252                 return OPERATOR_CANCELLED;
2253         }
2254
2255         /* Get object to work on - use a menu if we need to... */
2256         if (!ID_IS_LINKED(obact) && obact->dup_group != NULL && ID_IS_LINKED(obact->dup_group)) {
2257                 /* Gives menu with list of objects in group. */
2258                 WM_enum_search_invoke(C, op, event);
2259                 return OPERATOR_CANCELLED;
2260         }
2261         else if (ID_IS_LINKED(obact)) {
2262                 uiPopupMenu *pup = UI_popup_menu_begin(C, IFACE_("OK?"), ICON_QUESTION);
2263                 uiLayout *layout = UI_popup_menu_layout(pup);
2264
2265                 /* Create operator menu item with relevant properties filled in. */
2266                 PointerRNA opptr_dummy;
2267                 uiItemFullO_ptr(layout, op->type, op->type->name, ICON_NONE, NULL,
2268                                 WM_OP_EXEC_REGION_WIN, 0, &opptr_dummy);
2269
2270                 /* Present the menu and be done... */
2271                 UI_popup_menu_end(C, pup);
2272
2273                 /* This invoke just calls another instance of this operator... */
2274                 return OPERATOR_INTERFACE;
2275         }
2276         else {
2277                 /* Error.. cannot continue. */
2278                 BKE_report(op->reports, RPT_ERROR, "Can only make static override for a referenced object or collection");
2279                 return OPERATOR_CANCELLED;
2280         }
2281
2282 }
2283
2284 static int make_override_static_exec(bContext *C, wmOperator *op)
2285 {
2286         Main *bmain = CTX_data_main(C);
2287         Object *obact = CTX_data_active_object(C);
2288
2289         bool success = false;
2290
2291         if (!ID_IS_LINKED(obact) && obact->dup_group != NULL && ID_IS_LINKED(obact->dup_group)) {
2292                 Object *obcollection = obact;
2293                 Collection *collection = obcollection->dup_group;
2294
2295                 const ListBase dup_collection_objects = BKE_collection_object_cache_get(collection);
2296                 Base *base = BLI_findlink(&dup_collection_objects, RNA_enum_get(op->ptr, "object"));
2297                 obact = base->object;
2298
2299                 /* First, we make a static override of the linked collection itself, and all its children. */
2300                 make_override_static_tag_collections(collection);
2301
2302                 /* Then, we make static override of the whole set of objects in the Collection. */
2303                 FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(collection, ob)
2304                 {
2305                         ob->id.tag |= LIB_TAG_DOIT;
2306                 }
2307                 FOREACH_COLLECTION_OBJECT_RECURSIVE_END;
2308
2309                 /* Then, we remove (untag) bone shape objects, you shall never want to override those (hopefully)... */
2310                 FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(collection, ob)
2311                 {
2312                         if (ob->type == OB_ARMATURE && ob->pose != NULL) {
2313                                 for (bPoseChannel *pchan = ob->pose->chanbase.first; pchan != NULL; pchan = pchan->next) {
2314                                         if (pchan->custom != NULL) {
2315                                                 pchan->custom->id.tag &= ~ LIB_TAG_DOIT;
2316                                         }
2317                                 }
2318                         }
2319                 }
2320                 FOREACH_COLLECTION_OBJECT_RECURSIVE_END;
2321
2322                 success = BKE_override_static_create_from_tag(bmain);
2323
2324                 /* Instantiate our newly overridden objects in scene, if not yet done. */
2325                 Scene *scene = CTX_data_scene(C);
2326                 ViewLayer *view_layer = CTX_data_view_layer(C);
2327                 Collection *new_collection = (Collection *)collection->id.newid;
2328
2329                 BKE_collection_child_add(bmain, scene->master_collection, new_collection);
2330                 FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(new_collection, new_ob)
2331                 {
2332                         if (new_ob != NULL && new_ob->id.override_static != NULL) {
2333                                 if ((base = BKE_view_layer_base_find(view_layer, new_ob)) == NULL) {
2334                                         BKE_collection_object_add_from(bmain, scene, obcollection, new_ob);
2335                                         base = BKE_view_layer_base_find(view_layer, new_ob);
2336                                         DEG_id_tag_update_ex(bmain, &new_ob->id, ID_RECALC_TRANSFORM | ID_RECALC_BASE_FLAGS);
2337                                 }
2338                                 /* parent to 'collection' empty */
2339                                 if (new_ob->parent == NULL) {
2340                                         new_ob->parent = obcollection;
2341                                 }
2342                                 if (new_ob == (Object *)obact->id.newid) {
2343                                         /* TODO: is setting active needed? */
2344                                         BKE_view_layer_base_select_and_set_active(view_layer, base);
2345                                 }
2346                                 else {
2347                                         /* Disable auto-override tags for non-active objects, will help with performaces... */
2348                                         new_ob->id.override_static->flag &= ~STATICOVERRIDE_AUTO;
2349                                 }
2350                                 /* We still want to store all objects' current override status (i.e. change of parent). */
2351                                 BKE_override_static_operations_create(bmain, &new_ob->id, true);
2352                         }
2353                 }
2354                 FOREACH_COLLECTION_OBJECT_RECURSIVE_END;
2355
2356                 /* obcollection is no more duplicollection-ing, it merely parents whole collection of overriding instantiated objects. */
2357                 obcollection->dup_group = NULL;
2358
2359                 /* Also, we'd likely want to lock by default things like transformations of implicitly overridden objects? */
2360
2361                 DEG_id_tag_update(&scene->id, 0);
2362
2363                 /* Cleanup. */
2364                 BKE_main_id_clear_newpoins(bmain);
2365                 BKE_main_id_tag_listbase(&bmain->object, LIB_TAG_DOIT, false);
2366         }
2367         /* Else, poll func ensures us that ID_IS_LINKED(obact) is true. */
2368         else if (obact->type == OB_ARMATURE) {
2369                 BKE_main_id_tag_all(bmain, LIB_TAG_DOIT, false);
2370
2371                 obact->id.tag |= LIB_TAG_DOIT;
2372
2373                 for (Object *ob = bmain->object.first; ob != NULL; ob = ob->id.next) {
2374                         make_override_static_tag_object(obact, ob);
2375                 }
2376
2377                 success = BKE_override_static_create_from_tag(bmain);
2378
2379                 /* Also, we'd likely want to lock by default things like transformations of implicitly overridden objects? */
2380
2381                 /* Cleanup. */
2382                 BKE_main_id_clear_newpoins(bmain);
2383                 BKE_main_id_tag_listbase(&bmain->object, LIB_TAG_DOIT, false);
2384         }
2385         /* TODO: probably more cases where we want to do automated smart things in the future! */
2386         else {
2387                 success = (BKE_override_static_create_from_id(bmain, &obact->id) != NULL);
2388         }
2389
2390         WM_event_add_notifier(C, NC_WINDOW, NULL);
2391
2392         return success ? OPERATOR_FINISHED : OPERATOR_CANCELLED;
2393 }
2394
2395 static bool make_override_static_poll(bContext *C)
2396 {
2397         Object *obact = CTX_data_active_object(C);
2398
2399         /* Object must be directly linked to be overridable. */
2400         return (BKE_override_static_is_enabled() &&
2401                 ED_operator_objectmode(C) && obact != NULL &&
2402                 ((ID_IS_LINKED(obact) && obact->id.tag & LIB_TAG_EXTERN) ||
2403                  (!ID_IS_LINKED(obact) && obact->dup_group != NULL && ID_IS_LINKED(obact->dup_group))));
2404 }
2405
2406 void OBJECT_OT_make_override_static(wmOperatorType *ot)
2407 {
2408         /* identifiers */
2409         ot->name = "Make Static Override";
2410         ot->description = "Make local override of this library linked data-block";
2411         ot->idname = "OBJECT_OT_make_override_static";
2412
2413         /* api callbacks */
2414         ot->invoke = make_override_static_invoke;
2415         ot->exec = make_override_static_exec;
2416         ot->poll = make_override_static_poll;
2417
2418         /* flags */
2419         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2420
2421         /* properties */
2422         PropertyRNA *prop;
2423         prop = RNA_def_enum(ot->srna, "object", DummyRNA_DEFAULT_items, 0, "Override Object",
2424                             "Name of lib-linked/collection object to make an override from");
2425         RNA_def_enum_funcs(prop, proxy_collection_object_itemf);
2426         RNA_def_property_flag(prop, PROP_ENUM_NO_TRANSLATE);
2427         ot->prop = prop;
2428 }
2429
2430 enum {
2431         MAKE_SINGLE_USER_ALL      = 1,
2432         MAKE_SINGLE_USER_SELECTED = 2,
2433 };
2434
2435 static int make_single_user_exec(bContext *C, wmOperator *op)
2436 {
2437         Main *bmain = CTX_data_main(C);
2438         Scene *scene = CTX_data_scene(C);
2439         ViewLayer *view_layer = CTX_data_view_layer(C);
2440         View3D *v3d = CTX_wm_view3d(C); /* ok if this is NULL */
2441         const int flag = (RNA_enum_get(op->ptr, "type") == MAKE_SINGLE_USER_SELECTED) ? SELECT : 0;
2442         const bool copy_collections = false;
2443         bool update_deps = false;
2444
2445         if (RNA_boolean_get(op->ptr, "object")) {
2446                 if (flag == SELECT) {
2447                         BKE_view_layer_selected_objects_tag(view_layer, OB_DONE);
2448                         single_object_users(bmain, scene, v3d, OB_DONE, copy_collections);
2449                 }
2450                 else {
2451                         single_object_users(bmain, scene, v3d, 0, copy_collections);
2452                 }
2453
2454                 /* needed since object relationships may have changed */
2455                 update_deps = true;
2456         }
2457
2458         if (RNA_boolean_get(op->ptr, "obdata")) {
2459                 single_obdata_users(bmain, scene, view_layer, v3d, flag);
2460         }
2461
2462         if (RNA_boolean_get(op->ptr, "material")) {
2463                 single_mat_users(bmain, scene, view_layer, v3d, flag);
2464         }
2465
2466         if (RNA_boolean_get(op->ptr, "animation")) {
2467                 single_object_action_users(bmain, scene, view_layer, v3d, flag);
2468         }
2469
2470         BKE_main_id_clear_newpoins(bmain);
2471
2472         WM_event_add_notifier(C, NC_WINDOW, NULL);
2473
2474         if (update_deps) {
2475                 DEG_relations_tag_update(bmain);
2476         }
2477
2478         return OPERATOR_FINISHED;
2479 }
2480
2481 void OBJECT_OT_make_single_user(wmOperatorType *ot)
2482 {
2483         static const EnumPropertyItem type_items[] = {
2484                 {MAKE_SINGLE_USER_SELECTED, "SELECTED_OBJECTS", 0, "Selected Objects", ""},
2485                 {MAKE_SINGLE_USER_ALL, "ALL", 0, "All", ""},
2486                 {0, NULL, 0, NULL, NULL}};
2487
2488         /* identifiers */
2489         ot->name = "Make Single User";
2490         ot->description = "Make linked data local to each object";
2491         ot->idname = "OBJECT_OT_make_single_user";
2492
2493         /* api callbacks */
2494         ot->invoke = WM_menu_invoke;
2495         ot->exec = make_single_user_exec;
2496         ot->poll = ED_operator_objectmode;
2497
2498         /* flags */
2499         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2500
2501         /* properties */
2502         ot->prop = RNA_def_enum(ot->srna, "type", type_items, MAKE_SINGLE_USER_SELECTED, "Type", "");
2503
2504         RNA_def_boolean(ot->srna, "object", 0, "Object", "Make single user objects");
2505         RNA_def_boolean(ot->srna, "obdata", 0, "Object Data", "Make single user object data");
2506         RNA_def_boolean(ot->srna, "material", 0, "Materials", "Make materials local to each data-block");
2507         RNA_def_boolean(ot->srna, "animation", 0, "Object Animation", "Make animation data local to each object");
2508 }
2509
2510 static int drop_named_material_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2511 {
2512         Main *bmain = CTX_data_main(C);
2513         Base *base = ED_view3d_give_base_under_cursor(C, event->mval);
2514         Material *ma;
2515         char name[MAX_ID_NAME - 2];
2516
2517         RNA_string_get(op->ptr, "name", name);
2518         ma = (Material *)BKE_libblock_find_name(bmain, ID_MA, name);
2519         if (base == NULL || ma == NULL)
2520                 return OPERATOR_CANCELLED;
2521
2522         assign_material(CTX_data_main(C), base->object, ma, 1, BKE_MAT_ASSIGN_USERPREF);
2523
2524         DEG_id_tag_update(&base->object->id, ID_RECALC_TRANSFORM);
2525
2526         WM_event_add_notifier(C, NC_OBJECT | ND_OB_SHADING, base->object);
2527         WM_event_add_notifier(C, NC_SPACE | ND_SPACE_VIEW3D, CTX_wm_view3d(C));
2528         WM_event_add_notifier(C, NC_MATERIAL | ND_SHADING_LINKS, ma);
2529
2530         return OPERATOR_FINISHED;
2531 }
2532
2533 /* used for dropbox */
2534 /* assigns to object under cursor, only first material slot */
2535 void OBJECT_OT_drop_named_material(wmOperatorType *ot)
2536 {
2537         /* identifiers */
2538         ot->name = "Drop Named Material on Object";
2539         ot->idname = "OBJECT_OT_drop_named_material";
2540
2541         /* api callbacks */
2542         ot->invoke = drop_named_material_invoke;
2543         ot->poll = ED_operator_objectmode;
2544
2545         /* flags */
2546         ot->flag = OPTYPE_UNDO | OPTYPE_INTERNAL;
2547
2548         /* properties */
2549         RNA_def_string(ot->srna, "name", "Material", MAX_ID_NAME - 2, "Name", "Material name to assign");
2550 }
2551
2552 static int object_unlink_data_exec(bContext *C, wmOperator *op)
2553 {
2554         ID *id;
2555         PropertyPointerRNA pprop;
2556
2557         UI_context_active_but_prop_get_templateID(C, &pprop.ptr, &pprop.prop);
2558
2559         if (pprop.prop == NULL) {
2560                 BKE_report(op->reports, RPT_ERROR, "Incorrect context for running object data unlink");
2561                 return OPERATOR_CANCELLED;
2562         }
2563
2564         id = pprop.ptr.id.data;
2565
2566         if (GS(id->name) == ID_OB) {
2567                 Object *ob = (Object *)id;
2568                 if (ob->data) {
2569                         ID *id_data = ob->data;
2570
2571                         if (GS(id_data->name) == ID_IM) {
2572                                 id_us_min(id_data);
2573                                 ob->data = NULL;
2574                         }
2575                         else {
2576                                 BKE_report(op->reports, RPT_ERROR, "Can't unlink this object data");
2577                                 return OPERATOR_CANCELLED;
2578                         }
2579                 }
2580         }
2581
2582         RNA_property_update(C, &pprop.ptr, pprop.prop);
2583
2584         return OPERATOR_FINISHED;
2585 }
2586
2587 /**
2588  * \note Only for empty-image objects, this operator is needed
2589  */
2590 void OBJECT_OT_unlink_data(wmOperatorType *ot)
2591 {
2592         /* identifiers */
2593         ot->name = "Unlink";
2594         ot->idname = "OBJECT_OT_unlink_data";
2595
2596         /* api callbacks */
2597         ot->exec = object_unlink_data_exec;
2598
2599         /* flags */
2600         ot->flag = OPTYPE_INTERNAL;
2601 }