324b6eca34ae92bd8089df7439cac8e8e46df9e7
[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_constraint_types.h"
41 #include "DNA_group_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_global.h"
73 #include "BKE_fcurve.h"
74 #include "BKE_idprop.h"
75 #include "BKE_lamp.h"
76 #include "BKE_lattice.h"
77 #include "BKE_layer.h"
78 #include "BKE_library.h"
79 #include "BKE_library_override.h"
80 #include "BKE_library_query.h"
81 #include "BKE_library_remap.h"
82 #include "BKE_lightprobe.h"
83 #include "BKE_main.h"
84 #include "BKE_material.h"
85 #include "BKE_mball.h"
86 #include "BKE_mesh.h"
87 #include "BKE_modifier.h"
88 #include "BKE_node.h"
89 #include "BKE_object.h"
90 #include "BKE_report.h"
91 #include "BKE_scene.h"
92 #include "BKE_speaker.h"
93 #include "BKE_texture.h"
94 #include "BKE_editmesh.h"
95
96 #include "DEG_depsgraph.h"
97 #include "DEG_depsgraph_build.h"
98
99 #include "WM_api.h"
100 #include "WM_types.h"
101
102 #include "UI_interface.h"
103 #include "UI_resources.h"
104
105 #include "RNA_access.h"
106 #include "RNA_define.h"
107 #include "RNA_enum_types.h"
108
109 #include "ED_armature.h"
110 #include "ED_curve.h"
111 #include "ED_keyframing.h"
112 #include "ED_object.h"
113 #include "ED_mesh.h"
114 #include "ED_screen.h"
115 #include "ED_view3d.h"
116
117 #include "object_intern.h"
118
119 /*********************** Make Vertex Parent Operator ************************/
120
121 static bool vertex_parent_set_poll(bContext *C)
122 {
123         return ED_operator_editmesh(C) || ED_operator_editsurfcurve(C) || ED_operator_editlattice(C);
124 }
125
126 static int vertex_parent_set_exec(bContext *C, wmOperator *op)
127 {
128         Main *bmain = CTX_data_main(C);
129         Scene *scene = CTX_data_scene(C);
130         Depsgraph *depsgraph = CTX_data_depsgraph(C);
131         ViewLayer *view_layer = CTX_data_view_layer(C);
132         Object *obedit = CTX_data_edit_object(C);
133         BMVert *eve;
134         BMIter iter;
135         Curve *cu;
136         Nurb *nu;
137         BezTriple *bezt;
138         BPoint *bp;
139         Object *par;
140         int a, v1 = 0, v2 = 0, v3 = 0, v4 = 0, nr = 1;
141
142         /* we need 1 to 3 selected vertices */
143
144         if (obedit->type == OB_MESH) {
145                 Mesh *me = obedit->data;
146                 BMEditMesh *em;
147
148                 EDBM_mesh_load(bmain, obedit);
149                 EDBM_mesh_make(obedit, scene->toolsettings->selectmode, true);
150
151                 DEG_id_tag_update(obedit->data, 0);
152
153                 em = me->edit_btmesh;
154
155                 EDBM_mesh_normals_update(em);
156                 BKE_editmesh_tessface_calc(em);
157
158                 /* derivedMesh might be needed for solving parenting,
159                  * so re-create it here */
160                 makeDerivedMesh(depsgraph, scene, obedit, em, CD_MASK_BAREMESH | CD_MASK_ORIGINDEX, false);
161
162                 BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
163                         if (BM_elem_flag_test(eve, BM_ELEM_SELECT)) {
164                                 if (v1 == 0) v1 = nr;
165                                 else if (v2 == 0) v2 = nr;
166                                 else if (v3 == 0) v3 = nr;
167                                 else if (v4 == 0) v4 = nr;
168                                 else break;
169                         }
170                         nr++;
171                 }
172         }
173         else if (ELEM(obedit->type, OB_SURF, OB_CURVE)) {
174                 ListBase *editnurb = object_editcurve_get(obedit);
175
176                 cu = obedit->data;
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(cu, 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, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
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(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, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
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, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
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, OB_RECALC_OB);
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, 0);  /* 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(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->curve_cache && par->curve_cache->path == NULL) {
720                                                                         DEG_id_tag_update(&par->id, OB_RECALC_DATA);
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 {
800                                 /* calculate inverse parent matrix */
801                                 BKE_object_workob_calc_parent(depsgraph, scene, ob, &workob);
802                                 invert_m4_m4(ob->parentinv, workob.obmat);
803                         }
804
805                         DEG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA);
806                 }
807         }
808
809         return true;
810 }
811
812
813
814 static void parent_set_vert_find(KDTree *tree, Object *child, int vert_par[3], bool is_tri)
815 {
816         const float *co_find = child->obmat[3];
817         if (is_tri) {
818                 KDTreeNearest nearest[3];
819                 int tot;
820
821                 tot = BLI_kdtree_find_nearest_n(tree, co_find, nearest, 3);
822                 BLI_assert(tot == 3);
823                 UNUSED_VARS(tot);
824
825                 vert_par[0] = nearest[0].index;
826                 vert_par[1] = nearest[1].index;
827                 vert_par[2] = nearest[2].index;
828
829                 BLI_assert(min_iii(UNPACK3(vert_par)) >= 0);
830         }
831         else {
832                 vert_par[0] = BLI_kdtree_find_nearest(tree, co_find, NULL);
833                 BLI_assert(vert_par[0] >= 0);
834                 vert_par[1] = 0;
835                 vert_par[2] = 0;
836         }
837 }
838
839 static int parent_set_exec(bContext *C, wmOperator *op)
840 {
841         Main *bmain = CTX_data_main(C);
842         Scene *scene = CTX_data_scene(C);
843         Object *par = ED_object_active_context(C);
844         int partype = RNA_enum_get(op->ptr, "type");
845         const bool xmirror = RNA_boolean_get(op->ptr, "xmirror");
846         const bool keep_transform = RNA_boolean_get(op->ptr, "keep_transform");
847         bool ok = true;
848
849         /* vertex parent (kdtree) */
850         const bool is_vert_par = ELEM(partype, PAR_VERTEX, PAR_VERTEX_TRI);
851         const bool is_tri = partype == PAR_VERTEX_TRI;
852         int tree_tot;
853         struct KDTree *tree = NULL;
854         int vert_par[3] = {0, 0, 0};
855         const int *vert_par_p = is_vert_par ? vert_par : NULL;
856
857
858         if (is_vert_par) {
859                 tree = BKE_object_as_kdtree(par, &tree_tot);
860                 BLI_assert(tree != NULL);
861
862                 if (tree_tot < (is_tri ? 3 : 1)) {
863                         BKE_report(op->reports, RPT_ERROR, "Not enough vertices for vertex-parent");
864                         ok = false;
865                 }
866         }
867
868         if (ok) {
869                 /* Non vertex-parent */
870                 CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
871                 {
872                         if (is_vert_par) {
873                                 parent_set_vert_find(tree, ob, vert_par, is_tri);
874                         }
875
876                         if (!ED_object_parent_set(op->reports, C, scene, ob, par, partype, xmirror, keep_transform, vert_par_p)) {
877                                 ok = false;
878                                 break;
879                         }
880                 }
881                 CTX_DATA_END;
882         }
883
884         if (is_vert_par) {
885                 BLI_kdtree_free(tree);
886         }
887
888         if (!ok)
889                 return OPERATOR_CANCELLED;
890
891         DEG_relations_tag_update(bmain);
892         WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL);
893         WM_event_add_notifier(C, NC_OBJECT | ND_PARENT, NULL);
894
895         return OPERATOR_FINISHED;
896 }
897
898
899 static int parent_set_invoke(bContext *C, wmOperator *UNUSED(op), const wmEvent *UNUSED(event))
900 {
901         Object *ob = ED_object_active_context(C);
902         uiPopupMenu *pup = UI_popup_menu_begin(C, IFACE_("Set Parent To"), ICON_NONE);
903         uiLayout *layout = UI_popup_menu_layout(pup);
904
905         wmOperatorType *ot = WM_operatortype_find("OBJECT_OT_parent_set", true);
906         PointerRNA opptr;
907
908 #if 0
909         uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_OBJECT);
910 #else
911         uiItemFullO_ptr(layout, ot, IFACE_("Object"), ICON_NONE, NULL, WM_OP_EXEC_DEFAULT, 0, &opptr);
912         RNA_enum_set(&opptr, "type", PAR_OBJECT);
913         RNA_boolean_set(&opptr, "keep_transform", false);
914
915         uiItemFullO_ptr(
916                 layout, ot, IFACE_("Object (Keep Transform)"), ICON_NONE,
917                 NULL, WM_OP_EXEC_DEFAULT, 0, &opptr);
918         RNA_enum_set(&opptr, "type", PAR_OBJECT);
919         RNA_boolean_set(&opptr, "keep_transform", true);
920 #endif
921         /* ob becomes parent, make the associated menus */
922         if (ob->type == OB_ARMATURE) {
923                 uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_ARMATURE);
924                 uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_ARMATURE_NAME);
925                 uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_ARMATURE_ENVELOPE);
926                 uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_ARMATURE_AUTO);
927                 uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_BONE);
928                 uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_BONE_RELATIVE);
929         }
930         else if (ob->type == OB_CURVE) {
931                 uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_CURVE);
932                 uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_FOLLOW);
933                 uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_PATH_CONST);
934         }
935         else if (ob->type == OB_LATTICE) {
936                 uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_LATTICE);
937         }
938
939         /* vertex parenting */
940         if (OB_TYPE_SUPPORT_PARVERT(ob->type)) {
941                 uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_VERTEX);
942                 uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_VERTEX_TRI);
943         }
944
945         UI_popup_menu_end(C, pup);
946
947         return OPERATOR_INTERFACE;
948 }
949
950 static bool parent_set_draw_check_prop(PointerRNA *ptr, PropertyRNA *prop)
951 {
952         const char *prop_id = RNA_property_identifier(prop);
953         const int type = RNA_enum_get(ptr, "type");
954
955         /* Only show XMirror for PAR_ARMATURE_ENVELOPE and PAR_ARMATURE_AUTO! */
956         if (STREQ(prop_id, "xmirror")) {
957                 if (ELEM(type, PAR_ARMATURE_ENVELOPE, PAR_ARMATURE_AUTO))
958                         return true;
959                 else
960                         return false;
961         }
962
963         return true;
964 }
965
966 static void parent_set_ui(bContext *C, wmOperator *op)
967 {
968         uiLayout *layout = op->layout;
969         wmWindowManager *wm = CTX_wm_manager(C);
970         PointerRNA ptr;
971
972         RNA_pointer_create(&wm->id, op->type->srna, op->properties, &ptr);
973
974         /* Main auto-draw call. */
975         uiDefAutoButsRNA(layout, &ptr, parent_set_draw_check_prop, UI_BUT_LABEL_ALIGN_NONE, false);
976 }
977
978 void OBJECT_OT_parent_set(wmOperatorType *ot)
979 {
980         /* identifiers */
981         ot->name = "Make Parent";
982         ot->description = "Set the object's parenting";
983         ot->idname = "OBJECT_OT_parent_set";
984
985         /* api callbacks */
986         ot->invoke = parent_set_invoke;
987         ot->exec = parent_set_exec;
988         ot->poll = ED_operator_object_active;
989         ot->ui = parent_set_ui;
990
991         /* flags */
992         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
993
994         ot->prop = RNA_def_enum(ot->srna, "type", prop_make_parent_types, 0, "Type", "");
995         RNA_def_boolean(ot->srna, "xmirror", false, "X Mirror",
996                         "Apply weights symmetrically along X axis, for Envelope/Automatic vertex groups creation");
997         RNA_def_boolean(ot->srna, "keep_transform", false, "Keep Transform",
998                         "Apply transformation before parenting");
999 }
1000
1001 /* ************ Make Parent Without Inverse Operator ******************* */
1002
1003 static int parent_noinv_set_exec(bContext *C, wmOperator *op)
1004 {
1005         Main *bmain = CTX_data_main(C);
1006         Object *par = ED_object_active_context(C);
1007
1008         DEG_id_tag_update(&par->id, OB_RECALC_OB);
1009
1010         /* context iterator */
1011         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
1012         {
1013                 if (ob != par) {
1014                         if (BKE_object_parent_loop_check(par, ob)) {
1015                                 BKE_report(op->reports, RPT_ERROR, "Loop in parents");
1016                         }
1017                         else {
1018                                 /* clear inverse matrix and also the object location */
1019                                 unit_m4(ob->parentinv);
1020                                 memset(ob->loc, 0, 3 * sizeof(float));
1021
1022                                 /* set recalc flags */
1023                                 DEG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA);
1024
1025                                 /* set parenting type for object - object only... */
1026                                 ob->parent = par;
1027                                 ob->partype = PAROBJECT; /* note, dna define, not operator property */
1028                         }
1029                 }
1030         }
1031         CTX_DATA_END;
1032
1033         DEG_relations_tag_update(bmain);
1034         WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL);
1035
1036         return OPERATOR_FINISHED;
1037 }
1038
1039 void OBJECT_OT_parent_no_inverse_set(wmOperatorType *ot)
1040 {
1041         /* identifiers */
1042         ot->name = "Make Parent without Inverse";
1043         ot->description = "Set the object's parenting without setting the inverse parent correction";
1044         ot->idname = "OBJECT_OT_parent_no_inverse_set";
1045
1046         /* api callbacks */
1047         ot->invoke = WM_operator_confirm;
1048         ot->exec = parent_noinv_set_exec;
1049         ot->poll = ED_operator_object_active_editable;
1050
1051         /* flags */
1052         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1053 }
1054
1055 /************************ Clear Slow Parent Operator *********************/
1056
1057 static int object_slow_parent_clear_exec(bContext *C, wmOperator *UNUSED(op))
1058 {
1059         Depsgraph *depsgraph = CTX_data_depsgraph(C);
1060         Scene *scene = CTX_data_scene(C);
1061
1062         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
1063         {
1064                 if (ob->parent) {
1065                         if (ob->partype & PARSLOW) {
1066                                 ob->partype -= PARSLOW;
1067                                 BKE_object_where_is_calc(depsgraph, scene, ob);
1068                                 ob->partype |= PARSLOW;
1069                                 DEG_id_tag_update(&ob->id, OB_RECALC_OB);
1070                         }
1071                 }
1072         }
1073         CTX_DATA_END;
1074
1075         WM_event_add_notifier(C, NC_SCENE, scene);
1076
1077         return OPERATOR_FINISHED;
1078 }
1079
1080 void OBJECT_OT_slow_parent_clear(wmOperatorType *ot)
1081 {
1082         /* identifiers */
1083         ot->name = "Clear Slow Parent";
1084         ot->description = "Clear the object's slow parent";
1085         ot->idname = "OBJECT_OT_slow_parent_clear";
1086
1087         /* api callbacks */
1088         ot->invoke = WM_operator_confirm;
1089         ot->exec = object_slow_parent_clear_exec;
1090         ot->poll = ED_operator_view3d_active;
1091
1092         /* flags */
1093         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1094 }
1095
1096 /********************** Make Slow Parent Operator *********************/
1097
1098 static int object_slow_parent_set_exec(bContext *C, wmOperator *UNUSED(op))
1099 {
1100         Scene *scene = CTX_data_scene(C);
1101
1102         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
1103         {
1104                 if (ob->parent)
1105                         ob->partype |= PARSLOW;
1106
1107                 DEG_id_tag_update(&ob->id, OB_RECALC_OB);
1108         }
1109         CTX_DATA_END;
1110
1111         WM_event_add_notifier(C, NC_SCENE, scene);
1112
1113         return OPERATOR_FINISHED;
1114 }
1115
1116 void OBJECT_OT_slow_parent_set(wmOperatorType *ot)
1117 {
1118         /* identifiers */
1119         ot->name = "Set Slow Parent";
1120         ot->description = "Set the object's slow parent";
1121         ot->idname = "OBJECT_OT_slow_parent_set";
1122
1123         /* api callbacks */
1124         ot->invoke = WM_operator_confirm;
1125         ot->exec = object_slow_parent_set_exec;
1126         ot->poll = ED_operator_view3d_active;
1127
1128         /* flags */
1129         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1130 }
1131
1132 /* ******************** Clear Track Operator ******************* */
1133
1134 enum {
1135         CLEAR_TRACK                = 1,
1136         CLEAR_TRACK_KEEP_TRANSFORM = 2,
1137 };
1138
1139 static const EnumPropertyItem prop_clear_track_types[] = {
1140         {CLEAR_TRACK, "CLEAR", 0, "Clear Track", ""},
1141         {CLEAR_TRACK_KEEP_TRANSFORM, "CLEAR_KEEP_TRANSFORM", 0, "Clear and Keep Transformation (Clear Track)", ""},
1142         {0, NULL, 0, NULL, NULL}
1143 };
1144
1145 /* note, poll should check for editable scene */
1146 static int object_track_clear_exec(bContext *C, wmOperator *op)
1147 {
1148         Main *bmain = CTX_data_main(C);
1149         const int type = RNA_enum_get(op->ptr, "type");
1150
1151         if (CTX_data_edit_object(C)) {
1152                 BKE_report(op->reports, RPT_ERROR, "Operation cannot be performed in edit mode");
1153                 return OPERATOR_CANCELLED;
1154         }
1155         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
1156         {
1157                 bConstraint *con, *pcon;
1158
1159                 /* remove track-object for old track */
1160                 ob->track = NULL;
1161                 DEG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
1162
1163                 /* also remove all tracking constraints */
1164                 for (con = ob->constraints.last; con; con = pcon) {
1165                         pcon = con->prev;
1166                         if (ELEM(con->type, CONSTRAINT_TYPE_TRACKTO, CONSTRAINT_TYPE_LOCKTRACK, CONSTRAINT_TYPE_DAMPTRACK))
1167                                 BKE_constraint_remove(&ob->constraints, con);
1168                 }
1169
1170                 if (type == CLEAR_TRACK_KEEP_TRANSFORM)
1171                         BKE_object_apply_mat4(ob, ob->obmat, true, true);
1172         }
1173         CTX_DATA_END;
1174
1175         DEG_relations_tag_update(bmain);
1176         WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL);
1177
1178         return OPERATOR_FINISHED;
1179 }
1180
1181 void OBJECT_OT_track_clear(wmOperatorType *ot)
1182 {
1183         /* identifiers */
1184         ot->name = "Clear Track";
1185         ot->description = "Clear tracking constraint or flag from object";
1186         ot->idname = "OBJECT_OT_track_clear";
1187
1188         /* api callbacks */
1189         ot->invoke = WM_menu_invoke;
1190         ot->exec = object_track_clear_exec;
1191
1192         ot->poll = ED_operator_objectmode;
1193
1194         /* flags */
1195         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1196
1197         ot->prop = RNA_def_enum(ot->srna, "type", prop_clear_track_types, 0, "Type", "");
1198 }
1199
1200 /************************** Make Track Operator *****************************/
1201
1202 enum {
1203         CREATE_TRACK_DAMPTRACK = 1,
1204         CREATE_TRACK_TRACKTO   = 2,
1205         CREATE_TRACK_LOCKTRACK = 3,
1206 };
1207
1208 static const EnumPropertyItem prop_make_track_types[] = {
1209         {CREATE_TRACK_DAMPTRACK, "DAMPTRACK", 0, "Damped Track Constraint", ""},
1210         {CREATE_TRACK_TRACKTO, "TRACKTO", 0, "Track To Constraint", ""},
1211         {CREATE_TRACK_LOCKTRACK, "LOCKTRACK", 0, "Lock Track Constraint", ""},
1212         {0, NULL, 0, NULL, NULL}
1213 };
1214
1215 static int track_set_exec(bContext *C, wmOperator *op)
1216 {
1217         Main *bmain = CTX_data_main(C);
1218         Object *obact = ED_object_active_context(C);
1219
1220         const int type = RNA_enum_get(op->ptr, "type");
1221
1222         switch (type) {
1223                 case CREATE_TRACK_DAMPTRACK:
1224                 {
1225                         bConstraint *con;
1226                         bDampTrackConstraint *data;
1227
1228                         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
1229                         {
1230                                 if (ob != obact) {
1231                                         con = BKE_constraint_add_for_object(ob, "AutoTrack", CONSTRAINT_TYPE_DAMPTRACK);
1232
1233                                         data = con->data;
1234                                         data->tar = obact;
1235                                         DEG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
1236
1237                                         /* Lamp, Camera and Speaker track differently by default */
1238                                         if (ELEM(ob->type, OB_LAMP, OB_CAMERA, OB_SPEAKER)) {
1239                                                 data->trackflag = TRACK_nZ;
1240                                         }
1241                                 }
1242                         }
1243                         CTX_DATA_END;
1244                         break;
1245                 }
1246                 case CREATE_TRACK_TRACKTO:
1247                 {
1248                         bConstraint *con;
1249                         bTrackToConstraint *data;
1250
1251                         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
1252                         {
1253                                 if (ob != obact) {
1254                                         con = BKE_constraint_add_for_object(ob, "AutoTrack", CONSTRAINT_TYPE_TRACKTO);
1255
1256                                         data = con->data;
1257                                         data->tar = obact;
1258                                         DEG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
1259
1260                                         /* Lamp, Camera and Speaker track differently by default */
1261                                         if (ELEM(ob->type, OB_LAMP, OB_CAMERA, OB_SPEAKER)) {
1262                                                 data->reserved1 = TRACK_nZ;
1263                                                 data->reserved2 = UP_Y;
1264                                         }
1265                                 }
1266                         }
1267                         CTX_DATA_END;
1268                         break;
1269                 }
1270                 case CREATE_TRACK_LOCKTRACK:
1271                 {
1272                         bConstraint *con;
1273                         bLockTrackConstraint *data;
1274
1275                         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
1276                         {
1277                                 if (ob != obact) {
1278                                         con = BKE_constraint_add_for_object(ob, "AutoTrack", CONSTRAINT_TYPE_LOCKTRACK);
1279
1280                                         data = con->data;
1281                                         data->tar = obact;
1282                                         DEG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
1283
1284                                         /* Lamp, Camera and Speaker track differently by default */
1285                                         if (ELEM(ob->type, OB_LAMP, OB_CAMERA, OB_SPEAKER)) {
1286                                                 data->trackflag = TRACK_nZ;
1287                                                 data->lockflag = LOCK_Y;
1288                                         }
1289                                 }
1290                         }
1291                         CTX_DATA_END;
1292                         break;
1293                 }
1294         }
1295
1296         DEG_relations_tag_update(bmain);
1297         WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL);
1298
1299         return OPERATOR_FINISHED;
1300 }
1301
1302 void OBJECT_OT_track_set(wmOperatorType *ot)
1303 {
1304         /* identifiers */
1305         ot->name = "Make Track";
1306         ot->description = "Make the object track another object, using various methods/constraints";
1307         ot->idname = "OBJECT_OT_track_set";
1308
1309         /* api callbacks */
1310         ot->invoke = WM_menu_invoke;
1311         ot->exec = track_set_exec;
1312
1313         ot->poll = ED_operator_objectmode;
1314
1315         /* flags */
1316         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1317
1318         /* properties */
1319         ot->prop = RNA_def_enum(ot->srna, "type", prop_make_track_types, 0, "Type", "");
1320 }
1321
1322 /************************** Link to Scene Operator *****************************/
1323
1324 #if 0
1325 static void link_to_scene(Main *UNUSED(bmain), unsigned short UNUSED(nr))
1326 {
1327         Scene *sce = (Scene *) BLI_findlink(&bmain->scene, G.curscreen->scenenr - 1);
1328         Base *base, *nbase;
1329
1330         if (sce == NULL) return;
1331         if (sce->id.lib) return;
1332
1333         for (base = FIRSTBASE; base; base = base->next) {
1334                 if (TESTBASE(v3d, base)) {
1335                         nbase = MEM_mallocN(sizeof(Base), "newbase");
1336                         *nbase = *base;
1337                         BLI_addhead(&(sce->base), nbase);
1338                         id_us_plus((ID *)base->object);
1339                 }
1340         }
1341 }
1342 #endif
1343
1344 static int make_links_scene_exec(bContext *C, wmOperator *op)
1345 {
1346         Main *bmain = CTX_data_main(C);
1347         Scene *scene_to = BLI_findlink(&bmain->scene, RNA_enum_get(op->ptr, "scene"));
1348
1349         if (scene_to == NULL) {
1350                 BKE_report(op->reports, RPT_ERROR, "Could not find scene");
1351                 return OPERATOR_CANCELLED;
1352         }
1353
1354         if (scene_to == CTX_data_scene(C)) {
1355                 BKE_report(op->reports, RPT_ERROR, "Cannot link objects into the same scene");
1356                 return OPERATOR_CANCELLED;
1357         }
1358
1359         if (ID_IS_LINKED(scene_to)) {
1360                 BKE_report(op->reports, RPT_ERROR, "Cannot link objects into a linked scene");
1361                 return OPERATOR_CANCELLED;
1362         }
1363
1364         Collection *collection_to = BKE_collection_master(scene_to);
1365         CTX_DATA_BEGIN (C, Base *, base, selected_bases)
1366         {
1367                 BKE_collection_object_add(bmain, collection_to, base->object);
1368         }
1369         CTX_DATA_END;
1370
1371         /* redraw the 3D view because the object center points are colored differently */
1372         WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, NULL);
1373
1374         /* one day multiple scenes will be visible, then we should have some update function for them */
1375         return OPERATOR_FINISHED;
1376 }
1377
1378 enum {
1379         MAKE_LINKS_OBDATA     = 1,
1380         MAKE_LINKS_MATERIALS  = 2,
1381         MAKE_LINKS_ANIMDATA   = 3,
1382         MAKE_LINKS_GROUP      = 4,
1383         MAKE_LINKS_DUPLICOLLECTION = 5,
1384         MAKE_LINKS_MODIFIERS  = 6,
1385         MAKE_LINKS_FONTS      = 7,
1386 };
1387
1388 /* Return true if make link data is allowed, false otherwise */
1389 static bool allow_make_links_data(const int type, Object *ob_src, Object *ob_dst)
1390 {
1391         switch (type) {
1392                 case MAKE_LINKS_OBDATA:
1393                         if (ob_src->type == ob_dst->type && ob_src->type != OB_EMPTY) {
1394                                 return true;
1395                         }
1396                         break;
1397                 case MAKE_LINKS_MATERIALS:
1398                         if (OB_TYPE_SUPPORT_MATERIAL(ob_src->type) && OB_TYPE_SUPPORT_MATERIAL(ob_dst->type)) {
1399                                 return true;
1400                         }
1401                         break;
1402                 case MAKE_LINKS_ANIMDATA:
1403                 case MAKE_LINKS_GROUP:
1404                 case MAKE_LINKS_DUPLICOLLECTION:
1405                         return true;
1406                 case MAKE_LINKS_MODIFIERS:
1407                         if (!ELEM(OB_EMPTY, ob_src->type, ob_dst->type)) {
1408                                 return true;
1409                         }
1410                         break;
1411                 case MAKE_LINKS_FONTS:
1412                         if ((ob_src->data != ob_dst->data) && (ob_src->type == OB_FONT) && (ob_dst->type == OB_FONT)) {
1413                                 return true;
1414                         }
1415                         break;
1416         }
1417         return false;
1418 }
1419
1420 static int make_links_data_exec(bContext *C, wmOperator *op)
1421 {
1422         Scene *scene = CTX_data_scene(C);
1423         Main *bmain = CTX_data_main(C);
1424         const int type = RNA_enum_get(op->ptr, "type");
1425         Object *ob_src;
1426         ID *obdata_id;
1427         int a;
1428
1429         /* collection */
1430         LinkNode *ob_collections = NULL;
1431         bool is_cycle = false;
1432         bool is_lib = false;
1433
1434         ob_src = ED_object_active_context(C);
1435
1436         /* avoid searching all collections in source object each time */
1437         if (type == MAKE_LINKS_GROUP) {
1438                 ob_collections = BKE_object_groups(bmain, ob_src);
1439         }
1440
1441         CTX_DATA_BEGIN (C, Base *, base_dst, selected_editable_bases)
1442         {
1443                 Object *ob_dst = base_dst->object;
1444
1445                 if (ob_src != ob_dst) {
1446                         if (allow_make_links_data(type, ob_src, ob_dst)) {
1447                                 obdata_id = ob_dst->data;
1448
1449                                 switch (type) {
1450                                         case MAKE_LINKS_OBDATA: /* obdata */
1451                                                 id_us_min(obdata_id);
1452
1453                                                 obdata_id = ob_src->data;
1454                                                 id_us_plus(obdata_id);
1455                                                 ob_dst->data = obdata_id;
1456
1457                                                 /* if amount of material indices changed: */
1458                                                 test_object_materials(bmain, ob_dst, ob_dst->data);
1459
1460                                                 DEG_id_tag_update(&ob_dst->id, OB_RECALC_DATA);
1461                                                 break;
1462                                         case MAKE_LINKS_MATERIALS:
1463                                                 /* new approach, using functions from kernel */
1464                                                 for (a = 0; a < ob_src->totcol; a++) {
1465                                                         Material *ma = give_current_material(ob_src, a + 1);
1466                                                         assign_material(bmain, ob_dst, ma, a + 1, BKE_MAT_ASSIGN_USERPREF); /* also works with ma==NULL */
1467                                                 }
1468                                                 DEG_id_tag_update(&ob_dst->id, OB_RECALC_DATA);
1469                                                 break;
1470                                         case MAKE_LINKS_ANIMDATA:
1471                                                 BKE_animdata_copy_id(bmain, (ID *)ob_dst, (ID *)ob_src, false, true);
1472                                                 if (ob_dst->data && ob_src->data) {
1473                                                         if (ID_IS_LINKED(obdata_id)) {
1474                                                                 is_lib = true;
1475                                                                 break;
1476                                                         }
1477                                                         BKE_animdata_copy_id(bmain, (ID *)ob_dst->data, (ID *)ob_src->data, false, true);
1478                                                 }
1479                                                 DEG_id_tag_update(&ob_dst->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
1480                                                 break;
1481                                         case MAKE_LINKS_GROUP:
1482                                         {
1483                                                 LinkNode *collection_node;
1484
1485                                                 /* first clear collections */
1486                                                 BKE_object_groups_clear(bmain, ob_dst);
1487
1488                                                 /* now add in the collections from the link nodes */
1489                                                 for (collection_node = ob_collections; collection_node; collection_node = collection_node->next) {
1490                                                         if (ob_dst->dup_group != collection_node->link) {
1491                                                                 BKE_collection_object_add(bmain, collection_node->link, ob_dst);
1492                                                         }
1493                                                         else {
1494                                                                 is_cycle = true;
1495                                                         }
1496                                                 }
1497                                                 break;
1498                                         }
1499                                         case MAKE_LINKS_DUPLICOLLECTION:
1500                                                 ob_dst->dup_group = ob_src->dup_group;
1501                                                 if (ob_dst->dup_group) {
1502                                                         id_us_plus(&ob_dst->dup_group->id);
1503                                                         ob_dst->transflag |= OB_DUPLICOLLECTION;
1504                                                 }
1505                                                 break;
1506                                         case MAKE_LINKS_MODIFIERS:
1507                                                 BKE_object_link_modifiers(scene, ob_dst, ob_src);
1508                                                 DEG_id_tag_update(&ob_dst->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
1509                                                 break;
1510                                         case MAKE_LINKS_FONTS:
1511                                         {
1512                                                 Curve *cu_src = ob_src->data;
1513                                                 Curve *cu_dst = ob_dst->data;
1514
1515                                                 if (ID_IS_LINKED(obdata_id)) {
1516                                                         is_lib = true;
1517                                                         break;
1518                                                 }
1519
1520                                                 if (cu_dst->vfont)
1521                                                         id_us_min(&cu_dst->vfont->id);
1522                                                 cu_dst->vfont = cu_src->vfont;
1523                                                 id_us_plus((ID *)cu_dst->vfont);
1524                                                 if (cu_dst->vfontb)
1525                                                         id_us_min(&cu_dst->vfontb->id);
1526                                                 cu_dst->vfontb = cu_src->vfontb;
1527                                                 id_us_plus((ID *)cu_dst->vfontb);
1528                                                 if (cu_dst->vfonti)
1529                                                         id_us_min(&cu_dst->vfonti->id);
1530                                                 cu_dst->vfonti = cu_src->vfonti;
1531                                                 id_us_plus((ID *)cu_dst->vfonti);
1532                                                 if (cu_dst->vfontbi)
1533                                                         id_us_min(&cu_dst->vfontbi->id);
1534                                                 cu_dst->vfontbi = cu_src->vfontbi;
1535                                                 id_us_plus((ID *)cu_dst->vfontbi);
1536
1537                                                 DEG_id_tag_update(&ob_dst->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
1538                                                 break;
1539                                         }
1540                                 }
1541                         }
1542                 }
1543         }
1544         CTX_DATA_END;
1545
1546         if (type == MAKE_LINKS_GROUP) {
1547                 if (ob_collections) {
1548                         BLI_linklist_free(ob_collections, NULL);
1549                 }
1550
1551                 if (is_cycle) {
1552                         BKE_report(op->reports, RPT_WARNING, "Skipped some collections because of cycle detected");
1553                 }
1554         }
1555
1556         if (is_lib) {
1557                 BKE_report(op->reports, RPT_WARNING, "Skipped editing library object data");
1558         }
1559
1560         DEG_relations_tag_update(bmain);
1561         WM_event_add_notifier(C, NC_SPACE | ND_SPACE_VIEW3D, CTX_wm_view3d(C));
1562         WM_event_add_notifier(C, NC_ANIMATION | ND_NLA_ACTCHANGE, CTX_wm_view3d(C));
1563         WM_event_add_notifier(C, NC_OBJECT, NULL);
1564
1565         return OPERATOR_FINISHED;
1566 }
1567
1568
1569 void OBJECT_OT_make_links_scene(wmOperatorType *ot)
1570 {
1571         PropertyRNA *prop;
1572
1573         /* identifiers */
1574         ot->name = "Link Objects to Scene";
1575         ot->description = "Link selection to another scene";
1576         ot->idname = "OBJECT_OT_make_links_scene";
1577
1578         /* api callbacks */
1579         ot->invoke = WM_enum_search_invoke;
1580         ot->exec = make_links_scene_exec;
1581         /* better not run the poll check */
1582
1583         /* flags */
1584         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1585
1586         /* properties */
1587         prop = RNA_def_enum(ot->srna, "scene", DummyRNA_NULL_items, 0, "Scene", "");
1588         RNA_def_enum_funcs(prop, RNA_scene_local_itemf);
1589         RNA_def_property_flag(prop, PROP_ENUM_NO_TRANSLATE);
1590         ot->prop = prop;
1591 }
1592
1593 void OBJECT_OT_make_links_data(wmOperatorType *ot)
1594 {
1595         static const EnumPropertyItem make_links_items[] = {
1596                 {MAKE_LINKS_OBDATA,     "OBDATA", 0, "Object Data", ""},
1597                 {MAKE_LINKS_MATERIALS,  "MATERIAL", 0, "Materials", ""},
1598                 {MAKE_LINKS_ANIMDATA,   "ANIMATION", 0, "Animation Data", ""},
1599                 {MAKE_LINKS_GROUP,      "GROUPS", 0, "Group", ""},
1600                 {MAKE_LINKS_DUPLICOLLECTION, "DUPLICOLLECTION", 0, "DupliGroup", ""},
1601                 {MAKE_LINKS_MODIFIERS,  "MODIFIERS", 0, "Modifiers", ""},
1602                 {MAKE_LINKS_FONTS,      "FONTS", 0, "Fonts", ""},
1603                 {0, NULL, 0, NULL, NULL}};
1604
1605         /* identifiers */
1606         ot->name = "Link Data";
1607         ot->description = "Apply active object links to other selected objects";
1608         ot->idname = "OBJECT_OT_make_links_data";
1609
1610         /* api callbacks */
1611         ot->exec = make_links_data_exec;
1612         ot->poll = ED_operator_object_active;
1613
1614         /* flags */
1615         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1616
1617         /* properties */
1618         ot->prop = RNA_def_enum(ot->srna, "type", make_links_items, 0, "Type", "");
1619 }
1620
1621
1622 /**************************** Make Single User ********************************/
1623
1624 static Object *single_object_users_object(Main *bmain, Scene *scene, Object *ob)
1625 {
1626         /* base gets copy of object */
1627         Object *obn = ID_NEW_SET(ob, BKE_object_copy(bmain, ob));
1628
1629         /* remap gpencil parenting */
1630
1631         if (scene->gpd) {
1632                 bGPdata *gpd = scene->gpd;
1633                 for (bGPDlayer *gpl = gpd->layers.first; gpl; gpl = gpl->next) {
1634                         if (gpl->parent == ob) {
1635                                 gpl->parent = obn;
1636                         }
1637                 }
1638         }
1639
1640         id_us_plus(&obn->id);
1641         id_us_min(&ob->id);
1642         return obn;
1643 }
1644
1645 static void libblock_relink_collection(Collection *collection)
1646 {
1647         for (CollectionObject *cob = collection->gobject.first; cob; cob = cob->next) {
1648                 BKE_libblock_relink_to_newid(&cob->ob->id);
1649         }
1650
1651         for (CollectionChild *child = collection->children.first; child; child = child->next) {
1652                 libblock_relink_collection(child->collection);
1653         }
1654 }
1655
1656 static void single_object_users_collection(Main *bmain, Scene *scene, Collection *collection, const int flag, const bool copy_collections)
1657 {
1658         for (CollectionObject *cob = collection->gobject.first; cob; cob = cob->next) {
1659                 Object *ob = cob->ob;
1660                 /* an object may be in more than one collection */
1661                 if ((ob->id.newid == NULL) && ((ob->flag & flag) == flag)) {
1662                         if (!ID_IS_LINKED(ob) && ob->id.us > 1) {
1663                                 cob->ob = single_object_users_object(bmain, scene, cob->ob);
1664                         }
1665                 }
1666         }
1667
1668         for (CollectionChild *child = collection->children.first; child; child = child->next) {
1669                 single_object_users_collection(bmain, scene, child->collection, flag, copy_collections);
1670         }
1671 }
1672
1673 /* Warning, sets ID->newid pointers of objects and collections, but does not clear them. */
1674 static void single_object_users(Main *bmain, Scene *scene, View3D *v3d, const int flag, const bool copy_collections)
1675 {
1676         Collection *collection, *collectionn;
1677
1678         /* duplicate all the objects of the scene */
1679         Collection *master_collection = BKE_collection_master(scene);
1680         single_object_users_collection(bmain, scene, master_collection, flag, copy_collections);
1681
1682         /* loop over ViewLayers and assign the pointers accordingly */
1683         for (ViewLayer *view_layer = scene->view_layers.first; view_layer; view_layer = view_layer->next) {
1684                 for (Base *base = view_layer->object_bases.first; base; base = base->next) {
1685                         ID_NEW_REMAP(base->object);
1686                 }
1687         }
1688
1689         /* duplicate collections that consist entirely of duplicated objects */
1690         for (collection = bmain->collection.first; collection; collection = collection->id.next) {
1691                 if (copy_collections) {
1692                         bool all_duplicated = true;
1693                         bool any_duplicated = false;
1694
1695                         for (CollectionObject *cob = collection->gobject.first; cob; cob = cob->next) {
1696                                 any_duplicated = true;
1697                                 if (cob->ob->id.newid == NULL) {
1698                                         all_duplicated = false;
1699                                         break;
1700                                 }
1701                         }
1702
1703                         if (any_duplicated && all_duplicated) {
1704                                 // TODO: test if this works, with child collections ..
1705                                 collectionn = ID_NEW_SET(collection, BKE_collection_copy(bmain, NULL, collection));
1706
1707                                 for (CollectionObject *cob = collectionn->gobject.first; cob; cob = cob->next) {
1708                                         cob->ob = (Object *)cob->ob->id.newid;
1709                                 }
1710                         }
1711                 }
1712         }
1713
1714         /* collection pointers in scene */
1715         BKE_scene_groups_relink(scene);
1716
1717         ID_NEW_REMAP(scene->camera);
1718         if (v3d) ID_NEW_REMAP(v3d->camera);
1719
1720         /* object and collection pointers */
1721         libblock_relink_collection(master_collection);
1722 }
1723
1724 /* not an especially efficient function, only added so the single user
1725  * button can be functional.*/
1726 void ED_object_single_user(Main *bmain, Scene *scene, Object *ob)
1727 {
1728         FOREACH_SCENE_OBJECT_BEGIN(scene, ob_iter)
1729         {
1730                 ob_iter->flag &= ~OB_DONE;
1731         }
1732         FOREACH_SCENE_OBJECT_END;
1733
1734         /* tag only the one object */
1735         ob->flag |= OB_DONE;
1736
1737         single_object_users(bmain, scene, NULL, OB_DONE, false);
1738         BKE_main_id_clear_newpoins(bmain);
1739 }
1740
1741 static void new_id_matar(Main *bmain, Material **matar, const int totcol)
1742 {
1743         ID *id;
1744         int a;
1745
1746         for (a = 0; a < totcol; a++) {
1747                 id = (ID *)matar[a];
1748                 if (id && !ID_IS_LINKED(id)) {
1749                         if (id->newid) {
1750                                 matar[a] = (Material *)id->newid;
1751                                 id_us_plus(id->newid);
1752                                 id_us_min(id);
1753                         }
1754                         else if (id->us > 1) {
1755                                 matar[a] = ID_NEW_SET(id, BKE_material_copy(bmain, matar[a]));
1756                                 id_us_min(id);
1757                         }
1758                 }
1759         }
1760 }
1761
1762 static void single_obdata_users(Main *bmain, Scene *scene, ViewLayer *view_layer, const int flag)
1763 {
1764         Lamp *la;
1765         Curve *cu;
1766         /* Camera *cam; */
1767         Mesh *me;
1768         Lattice *lat;
1769         ID *id;
1770
1771         FOREACH_OBJECT_FLAG_BEGIN(scene, view_layer, flag, ob)
1772         {
1773                 if (!ID_IS_LINKED(ob)) {
1774                         id = ob->data;
1775
1776                         if (id && id->us > 1 && !ID_IS_LINKED(id)) {
1777                                 DEG_id_tag_update(&ob->id, OB_RECALC_DATA);
1778
1779                                 switch (ob->type) {
1780                                         case OB_LAMP:
1781                                                 ob->data = la = ID_NEW_SET(ob->data, BKE_lamp_copy(bmain, ob->data));
1782                                                 break;
1783                                         case OB_CAMERA:
1784                                                 ob->data = ID_NEW_SET(ob->data, BKE_camera_copy(bmain, ob->data));
1785                                                 break;
1786                                         case OB_MESH:
1787                                                 /* Needed to remap texcomesh below. */
1788                                                 me = ob->data = ID_NEW_SET(ob->data, BKE_mesh_copy(bmain, ob->data));
1789                                                 if (me->key)  /* We do not need to set me->key->id.newid here... */
1790                                                         BKE_animdata_copy_id_action(bmain, (ID *)me->key, false);
1791                                                 break;
1792                                         case OB_MBALL:
1793                                                 ob->data = ID_NEW_SET(ob->data, BKE_mball_copy(bmain, ob->data));
1794                                                 break;
1795                                         case OB_CURVE:
1796                                         case OB_SURF:
1797                                         case OB_FONT:
1798                                                 ob->data = cu = ID_NEW_SET(ob->data, BKE_curve_copy(bmain, ob->data));
1799                                                 ID_NEW_REMAP(cu->bevobj);
1800                                                 ID_NEW_REMAP(cu->taperobj);
1801                                                 if (cu->key)  /* We do not need to set cu->key->id.newid here... */
1802                                                         BKE_animdata_copy_id_action(bmain, (ID *)cu->key, false);
1803                                                 break;
1804                                         case OB_LATTICE:
1805                                                 ob->data = lat = ID_NEW_SET(ob->data, BKE_lattice_copy(bmain, ob->data));
1806                                                 if (lat->key)  /* We do not need to set lat->key->id.newid here... */
1807                                                         BKE_animdata_copy_id_action(bmain, (ID *)lat->key, false);
1808                                                 break;
1809                                         case OB_ARMATURE:
1810                                                 DEG_id_tag_update(&ob->id, OB_RECALC_DATA);
1811                                                 ob->data = ID_NEW_SET(ob->data, BKE_armature_copy(bmain, ob->data));
1812                                                 BKE_pose_rebuild(ob, ob->data);
1813                                                 break;
1814                                         case OB_SPEAKER:
1815                                                 ob->data = ID_NEW_SET(ob->data, BKE_speaker_copy(bmain, ob->data));
1816                                                 break;
1817                                         case OB_LIGHTPROBE:
1818                                                 ob->data = ID_NEW_SET(ob->data, BKE_lightprobe_copy(bmain, ob->data));
1819                                                 break;
1820                                         default:
1821                                                 printf("ERROR %s: can't copy %s\n", __func__, id->name);
1822                                                 BLI_assert(!"This should never happen.");
1823
1824                                                 /* We need to end the FOREACH_OBJECT_FLAG_BEGIN iterator to prevent memory leak. */
1825                                                 BKE_scene_objects_iterator_end(&iter_macro);
1826                                                 return;
1827                                 }
1828
1829                                 /* Copy animation data after object data became local,
1830                                  * otherwise old and new object data will share the same
1831                                  * AnimData structure, which is not what we want.
1832                                  *                                             (sergey)
1833                                  */
1834                                 BKE_animdata_copy_id_action(bmain, (ID *)ob->data, false);
1835
1836                                 id_us_min(id);
1837                         }
1838                 }
1839         }
1840         FOREACH_OBJECT_FLAG_END;
1841
1842         me = bmain->mesh.first;
1843         while (me) {
1844                 ID_NEW_REMAP(me->texcomesh);
1845                 me = me->id.next;
1846         }
1847 }
1848
1849 static void single_object_action_users(Main *bmain, Scene *scene, ViewLayer *view_layer, const int flag)
1850 {
1851         FOREACH_OBJECT_FLAG_BEGIN(scene, view_layer, flag, ob)
1852         {
1853                 if (!ID_IS_LINKED(ob)) {
1854                         DEG_id_tag_update(&ob->id, OB_RECALC_DATA);
1855                         BKE_animdata_copy_id_action(bmain, &ob->id, false);
1856                 }
1857         }
1858         FOREACH_OBJECT_FLAG_END;
1859 }
1860
1861 static void single_mat_users(Main *bmain, Scene *scene, ViewLayer *view_layer, const int flag)
1862 {
1863         Material *ma, *man;
1864         int a;
1865
1866         FOREACH_OBJECT_FLAG_BEGIN(scene, view_layer, flag, ob)
1867         {
1868                 if (!ID_IS_LINKED(ob)) {
1869                         for (a = 1; a <= ob->totcol; a++) {
1870                                 ma = give_current_material(ob, a);
1871                                 if (ma) {
1872                                         /* do not test for LIB_TAG_NEW or use newid: this functions guaranteed delivers single_users! */
1873
1874                                         if (ma->id.us > 1) {
1875                                                 man = BKE_material_copy(bmain, ma);
1876                                                 BKE_animdata_copy_id_action(bmain, &man->id, false);
1877
1878                                                 man->id.us = 0;
1879                                                 assign_material(bmain, ob, man, a, BKE_MAT_ASSIGN_USERPREF);
1880                                         }
1881                                 }
1882                         }
1883                 }
1884         }
1885         FOREACH_OBJECT_FLAG_END;
1886 }
1887
1888 static void single_mat_users_expand(Main *bmain)
1889 {
1890         /* only when 'parent' blocks are LIB_TAG_NEW */
1891         Object *ob;
1892         Mesh *me;
1893         Curve *cu;
1894         MetaBall *mb;
1895
1896         for (ob = bmain->object.first; ob; ob = ob->id.next)
1897                 if (ob->id.tag & LIB_TAG_NEW)
1898                         new_id_matar(bmain, ob->mat, ob->totcol);
1899
1900         for (me = bmain->mesh.first; me; me = me->id.next)
1901                 if (me->id.tag & LIB_TAG_NEW)
1902                         new_id_matar(bmain, me->mat, me->totcol);
1903
1904         for (cu = bmain->curve.first; cu; cu = cu->id.next)
1905                 if (cu->id.tag & LIB_TAG_NEW)
1906                         new_id_matar(bmain, cu->mat, cu->totcol);
1907
1908         for (mb = bmain->mball.first; mb; mb = mb->id.next)
1909                 if (mb->id.tag & LIB_TAG_NEW)
1910                         new_id_matar(bmain, mb->mat, mb->totcol);
1911 }
1912
1913 /* used for copying scenes */
1914 void ED_object_single_users(Main *bmain, Scene *scene, const bool full, const bool copy_collections)
1915 {
1916         single_object_users(bmain, scene, NULL, 0, copy_collections);
1917
1918         if (full) {
1919                 single_obdata_users(bmain, scene, NULL, 0);
1920                 single_object_action_users(bmain, scene, NULL, 0);
1921                 single_mat_users_expand(bmain);
1922         }
1923
1924         /* Relink nodetrees' pointers that have been duplicated. */
1925         FOREACH_NODETREE(bmain, ntree, id)
1926         {
1927                 /* This is a bit convoluted, we want to root ntree of copied IDs and only those,
1928                  * so we first check that old ID has been copied and that ntree is root tree of old ID,
1929                  * then get root tree of new ID and remap its pointers to new ID... */
1930                 if (id->newid && (&ntree->id != id)) {
1931                         ntree = ntreeFromID(id->newid);
1932                         BKE_libblock_relink_to_newid(&ntree->id);
1933                 }
1934         } FOREACH_NODETREE_END
1935
1936         /* Relink datablock pointer properties */
1937         {
1938                 IDP_RelinkProperty(scene->id.properties);
1939
1940                 FOREACH_SCENE_OBJECT_BEGIN(scene, ob)
1941                 {
1942                         if (!ID_IS_LINKED(ob)) {
1943                                 IDP_RelinkProperty(ob->id.properties);
1944                         }
1945                 }
1946                 FOREACH_SCENE_OBJECT_END;
1947
1948                 if (scene->nodetree) {
1949                         IDP_RelinkProperty(scene->nodetree->id.properties);
1950                         for (bNode *node = scene->nodetree->nodes.first; node; node = node->next) {
1951                                 IDP_RelinkProperty(node->prop);
1952                         }
1953                 }
1954
1955                 if (scene->gpd) {
1956                         IDP_RelinkProperty(scene->gpd->id.properties);
1957                 }
1958
1959                 if (scene->world) {
1960                         IDP_RelinkProperty(scene->world->id.properties);
1961                 }
1962
1963                 if (scene->clip) {
1964                         IDP_RelinkProperty(scene->clip->id.properties);
1965                 }
1966         }
1967         BKE_main_id_clear_newpoins(bmain);
1968         DEG_relations_tag_update(bmain);
1969 }
1970
1971 /******************************* Make Local ***********************************/
1972
1973 enum {
1974         MAKE_LOCAL_SELECT_OB              = 1,
1975         MAKE_LOCAL_SELECT_OBDATA          = 2,
1976         MAKE_LOCAL_SELECT_OBDATA_MATERIAL = 3,
1977         MAKE_LOCAL_ALL                    = 4,
1978 };
1979
1980 static int tag_localizable_looper(
1981         void *UNUSED(user_data), ID *UNUSED(self_id), ID **id_pointer, const int UNUSED(cb_flag))
1982 {
1983         if (*id_pointer) {
1984                 (*id_pointer)->tag &= ~LIB_TAG_DOIT;
1985         }
1986
1987         return IDWALK_RET_NOP;
1988 }
1989
1990 static void tag_localizable_objects(bContext *C, const int mode)
1991 {
1992         Main *bmain = CTX_data_main(C);
1993
1994         BKE_main_id_tag_all(bmain, LIB_TAG_DOIT, false);
1995
1996         /* Set LIB_TAG_DOIT flag for all selected objects, so next we can check whether
1997          * object is gonna to become local or not.
1998          */
1999         CTX_DATA_BEGIN (C, Object *, object, selected_objects)
2000         {
2001                 object->id.tag |= LIB_TAG_DOIT;
2002
2003                 /* If data is also gonna to become local, mark data we're interested in
2004                  * as gonna-to-be-local.
2005                  */
2006                 if (mode == MAKE_LOCAL_SELECT_OBDATA && object->data) {
2007                         ID *data_id = (ID *) object->data;
2008                         data_id->tag |= LIB_TAG_DOIT;
2009                 }
2010         }
2011         CTX_DATA_END;
2012
2013         /* Also forbid making objects local if other library objects are using
2014          * them for modifiers or constraints.
2015          */
2016         for (Object *object = bmain->object.first; object; object = object->id.next) {
2017                 if ((object->id.tag & LIB_TAG_DOIT) == 0) {
2018                         BKE_library_foreach_ID_link(NULL, &object->id, tag_localizable_looper, NULL, IDWALK_READONLY);
2019                 }
2020                 if (object->data) {
2021                         ID *data_id = (ID *) object->data;
2022                         if ((data_id->tag & LIB_TAG_DOIT) == 0) {
2023                                 BKE_library_foreach_ID_link(NULL, data_id, tag_localizable_looper, NULL, IDWALK_READONLY);
2024                         }
2025                 }
2026         }
2027
2028         /* TODO(sergey): Drivers targets? */
2029 }
2030
2031 /**
2032  * Instance indirectly referenced zero user objects,
2033  * otherwise they're lost on reload, see T40595.
2034  */
2035 static bool make_local_all__instance_indirect_unused(Main *bmain, ViewLayer *view_layer, Collection *collection)
2036 {
2037         Object *ob;
2038         bool changed = false;
2039
2040         for (ob = bmain->object.first; ob; ob = ob->id.next) {
2041                 if (ID_IS_LINKED(ob) && (ob->id.us == 0)) {
2042                         Base *base;
2043
2044                         id_us_plus(&ob->id);
2045
2046                         BKE_collection_object_add(bmain, collection, ob);
2047                         base = BKE_view_layer_base_find(view_layer, ob);
2048                         base->flag |= BASE_SELECTED;
2049                         BKE_scene_object_base_flag_sync_from_base(base);
2050                         DEG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
2051
2052                         changed = true;
2053                 }
2054         }
2055
2056         return changed;
2057 }
2058
2059 static void make_local_animdata_tag_strips(ListBase *strips)
2060 {
2061         NlaStrip *strip;
2062
2063         for (strip = strips->first; strip; strip = strip->next) {
2064                 if (strip->act) {
2065                         strip->act->id.tag &= ~LIB_TAG_PRE_EXISTING;
2066                 }
2067                 if (strip->remap && strip->remap->target) {
2068                         strip->remap->target->id.tag &= ~LIB_TAG_PRE_EXISTING;
2069                 }
2070
2071                 make_local_animdata_tag_strips(&strip->strips);
2072         }
2073 }
2074
2075 /* Tag all actions used by given animdata to be made local. */
2076 static void make_local_animdata_tag(AnimData *adt)
2077 {
2078         if (adt) {
2079                 /* Actions - Active and Temp */
2080                 if (adt->action) {
2081                         adt->action->id.tag &= ~LIB_TAG_PRE_EXISTING;
2082                 }
2083                 if (adt->tmpact) {
2084                         adt->tmpact->id.tag &= ~LIB_TAG_PRE_EXISTING;
2085                 }
2086                 /* Remaps */
2087                 if (adt->remap && adt->remap->target) {
2088                         adt->remap->target->id.tag &= ~LIB_TAG_PRE_EXISTING;
2089                 }
2090
2091                 /* Drivers */
2092                 /* TODO: need to handle the ID-targets too? */
2093
2094                 /* NLA Data */
2095                 for (NlaTrack *nlt = adt->nla_tracks.first; nlt; nlt = nlt->next) {
2096                         make_local_animdata_tag_strips(&nlt->strips);
2097                 }
2098         }
2099 }
2100
2101 static void make_local_material_tag(Material *ma)
2102 {
2103         if (ma) {
2104                 ma->id.tag &= ~LIB_TAG_PRE_EXISTING;
2105                 make_local_animdata_tag(BKE_animdata_from_id(&ma->id));
2106
2107                 /* About nodetrees: root one is made local together with material, others we keep linked for now... */
2108         }
2109 }
2110
2111 static int make_local_exec(bContext *C, wmOperator *op)
2112 {
2113         Main *bmain = CTX_data_main(C);
2114         ParticleSystem *psys;
2115         Material *ma, ***matarar;
2116         const int mode = RNA_enum_get(op->ptr, "type");
2117         int a;
2118
2119         /* Note: we (ab)use LIB_TAG_PRE_EXISTING to cherry pick which ID to make local... */
2120         if (mode == MAKE_LOCAL_ALL) {
2121                 ViewLayer *view_layer = CTX_data_view_layer(C);
2122                 Collection *collection = CTX_data_collection(C);
2123
2124                 BKE_main_id_tag_all(bmain, LIB_TAG_PRE_EXISTING, false);
2125
2126                 /* De-select so the user can differentiate newly instanced from existing objects. */
2127                 BKE_view_layer_base_deselect_all(view_layer);
2128
2129                 if (make_local_all__instance_indirect_unused(bmain, view_layer, collection)) {
2130                         BKE_report(op->reports, RPT_INFO, "Orphan library objects added to the current scene to avoid loss");
2131                 }
2132         }
2133         else {
2134                 BKE_main_id_tag_all(bmain, LIB_TAG_PRE_EXISTING, true);
2135                 tag_localizable_objects(C, mode);
2136
2137                 CTX_DATA_BEGIN (C, Object *, ob, selected_objects)
2138                 {
2139                         if ((ob->id.tag & LIB_TAG_DOIT) == 0) {
2140                                 continue;
2141                         }
2142
2143                         ob->id.tag &= ~LIB_TAG_PRE_EXISTING;
2144                         make_local_animdata_tag(BKE_animdata_from_id(&ob->id));
2145                         for (psys = ob->particlesystem.first; psys; psys = psys->next) {
2146                                 psys->part->id.tag &= ~LIB_TAG_PRE_EXISTING;
2147                         }
2148
2149                         if (mode == MAKE_LOCAL_SELECT_OBDATA_MATERIAL) {
2150                                 for (a = 0; a < ob->totcol; a++) {
2151                                         ma = ob->mat[a];
2152                                         if (ma) {
2153                                                 make_local_material_tag(ma);
2154                                         }
2155                                 }
2156
2157                                 matarar = (Material ***)give_matarar(ob);
2158                                 if (matarar) {
2159                                         for (a = 0; a < ob->totcol; a++) {
2160                                                 ma = (*matarar)[a];
2161                                                 if (ma) {
2162                                                         make_local_material_tag(ma);
2163                                                 }
2164                                         }
2165                                 }
2166                         }
2167
2168                         if (ELEM(mode, MAKE_LOCAL_SELECT_OBDATA, MAKE_LOCAL_SELECT_OBDATA_MATERIAL) && ob->data != NULL) {
2169                                 ID *ob_data = ob->data;
2170                                 ob_data->tag &= ~LIB_TAG_PRE_EXISTING;
2171                                 make_local_animdata_tag(BKE_animdata_from_id(ob_data));
2172                         }
2173                 }
2174                 CTX_DATA_END;
2175         }
2176
2177         BKE_library_make_local(bmain, NULL, NULL, true, false); /* NULL is all libs */
2178
2179         WM_event_add_notifier(C, NC_WINDOW, NULL);
2180         return OPERATOR_FINISHED;
2181 }
2182
2183 void OBJECT_OT_make_local(wmOperatorType *ot)
2184 {
2185         static const EnumPropertyItem type_items[] = {
2186                 {MAKE_LOCAL_SELECT_OB, "SELECT_OBJECT", 0, "Selected Objects", ""},
2187                 {MAKE_LOCAL_SELECT_OBDATA, "SELECT_OBDATA", 0, "Selected Objects and Data", ""},
2188                 {MAKE_LOCAL_SELECT_OBDATA_MATERIAL, "SELECT_OBDATA_MATERIAL", 0, "Selected Objects, Data and Materials", ""},
2189                 {MAKE_LOCAL_ALL, "ALL", 0, "All", ""},
2190                 {0, NULL, 0, NULL, NULL}
2191         };
2192
2193         /* identifiers */
2194         ot->name = "Make Local";
2195         ot->description = "Make library linked data-blocks local to this file";
2196         ot->idname = "OBJECT_OT_make_local";
2197
2198         /* api callbacks */
2199         ot->invoke = WM_menu_invoke;
2200         ot->exec = make_local_exec;
2201         ot->poll = ED_operator_objectmode;
2202
2203         /* flags */
2204         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2205
2206         /* properties */
2207         ot->prop = RNA_def_enum(ot->srna, "type", type_items, 0, "Type", "");
2208 }
2209
2210
2211 static void make_override_static_tag_object(Object *obact, Object *ob)
2212 {
2213         if (ob == obact) {
2214                 return;
2215         }
2216
2217         if (!ID_IS_LINKED(ob)) {
2218                 return;
2219         }
2220
2221         /* Note: all this is very case-by-case bad handling, ultimately we'll want a real full 'automatic', generic
2222          * handling of all this, will probably require adding some override-aware stuff to library_query code... */
2223
2224         if (obact->type == OB_ARMATURE && ob->modifiers.first != NULL) {
2225                 for (ModifierData *md = ob->modifiers.first; md != NULL; md = md->next) {
2226                         if (md->type == eModifierType_Armature) {
2227                                 ArmatureModifierData *amd = (ArmatureModifierData *)md;
2228                                 if (amd->object == obact) {
2229                                         ob->id.tag |= LIB_TAG_DOIT;
2230                                         break;
2231                                 }
2232                         }
2233                 }
2234         }
2235         else if (ob->parent == obact) {
2236                 ob->id.tag |= LIB_TAG_DOIT;
2237         }
2238
2239         if (ob->id.tag & LIB_TAG_DOIT) {
2240                 printf("Indirectly overriding %s for %s\n", ob->id.name, obact->id.name);
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                 const ListBase dup_collection_objects = BKE_collection_object_cache_get(obact->dup_group);
2293                 Base *base = BLI_findlink(&dup_collection_objects, RNA_enum_get(op->ptr, "object"));
2294                 Object *obcollection = obact;
2295                 obact = base->object;
2296                 Collection *collection = obcollection->dup_group;
2297
2298                 /* First, we make a static override of the linked collection itself. */
2299                 collection->id.tag |= LIB_TAG_DOIT;
2300
2301                 /* Then, we make static override of the whole set of objects in the Collection. */
2302                 FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(collection, ob)
2303                 {
2304                         ob->id.tag |= LIB_TAG_DOIT;
2305                 }
2306                 FOREACH_COLLECTION_OBJECT_RECURSIVE_END;
2307
2308                 /* Then, we remove (untag) bone shape objects, you shall never want to override those (hopefully)... */
2309                 FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(collection, ob)
2310                 {
2311                         if (ob->type == OB_ARMATURE && ob->pose != NULL) {
2312                                 for (bPoseChannel *pchan = ob->pose->chanbase.first; pchan != NULL; pchan = pchan->next) {
2313                                         if (pchan->custom != NULL) {
2314                                                 pchan->custom->id.tag &= ~ LIB_TAG_DOIT;
2315                                         }
2316                                 }
2317                         }
2318                 }
2319                 FOREACH_COLLECTION_OBJECT_RECURSIVE_END;
2320
2321                 success = BKE_override_static_create_from_tag(bmain);
2322
2323                 /* Intantiate our newly overridden objects in scene, if not yet done. */
2324                 Scene *scene = CTX_data_scene(C);
2325                 ViewLayer *view_layer = CTX_data_view_layer(C);
2326                 Collection *new_collection = (Collection *)collection->id.newid;
2327                 FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(new_collection, new_ob)
2328                 {
2329                         if (new_ob != NULL && new_ob->id.override_static != NULL) {
2330                                 if ((base = BKE_view_layer_base_find(view_layer, new_ob)) == NULL) {
2331                                         BKE_collection_object_add_from(bmain, scene, obcollection, new_ob);
2332                                         DEG_id_tag_update_ex(bmain, &new_ob->id, DEG_TAG_TRANSFORM | DEG_TAG_BASE_FLAGS_UPDATE);
2333                                 }
2334                                 /* parent to 'collection' empty */
2335                                 if (new_ob->parent == NULL) {
2336                                         new_ob->parent = obcollection;
2337                                 }
2338                                 if (new_ob == (Object *)obact->id.newid) {
2339                                         BKE_view_layer_base_select(view_layer, base);
2340                                 }
2341                                 else {
2342                                         /* Disable auto-override tags for non-active objects, will help with performaces... */
2343                                         new_ob->id.override_static->flag &= ~STATICOVERRIDE_AUTO;
2344                                 }
2345                                 /* We still want to store all objects' current override status (i.e. change of parent). */
2346                                 BKE_override_static_operations_create(bmain, &new_ob->id, true);
2347                         }
2348                 }
2349                 FOREACH_COLLECTION_OBJECT_RECURSIVE_END;
2350
2351                 /* obcollection is no more duplicollection-ing, it merely parents whole collection of overriding instantiated objects. */
2352                 obcollection->dup_group = NULL;
2353
2354                 /* Also, we'd likely want to lock by default things like transformations of implicitly overriden objects? */
2355
2356                 DEG_id_tag_update(&scene->id, 0);
2357
2358                 /* Cleanup. */
2359                 BKE_main_id_clear_newpoins(bmain);
2360                 BKE_main_id_tag_listbase(&bmain->object, LIB_TAG_DOIT, false);
2361         }
2362         /* Else, poll func ensures us that ID_IS_LINKED(obact) is true. */
2363         else if (obact->type == OB_ARMATURE) {
2364                 BKE_main_id_tag_all(bmain, LIB_TAG_DOIT, false);
2365
2366                 obact->id.tag |= LIB_TAG_DOIT;
2367
2368                 for (Object *ob = bmain->object.first; ob != NULL; ob = ob->id.next) {
2369                         make_override_static_tag_object(obact, ob);
2370                 }
2371
2372                 success = BKE_override_static_create_from_tag(bmain);
2373
2374                 /* Also, we'd likely want to lock by default things like transformations of implicitly overriden objects? */
2375
2376                 /* Cleanup. */
2377                 BKE_main_id_clear_newpoins(bmain);
2378                 BKE_main_id_tag_listbase(&bmain->object, LIB_TAG_DOIT, false);
2379         }
2380         /* TODO: probably more cases where we want to do automated smart things in the future! */
2381         else {
2382                 success = (BKE_override_static_create_from_id(bmain, &obact->id) != NULL);
2383         }
2384
2385         WM_event_add_notifier(C, NC_WINDOW, NULL);
2386
2387         return success ? OPERATOR_FINISHED : OPERATOR_CANCELLED;
2388 }
2389
2390 static bool make_override_static_poll(bContext *C)
2391 {
2392         Object *obact = CTX_data_active_object(C);
2393
2394         /* Object must be directly linked to be overridable. */
2395         return (ED_operator_objectmode(C) && obact != NULL &&
2396                 ((ID_IS_LINKED(obact) && obact->id.tag & LIB_TAG_EXTERN) ||
2397                  (!ID_IS_LINKED(obact) && obact->dup_group != NULL && ID_IS_LINKED(obact->dup_group))));
2398 }
2399
2400 void OBJECT_OT_make_override_static(wmOperatorType *ot)
2401 {
2402         /* identifiers */
2403         ot->name = "Make Static Override";
2404         ot->description = "Make local override of this library linked data-block";
2405         ot->idname = "OBJECT_OT_make_override_static";
2406
2407         /* api callbacks */
2408         ot->invoke = make_override_static_invoke;
2409         ot->exec = make_override_static_exec;
2410         ot->poll = make_override_static_poll;
2411
2412         /* flags */
2413         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2414
2415         /* properties */
2416         PropertyRNA *prop;
2417         prop = RNA_def_enum(ot->srna, "object", DummyRNA_DEFAULT_items, 0, "Override Object",
2418                             "Name of lib-linked/collection object to make an override from");
2419         RNA_def_enum_funcs(prop, proxy_collection_object_itemf);
2420         RNA_def_property_flag(prop, PROP_ENUM_NO_TRANSLATE);
2421         ot->prop = prop;
2422 }
2423
2424 enum {
2425         MAKE_SINGLE_USER_ALL      = 1,
2426         MAKE_SINGLE_USER_SELECTED = 2,
2427 };
2428
2429 static int make_single_user_exec(bContext *C, wmOperator *op)
2430 {
2431         Main *bmain = CTX_data_main(C);
2432         Scene *scene = CTX_data_scene(C);
2433         ViewLayer *view_layer = CTX_data_view_layer(C);
2434         View3D *v3d = CTX_wm_view3d(C); /* ok if this is NULL */
2435         const int flag = (RNA_enum_get(op->ptr, "type") == MAKE_SINGLE_USER_SELECTED) ? SELECT : 0;
2436         const bool copy_collections = false;
2437         bool update_deps = false;
2438
2439         if (RNA_boolean_get(op->ptr, "object")) {
2440                 if (flag == SELECT) {
2441                         BKE_view_layer_selected_objects_tag(view_layer, OB_DONE);
2442                         single_object_users(bmain, scene, v3d, OB_DONE, copy_collections);
2443                 }
2444                 else {
2445                         single_object_users(bmain, scene, v3d, 0, copy_collections);
2446                 }
2447
2448                 /* needed since object relationships may have changed */
2449                 update_deps = true;
2450         }
2451
2452         if (RNA_boolean_get(op->ptr, "obdata")) {
2453                 single_obdata_users(bmain, scene, view_layer, flag);
2454         }
2455
2456         if (RNA_boolean_get(op->ptr, "material")) {
2457                 single_mat_users(bmain, scene, view_layer, flag);
2458         }
2459
2460         if (RNA_boolean_get(op->ptr, "animation")) {
2461                 single_object_action_users(bmain, scene, view_layer, flag);
2462         }
2463
2464         BKE_main_id_clear_newpoins(bmain);
2465
2466         WM_event_add_notifier(C, NC_WINDOW, NULL);
2467
2468         if (update_deps) {
2469                 DEG_relations_tag_update(bmain);
2470         }
2471
2472         return OPERATOR_FINISHED;
2473 }
2474
2475 void OBJECT_OT_make_single_user(wmOperatorType *ot)
2476 {
2477         static const EnumPropertyItem type_items[] = {
2478                 {MAKE_SINGLE_USER_SELECTED, "SELECTED_OBJECTS", 0, "Selected Objects", ""},
2479                 {MAKE_SINGLE_USER_ALL, "ALL", 0, "All", ""},
2480                 {0, NULL, 0, NULL, NULL}};
2481
2482         /* identifiers */
2483         ot->name = "Make Single User";
2484         ot->description = "Make linked data local to each object";
2485         ot->idname = "OBJECT_OT_make_single_user";
2486
2487         /* api callbacks */
2488         ot->invoke = WM_menu_invoke;
2489         ot->exec = make_single_user_exec;
2490         ot->poll = ED_operator_objectmode;
2491
2492         /* flags */
2493         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2494
2495         /* properties */
2496         ot->prop = RNA_def_enum(ot->srna, "type", type_items, MAKE_SINGLE_USER_SELECTED, "Type", "");
2497
2498         RNA_def_boolean(ot->srna, "object", 0, "Object", "Make single user objects");
2499         RNA_def_boolean(ot->srna, "obdata", 0, "Object Data", "Make single user object data");
2500         RNA_def_boolean(ot->srna, "material", 0, "Materials", "Make materials local to each data-block");
2501         RNA_def_boolean(ot->srna, "animation", 0, "Object Animation", "Make animation data local to each object");
2502 }
2503
2504 static int drop_named_material_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2505 {
2506         Main *bmain = CTX_data_main(C);
2507         Base *base = ED_view3d_give_base_under_cursor(C, event->mval);
2508         Material *ma;
2509         char name[MAX_ID_NAME - 2];
2510
2511         RNA_string_get(op->ptr, "name", name);
2512         ma = (Material *)BKE_libblock_find_name(bmain, ID_MA, name);
2513         if (base == NULL || ma == NULL)
2514                 return OPERATOR_CANCELLED;
2515
2516         assign_material(CTX_data_main(C), base->object, ma, 1, BKE_MAT_ASSIGN_USERPREF);
2517
2518         DEG_id_tag_update(&base->object->id, OB_RECALC_OB);
2519
2520         WM_event_add_notifier(C, NC_OBJECT | ND_OB_SHADING, base->object);
2521         WM_event_add_notifier(C, NC_SPACE | ND_SPACE_VIEW3D, CTX_wm_view3d(C));
2522         WM_event_add_notifier(C, NC_MATERIAL | ND_SHADING_LINKS, ma);
2523
2524         return OPERATOR_FINISHED;
2525 }
2526
2527 /* used for dropbox */
2528 /* assigns to object under cursor, only first material slot */
2529 void OBJECT_OT_drop_named_material(wmOperatorType *ot)
2530 {
2531         /* identifiers */
2532         ot->name = "Drop Named Material on Object";
2533         ot->description = "";
2534         ot->idname = "OBJECT_OT_drop_named_material";
2535
2536         /* api callbacks */
2537         ot->invoke = drop_named_material_invoke;
2538         ot->poll = ED_operator_objectmode;
2539
2540         /* flags */
2541         ot->flag = OPTYPE_UNDO | OPTYPE_INTERNAL;
2542
2543         /* properties */
2544         RNA_def_string(ot->srna, "name", "Material", MAX_ID_NAME - 2, "Name", "Material name to assign");
2545 }
2546
2547 static int object_unlink_data_exec(bContext *C, wmOperator *op)
2548 {
2549         ID *id;
2550         PropertyPointerRNA pprop;
2551
2552         UI_context_active_but_prop_get_templateID(C, &pprop.ptr, &pprop.prop);
2553
2554         if (pprop.prop == NULL) {
2555                 BKE_report(op->reports, RPT_ERROR, "Incorrect context for running object data unlink");
2556                 return OPERATOR_CANCELLED;
2557         }
2558
2559         id = pprop.ptr.id.data;
2560
2561         if (GS(id->name) == ID_OB) {
2562                 Object *ob = (Object *)id;
2563                 if (ob->data) {
2564                         ID *id_data = ob->data;
2565
2566                         if (GS(id_data->name) == ID_IM) {
2567                                 id_us_min(id_data);
2568                                 ob->data = NULL;
2569                         }
2570                         else {
2571                                 BKE_report(op->reports, RPT_ERROR, "Can't unlink this object data");
2572                                 return OPERATOR_CANCELLED;
2573                         }
2574                 }
2575         }
2576
2577         RNA_property_update(C, &pprop.ptr, pprop.prop);
2578
2579         return OPERATOR_FINISHED;
2580 }
2581
2582 /**
2583  * \note Only for empty-image objects, this operator is needed
2584  */
2585 void OBJECT_OT_unlink_data(wmOperatorType *ot)
2586 {
2587         /* identifiers */
2588         ot->name = "Unlink";
2589         ot->idname = "OBJECT_OT_unlink_data";
2590         ot->description = "";
2591
2592         /* api callbacks */
2593         ot->exec = object_unlink_data_exec;
2594
2595         /* flags */
2596         ot->flag = OPTYPE_INTERNAL;
2597 }