Fix T37599: Crash making linked objects local and undo
[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_rigidbody_types.h"
48 #include "DNA_scene_types.h"
49 #include "DNA_speaker_types.h"
50 #include "DNA_world_types.h"
51 #include "DNA_object_types.h"
52 #include "DNA_vfont_types.h"
53
54 #include "BLI_math.h"
55 #include "BLI_listbase.h"
56 #include "BLI_linklist.h"
57 #include "BLI_string.h"
58 #include "BLI_kdtree.h"
59 #include "BLI_utildefines.h"
60
61 #include "BLF_translation.h"
62
63 #include "BKE_action.h"
64 #include "BKE_animsys.h"
65 #include "BKE_armature.h"
66 #include "BKE_camera.h"
67 #include "BKE_context.h"
68 #include "BKE_constraint.h"
69 #include "BKE_curve.h"
70 #include "BKE_depsgraph.h"
71 #include "BKE_DerivedMesh.h"
72 #include "BKE_displist.h"
73 #include "BKE_global.h"
74 #include "BKE_group.h"
75 #include "BKE_fcurve.h"
76 #include "BKE_lamp.h"
77 #include "BKE_lattice.h"
78 #include "BKE_library.h"
79 #include "BKE_library_query.h"
80 #include "BKE_main.h"
81 #include "BKE_material.h"
82 #include "BKE_mball.h"
83 #include "BKE_mesh.h"
84 #include "BKE_modifier.h"
85 #include "BKE_object.h"
86 #include "BKE_report.h"
87 #include "BKE_sca.h"
88 #include "BKE_scene.h"
89 #include "BKE_speaker.h"
90 #include "BKE_texture.h"
91 #include "BKE_editmesh.h"
92
93 #include "WM_api.h"
94 #include "WM_types.h"
95
96 #include "UI_interface.h"
97 #include "UI_resources.h"
98
99 #include "RNA_access.h"
100 #include "RNA_define.h"
101 #include "RNA_enum_types.h"
102
103 #include "ED_armature.h"
104 #include "ED_curve.h"
105 #include "ED_keyframing.h"
106 #include "ED_object.h"
107 #include "ED_mesh.h"
108 #include "ED_screen.h"
109 #include "ED_view3d.h"
110
111 #include "object_intern.h"
112
113 /*********************** Make Vertex Parent Operator ************************/
114
115 static int vertex_parent_set_poll(bContext *C)
116 {
117         return ED_operator_editmesh(C) || ED_operator_editsurfcurve(C) || ED_operator_editlattice(C);
118 }
119
120 static int vertex_parent_set_exec(bContext *C, wmOperator *op)
121 {
122         Main *bmain = CTX_data_main(C);
123         Scene *scene = CTX_data_scene(C);
124         Object *obedit = CTX_data_edit_object(C);
125         BMVert *eve;
126         BMIter iter;
127         Curve *cu;
128         Nurb *nu;
129         BezTriple *bezt;
130         BPoint *bp;
131         Object *par;
132         int a, v1 = 0, v2 = 0, v3 = 0, v4 = 0, nr = 1;
133         
134         /* we need 1 to 3 selected vertices */
135         
136         if (obedit->type == OB_MESH) {
137                 Mesh *me = obedit->data;
138                 BMEditMesh *em;
139
140                 EDBM_mesh_load(obedit);
141                 EDBM_mesh_make(scene->toolsettings, obedit);
142
143                 em = me->edit_btmesh;
144
145                 EDBM_mesh_normals_update(em);
146                 BKE_editmesh_tessface_calc(em);
147
148                 /* derivedMesh might be needed for solving parenting,
149                  * so re-create it here */
150                 makeDerivedMesh(scene, obedit, em, CD_MASK_BAREMESH | CD_MASK_ORIGINDEX, 0);
151
152                 BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
153                         if (BM_elem_flag_test(eve, BM_ELEM_SELECT)) {
154                                 if (v1 == 0) v1 = nr;
155                                 else if (v2 == 0) v2 = nr;
156                                 else if (v3 == 0) v3 = nr;
157                                 else if (v4 == 0) v4 = nr;
158                                 else break;
159                         }
160                         nr++;
161                 }
162         }
163         else if (ELEM(obedit->type, OB_SURF, OB_CURVE)) {
164                 ListBase *editnurb = object_editcurve_get(obedit);
165                 
166                 cu = obedit->data;
167
168                 nu = editnurb->first;
169                 while (nu) {
170                         if (nu->type == CU_BEZIER) {
171                                 bezt = nu->bezt;
172                                 a = nu->pntsu;
173                                 while (a--) {
174                                         if (BEZSELECTED_HIDDENHANDLES(cu, bezt)) {
175                                                 if (v1 == 0) v1 = nr;
176                                                 else if (v2 == 0) v2 = nr;
177                                                 else if (v3 == 0) v3 = nr;
178                                                 else if (v4 == 0) v4 = nr;
179                                                 else break;
180                                         }
181                                         nr++;
182                                         bezt++;
183                                 }
184                         }
185                         else {
186                                 bp = nu->bp;
187                                 a = nu->pntsu * nu->pntsv;
188                                 while (a--) {
189                                         if (bp->f1 & SELECT) {
190                                                 if (v1 == 0) v1 = nr;
191                                                 else if (v2 == 0) v2 = nr;
192                                                 else if (v3 == 0) v3 = nr;
193                                                 else if (v4 == 0) v4 = nr;
194                                                 else break;
195                                         }
196                                         nr++;
197                                         bp++;
198                                 }
199                         }
200                         nu = nu->next;
201                 }
202         }
203         else if (obedit->type == OB_LATTICE) {
204                 Lattice *lt = obedit->data;
205                 
206                 a = lt->editlatt->latt->pntsu * lt->editlatt->latt->pntsv * lt->editlatt->latt->pntsw;
207                 bp = lt->editlatt->latt->def;
208                 while (a--) {
209                         if (bp->f1 & SELECT) {
210                                 if (v1 == 0) v1 = nr;
211                                 else if (v2 == 0) v2 = nr;
212                                 else if (v3 == 0) v3 = nr;
213                                 else if (v4 == 0) v4 = nr;
214                                 else break;
215                         }
216                         nr++;
217                         bp++;
218                 }
219         }
220         
221         if (v4 || !((v1 && v2 == 0 && v3 == 0) || (v1 && v2 && v3))) {
222                 BKE_report(op->reports, RPT_ERROR, "Select either 1 or 3 vertices to parent to");
223                 return OPERATOR_CANCELLED;
224         }
225         
226         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
227         {
228                 if (ob != obedit) {
229                         DAG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
230                         par = obedit->parent;
231                         
232                         while (par) {
233                                 if (par == ob) break;
234                                 par = par->parent;
235                         }
236                         if (par) {
237                                 BKE_report(op->reports, RPT_ERROR, "Loop in parents");
238                         }
239                         else {
240                                 Object workob;
241                                 
242                                 ob->parent = BASACT->object;
243                                 if (v3) {
244                                         ob->partype = PARVERT3;
245                                         ob->par1 = v1 - 1;
246                                         ob->par2 = v2 - 1;
247                                         ob->par3 = v3 - 1;
248
249                                         /* inverse parent matrix */
250                                         BKE_object_workob_calc_parent(scene, ob, &workob);
251                                         invert_m4_m4(ob->parentinv, workob.obmat);
252                                 }
253                                 else {
254                                         ob->partype = PARVERT1;
255                                         ob->par1 = v1 - 1;
256
257                                         /* inverse parent matrix */
258                                         BKE_object_workob_calc_parent(scene, ob, &workob);
259                                         invert_m4_m4(ob->parentinv, workob.obmat);
260                                 }
261                         }
262                 }
263         }
264         CTX_DATA_END;
265         
266         DAG_relations_tag_update(bmain);
267
268         WM_event_add_notifier(C, NC_OBJECT, NULL);
269
270         return OPERATOR_FINISHED;
271 }
272
273 void OBJECT_OT_vertex_parent_set(wmOperatorType *ot)
274 {
275         /* identifiers */
276         ot->name = "Make Vertex Parent";
277         ot->description = "Parent selected objects to the selected vertices";
278         ot->idname = "OBJECT_OT_vertex_parent_set";
279         
280         /* api callbacks */
281         ot->invoke = WM_operator_confirm;
282         ot->poll = vertex_parent_set_poll;
283         ot->exec = vertex_parent_set_exec;
284         
285         /* flags */
286         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
287 }
288
289 /********************** Make Proxy Operator *************************/
290
291 /* set the object to proxify */
292 static int make_proxy_invoke(bContext *C, wmOperator *op, const wmEvent *event)
293 {
294         Scene *scene = CTX_data_scene(C);
295         Object *ob = ED_object_active_context(C);
296         
297         /* sanity checks */
298         if (!scene || scene->id.lib || !ob)
299                 return OPERATOR_CANCELLED;
300                 
301         /* Get object to work on - use a menu if we need to... */
302         if (ob->dup_group && ob->dup_group->id.lib) {
303                 /* gives menu with list of objects in group */
304                 //proxy_group_objects_menu(C, op, ob, ob->dup_group);
305                 WM_enum_search_invoke(C, op, event);
306                 return OPERATOR_CANCELLED;
307
308         }
309         else if (ob->id.lib) {
310                 uiPopupMenu *pup = uiPupMenuBegin(C, IFACE_("OK?"), ICON_QUESTION);
311                 uiLayout *layout = uiPupMenuLayout(pup);
312                 
313                 /* create operator menu item with relevant properties filled in */
314                 uiItemFullO_ptr(layout, op->type, op->type->name, ICON_NONE, NULL, WM_OP_EXEC_REGION_WIN, UI_ITEM_O_RETURN_PROPS);
315                 
316                 /* present the menu and be done... */
317                 uiPupMenuEnd(C, pup);
318         }
319         else {
320                 /* error.. cannot continue */
321                 BKE_report(op->reports, RPT_ERROR, "Can only make proxy for a referenced object or group");
322         }
323         
324         /* this invoke just calls another instance of this operator... */
325         return OPERATOR_CANCELLED;
326 }
327
328 static int make_proxy_exec(bContext *C, wmOperator *op)
329 {
330         Main *bmain = CTX_data_main(C);
331         Object *ob, *gob = ED_object_active_context(C);
332         GroupObject *go;
333         Scene *scene = CTX_data_scene(C);
334
335         if (gob->dup_group != NULL) {
336                 go = BLI_findlink(&gob->dup_group->gobject, RNA_enum_get(op->ptr, "object"));
337                 ob = go->ob;
338         }
339         else {
340                 ob = gob;
341                 gob = NULL;
342         }
343         
344         if (ob) {
345                 Object *newob;
346                 Base *newbase, *oldbase = BASACT;
347                 char name[MAX_ID_NAME + 4];
348                 
349                 /* Add new object for the proxy */
350                 newob = BKE_object_add(bmain, scene, OB_EMPTY);
351
352                 BLI_snprintf(name, sizeof(name), "%s_proxy", ((ID *)(gob ? gob : ob))->name + 2);
353
354                 rename_id(&newob->id, name);
355                 
356                 /* set layers OK */
357                 newbase = BASACT;    /* BKE_object_add sets active... */
358                 newbase->lay = oldbase->lay;
359                 newob->lay = newbase->lay;
360                 
361                 /* remove base, leave user count of object, it gets linked in BKE_object_make_proxy */
362                 if (gob == NULL) {
363                         BKE_scene_base_unlink(scene, oldbase);
364                         MEM_freeN(oldbase);
365                 }
366                 
367                 BKE_object_make_proxy(newob, ob, gob);
368                 
369                 /* depsgraph flushes are needed for the new data */
370                 DAG_relations_tag_update(bmain);
371                 DAG_id_tag_update(&newob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
372                 WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, newob);
373         }
374         else {
375                 BKE_report(op->reports, RPT_ERROR, "No object to make proxy for");
376                 return OPERATOR_CANCELLED;
377         }
378         
379         return OPERATOR_FINISHED;
380 }
381
382 /* Generic itemf's for operators that take library args */
383 static EnumPropertyItem *proxy_group_object_itemf(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free)
384 {
385         EnumPropertyItem item_tmp = {0}, *item = NULL;
386         int totitem = 0;
387         int i = 0;
388         Object *ob = ED_object_active_context(C);
389         GroupObject *go;
390
391         if (!ob || !ob->dup_group)
392                 return DummyRNA_DEFAULT_items;
393
394         /* find the object to affect */
395         for (go = ob->dup_group->gobject.first; go; go = go->next) {
396                 item_tmp.identifier = item_tmp.name = go->ob->id.name + 2;
397                 item_tmp.value = i++;
398                 RNA_enum_item_add(&item, &totitem, &item_tmp);
399         }
400
401         RNA_enum_item_end(&item, &totitem);
402         *r_free = true;
403
404         return item;
405 }
406
407 void OBJECT_OT_proxy_make(wmOperatorType *ot)
408 {
409         PropertyRNA *prop;
410
411         /* identifiers */
412         ot->name = "Make Proxy";
413         ot->idname = "OBJECT_OT_proxy_make";
414         ot->description = "Add empty object to become local replacement data of a library-linked object";
415         
416         /* callbacks */
417         ot->invoke = make_proxy_invoke;
418         ot->exec = make_proxy_exec;
419         ot->poll = ED_operator_object_active;
420         
421         /* flags */
422         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
423         
424         /* properties */
425         prop = RNA_def_enum(ot->srna, "object", DummyRNA_DEFAULT_items, 0, "Proxy Object", "Name of lib-linked/grouped object to make a proxy for"); /* XXX, relies on hard coded ID at the moment */
426         RNA_def_enum_funcs(prop, proxy_group_object_itemf);
427         ot->prop = prop;
428 }
429
430 /********************** Clear Parent Operator ******************* */
431
432 typedef enum eObClearParentTypes {
433         CLEAR_PARENT_ALL = 0,
434         CLEAR_PARENT_KEEP_TRANSFORM,
435         CLEAR_PARENT_INVERSE
436 } eObClearParentTypes;
437
438 EnumPropertyItem prop_clear_parent_types[] = {
439         {CLEAR_PARENT_ALL, "CLEAR", 0, "Clear Parent", ""},
440         {CLEAR_PARENT_KEEP_TRANSFORM, "CLEAR_KEEP_TRANSFORM", 0, "Clear and Keep Transformation", ""},
441         {CLEAR_PARENT_INVERSE, "CLEAR_INVERSE", 0, "Clear Parent Inverse", ""},
442         {0, NULL, 0, NULL, NULL}
443 };
444
445 /* Helper for ED_object_parent_clear() - Remove deform-modifiers associated with parent */
446 static void object_remove_parent_deform_modifiers(Object *ob, const Object *par)
447 {
448         if (ELEM3(par->type, OB_ARMATURE, OB_LATTICE, OB_CURVE)) {
449                 ModifierData *md, *mdn;
450                 
451                 /* assume that we only need to remove the first instance of matching deform modifier here */
452                 for (md = ob->modifiers.first; md; md = mdn) {
453                         short free = FALSE;
454                         
455                         mdn = md->next;
456                         
457                         /* need to match types (modifier + parent) and references */
458                         if ((md->type == eModifierType_Armature) && (par->type == OB_ARMATURE)) {
459                                 ArmatureModifierData *amd = (ArmatureModifierData *)md;
460                                 if (amd->object == par) {
461                                         free = TRUE;
462                                 }
463                         }
464                         else if ((md->type == eModifierType_Lattice) && (par->type == OB_LATTICE)) {
465                                 LatticeModifierData *lmd = (LatticeModifierData *)md;
466                                 if (lmd->object == par) {
467                                         free = TRUE;
468                                 }
469                         }
470                         else if ((md->type == eModifierType_Curve) && (par->type == OB_CURVE)) {
471                                 CurveModifierData *cmd = (CurveModifierData *)md;
472                                 if (cmd->object == par) {
473                                         free = TRUE;
474                                 }
475                         }
476                         
477                         /* free modifier if match */
478                         if (free) {
479                                 BLI_remlink(&ob->modifiers, md);
480                                 modifier_free(md);
481                         }
482                 }
483         }
484 }
485
486 void ED_object_parent_clear(Object *ob, int type)
487 {
488         if (ob->parent == NULL)
489                 return;
490         
491         switch (type) {
492                 case CLEAR_PARENT_ALL:
493                 {
494                         /* for deformers, remove corresponding modifiers to prevent a large number of modifiers building up */
495                         object_remove_parent_deform_modifiers(ob, ob->parent);
496                         
497                         /* clear parenting relationship completely */
498                         ob->parent = NULL;
499                         break;
500                 }
501                 case CLEAR_PARENT_KEEP_TRANSFORM:
502                 {
503                         /* remove parent, and apply the parented transform result as object's local transforms */
504                         ob->parent = NULL;
505                         BKE_object_apply_mat4(ob, ob->obmat, TRUE, FALSE);
506                         break;
507                 }
508                 case CLEAR_PARENT_INVERSE:
509                 {
510                         /* object stays parented, but the parent inverse (i.e. offset from parent to retain binding state) is cleared */
511                         unit_m4(ob->parentinv);
512                         break;
513                 }
514         }
515         
516         DAG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
517 }
518
519 /* note, poll should check for editable scene */
520 static int parent_clear_exec(bContext *C, wmOperator *op)
521 {
522         Main *bmain = CTX_data_main(C);
523         int type = RNA_enum_get(op->ptr, "type");
524
525         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
526         {
527                 ED_object_parent_clear(ob, type);
528         }
529         CTX_DATA_END;
530
531         DAG_relations_tag_update(bmain);
532         WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL);
533         WM_event_add_notifier(C, NC_OBJECT | ND_PARENT, NULL);
534         return OPERATOR_FINISHED;
535 }
536
537 void OBJECT_OT_parent_clear(wmOperatorType *ot)
538 {
539         /* identifiers */
540         ot->name = "Clear Parent";
541         ot->description = "Clear the object's parenting";
542         ot->idname = "OBJECT_OT_parent_clear";
543         
544         /* api callbacks */
545         ot->invoke = WM_menu_invoke;
546         ot->exec = parent_clear_exec;
547         
548         ot->poll = ED_operator_object_active_editable;
549         
550         /* flags */
551         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
552         
553         ot->prop = RNA_def_enum(ot->srna, "type", prop_clear_parent_types, CLEAR_PARENT_ALL, "Type", "");
554 }
555
556 /* ******************** Make Parent Operator *********************** */
557
558 void ED_object_parent(Object *ob, Object *par, int type, const char *substr)
559 {
560         if (!par || BKE_object_parent_loop_check(par, ob)) {
561                 ob->parent = NULL;
562                 ob->partype = PAROBJECT;
563                 ob->parsubstr[0] = 0;
564                 return;
565         }
566
567         /* this could use some more checks */
568
569         ob->parent = par;
570         ob->partype &= ~PARTYPE;
571         ob->partype |= type;
572         BLI_strncpy(ob->parsubstr, substr, sizeof(ob->parsubstr));
573 }
574
575 /* Operator Property */
576 EnumPropertyItem prop_make_parent_types[] = {
577         {PAR_OBJECT, "OBJECT", 0, "Object", ""},
578         {PAR_ARMATURE, "ARMATURE", 0, "Armature Deform", ""},
579         {PAR_ARMATURE_NAME, "ARMATURE_NAME", 0, "   With Empty Groups", ""},
580         {PAR_ARMATURE_AUTO, "ARMATURE_AUTO", 0, "   With Automatic Weights", ""},
581         {PAR_ARMATURE_ENVELOPE, "ARMATURE_ENVELOPE", 0, "   With Envelope Weights", ""},
582         {PAR_BONE, "BONE", 0, "Bone", ""},
583         {PAR_BONE_RELATIVE, "BONE_RELATIVE", 0, "Bone Relative", ""},
584         {PAR_CURVE, "CURVE", 0, "Curve Deform", ""},
585         {PAR_FOLLOW, "FOLLOW", 0, "Follow Path", ""},
586         {PAR_PATH_CONST, "PATH_CONST", 0, "Path Constraint", ""},
587         {PAR_LATTICE, "LATTICE", 0, "Lattice Deform", ""},
588         {PAR_VERTEX, "VERTEX", 0, "Vertex", ""},
589         {PAR_VERTEX_TRI, "VERTEX_TRI", 0, "Vertex (Triangle)", ""},
590         {0, NULL, 0, NULL, NULL}
591 };
592
593 int ED_object_parent_set(ReportList *reports, Main *bmain, Scene *scene, Object *ob, Object *par,
594                          int partype, bool xmirror, bool keep_transform, const int vert_par[3])
595 {
596         bPoseChannel *pchan = NULL;
597         int pararm = ELEM4(partype, PAR_ARMATURE, PAR_ARMATURE_NAME, PAR_ARMATURE_ENVELOPE, PAR_ARMATURE_AUTO);
598         
599         DAG_id_tag_update(&par->id, OB_RECALC_OB);
600         
601         /* preconditions */
602         if (partype == PAR_FOLLOW || partype == PAR_PATH_CONST) {
603                 if (par->type != OB_CURVE)
604                         return 0;
605                 else {
606                         Curve *cu = par->data;
607                         
608                         if ((cu->flag & CU_PATH) == 0) {
609                                 cu->flag |= CU_PATH | CU_FOLLOW;
610                                 BKE_displist_make_curveTypes(scene, par, 0);  /* force creation of path data */
611                         }
612                         else {
613                                 cu->flag |= CU_FOLLOW;
614                         }
615
616                         /* if follow, add F-Curve for ctime (i.e. "eval_time") so that path-follow works */
617                         if (partype == PAR_FOLLOW) {
618                                 /* get or create F-Curve */
619                                 bAction *act = verify_adt_action(&cu->id, 1);
620                                 FCurve *fcu = verify_fcurve(act, NULL, NULL, "eval_time", 0, 1);
621                                 
622                                 /* setup dummy 'generator' modifier here to get 1-1 correspondence still working */
623                                 if (!fcu->bezt && !fcu->fpt && !fcu->modifiers.first)
624                                         add_fmodifier(&fcu->modifiers, FMODIFIER_TYPE_GENERATOR);
625                         }
626                         
627                         /* fall back on regular parenting now (for follow only) */
628                         if (partype == PAR_FOLLOW)
629                                 partype = PAR_OBJECT;
630                 }
631         }
632         else if (ELEM(partype, PAR_BONE, PAR_BONE_RELATIVE)) {
633                 pchan = BKE_pose_channel_active(par);
634                 
635                 if (pchan == NULL) {
636                         BKE_report(reports, RPT_ERROR, "No active bone");
637                         return 0;
638                 }
639         }
640         
641         if (ob != par) {
642                 if (BKE_object_parent_loop_check(par, ob)) {
643                         BKE_report(reports, RPT_ERROR, "Loop in parents");
644                         return 0;
645                 }
646                 else {
647                         Object workob;
648
649                         /* apply transformation of previous parenting */
650                         if (keep_transform) {
651                                 /* was removed because of bug [#23577],
652                                  * but this can be handy in some cases too [#32616], so make optional */
653                                 BKE_object_apply_mat4(ob, ob->obmat, FALSE, FALSE);
654                         }
655
656                         /* set the parent (except for follow-path constraint option) */
657                         if (partype != PAR_PATH_CONST) {
658                                 ob->parent = par;
659                         }
660                         
661                         /* handle types */
662                         if (pchan)
663                                 BLI_strncpy(ob->parsubstr, pchan->name, sizeof(ob->parsubstr));
664                         else
665                                 ob->parsubstr[0] = 0;
666                                 
667                         if (partype == PAR_PATH_CONST) {
668                                 /* don't do anything here, since this is not technically "parenting" */
669                         }
670                         else if (ELEM(partype, PAR_CURVE, PAR_LATTICE) || (pararm)) {
671                                 /* partype is now set to PAROBJECT so that invisible 'virtual' modifiers don't need to be created
672                                  * NOTE: the old (2.4x) method was to set ob->partype = PARSKEL, creating the virtual modifiers
673                                  */
674                                 ob->partype = PAROBJECT; /* note, dna define, not operator property */
675                                 //ob->partype = PARSKEL; /* note, dna define, not operator property */
676                                 
677                                 /* BUT, to keep the deforms, we need a modifier, and then we need to set the object that it uses 
678                                  * - We need to ensure that the modifier we're adding doesn't already exist, so we check this by
679                                  *   assuming that the parent is selected too...
680                                  */
681                                 // XXX currently this should only happen for meshes, curves, surfaces, and lattices - this stuff isn't available for metas yet
682                                 if (ELEM5(ob->type, OB_MESH, OB_CURVE, OB_SURF, OB_FONT, OB_LATTICE)) {
683                                         ModifierData *md;
684                                         
685                                         switch (partype) {
686                                                 case PAR_CURVE: /* curve deform */
687                                                         if (modifiers_isDeformedByCurve(ob) != par) {
688                                                                 md = ED_object_modifier_add(reports, bmain, scene, ob, NULL, eModifierType_Curve);
689                                                                 if (md) {
690                                                                         ((CurveModifierData *)md)->object = par;
691                                                                 }
692                                                         }
693                                                         break;
694                                                 case PAR_LATTICE: /* lattice deform */
695                                                         if (modifiers_isDeformedByLattice(ob) != par) {
696                                                                 md = ED_object_modifier_add(reports, bmain, scene, ob, NULL, eModifierType_Lattice);
697                                                                 if (md) {
698                                                                         ((LatticeModifierData *)md)->object = par;
699                                                                 }
700                                                         }
701                                                         break;
702                                                 default: /* armature deform */
703                                                         if (modifiers_isDeformedByArmature(ob) != par) {
704                                                                 md = ED_object_modifier_add(reports, bmain, scene, ob, NULL, eModifierType_Armature);
705                                                                 if (md) {
706                                                                         ((ArmatureModifierData *)md)->object = par;
707                                                                 }
708                                                         }
709                                                         break;
710                                         }
711                                 }
712                         }
713                         else if (partype == PAR_BONE) {
714                                 ob->partype = PARBONE;  /* note, dna define, not operator property */
715                                 if (pchan->bone)
716                                         pchan->bone->flag &= ~BONE_RELATIVE_PARENTING;
717                         }
718                         else if (partype == PAR_BONE_RELATIVE) {
719                                 ob->partype = PARBONE;  /* note, dna define, not operator property */
720                                 if (pchan->bone)
721                                         pchan->bone->flag |= BONE_RELATIVE_PARENTING;
722                         }
723                         else if (partype == PAR_VERTEX) {
724                                 ob->partype = PARVERT1;
725                                 ob->par1 = vert_par[0];
726                         }
727                         else if (partype == PAR_VERTEX_TRI) {
728                                 ob->partype = PARVERT3;
729                                 copy_v3_v3_int(&ob->par1, vert_par);
730                         }
731                         else {
732                                 ob->partype = PAROBJECT;  /* note, dna define, not operator property */
733                         }
734                         
735                         /* constraint */
736                         if (partype == PAR_PATH_CONST) {
737                                 bConstraint *con;
738                                 bFollowPathConstraint *data;
739                                 float cmat[4][4], vec[3];
740                                 
741                                 con = BKE_add_ob_constraint(ob, "AutoPath", CONSTRAINT_TYPE_FOLLOWPATH);
742                                 
743                                 data = con->data;
744                                 data->tar = par;
745                                 
746                                 BKE_get_constraint_target_matrix(scene, con, 0, CONSTRAINT_OBTYPE_OBJECT, NULL, cmat, scene->r.cfra);
747                                 sub_v3_v3v3(vec, ob->obmat[3], cmat[3]);
748                                 
749                                 copy_v3_v3(ob->loc, vec);
750                         }
751                         else if (pararm && (ob->type == OB_MESH) && (par->type == OB_ARMATURE)) {
752                                 if (partype == PAR_ARMATURE_NAME)
753                                         create_vgroups_from_armature(reports, scene, ob, par, ARM_GROUPS_NAME, FALSE);
754                                 else if (partype == PAR_ARMATURE_ENVELOPE)
755                                         create_vgroups_from_armature(reports, scene, ob, par, ARM_GROUPS_ENVELOPE, xmirror);
756                                 else if (partype == PAR_ARMATURE_AUTO) {
757                                         WM_cursor_wait(1);
758                                         create_vgroups_from_armature(reports, scene, ob, par, ARM_GROUPS_AUTO, xmirror);
759                                         WM_cursor_wait(0);
760                                 }
761                                 /* get corrected inverse */
762                                 ob->partype = PAROBJECT;
763                                 BKE_object_workob_calc_parent(scene, ob, &workob);
764                                 
765                                 invert_m4_m4(ob->parentinv, workob.obmat);
766                         }
767                         else {
768                                 /* calculate inverse parent matrix */
769                                 BKE_object_workob_calc_parent(scene, ob, &workob);
770                                 invert_m4_m4(ob->parentinv, workob.obmat);
771                         }
772                         
773                         DAG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA);
774                 }
775         }
776
777         return 1;
778 }
779
780
781
782 static void parent_set_vert_find(KDTree *tree, Object *child, int vert_par[3], bool is_tri)
783 {
784         const float *co_find = child->obmat[3];
785         if (is_tri) {
786                 KDTreeNearest nearest[3];
787                 int tot;
788
789                 tot = BLI_kdtree_find_nearest_n(tree, co_find, nearest, 3);
790                 BLI_assert(tot == 3);
791
792                 vert_par[0] = nearest[0].index;
793                 vert_par[1] = nearest[1].index;
794                 vert_par[2] = nearest[2].index;
795
796                 BLI_assert(min_iii(UNPACK3(vert_par)) >= 0);
797         }
798         else {
799                 vert_par[0] = BLI_kdtree_find_nearest(tree, co_find, NULL);
800                 BLI_assert(vert_par[0] >= 0);
801                 vert_par[1] = 0;
802                 vert_par[2] = 0;
803         }
804 }
805
806 static int parent_set_exec(bContext *C, wmOperator *op)
807 {
808         Main *bmain = CTX_data_main(C);
809         Scene *scene = CTX_data_scene(C);
810         Object *par = ED_object_active_context(C);
811         int partype = RNA_enum_get(op->ptr, "type");
812         bool xmirror = RNA_boolean_get(op->ptr, "xmirror");
813         bool keep_transform = RNA_boolean_get(op->ptr, "keep_transform");
814         bool ok = true;
815
816         /* vertex parent (kdtree) */
817         const bool is_vert_par = ELEM(partype, PAR_VERTEX, PAR_VERTEX_TRI);
818         const bool is_tri = partype == PAR_VERTEX_TRI;
819         int tree_tot;
820         struct KDTree *tree = NULL;
821         int vert_par[3] = {0, 0, 0};
822         int *vert_par_p = is_vert_par ? vert_par : NULL;
823
824
825         if (is_vert_par) {
826                 tree = BKE_object_as_kdtree(par, &tree_tot);
827                 BLI_assert(tree != NULL);
828
829                 if (tree_tot < (is_tri ? 3 : 1)) {
830                         BKE_report(op->reports, RPT_ERROR, "Not enough vertices for vertex-parent");
831                         ok = false;
832                         goto cleanup;
833                 }
834         }
835
836
837         /* Non vertex-parent */
838         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
839         {
840                 if (is_vert_par) {
841                         parent_set_vert_find(tree, ob, vert_par, is_tri);
842                 }
843
844                 if (!ED_object_parent_set(op->reports, bmain, scene, ob, par, partype, xmirror, keep_transform, vert_par_p)) {
845                         ok = false;
846                         break;
847                 }
848         }
849         CTX_DATA_END;
850
851
852 cleanup:
853         if (is_vert_par) {
854                 BLI_kdtree_free(tree);
855         }
856
857         if (!ok)
858                 return OPERATOR_CANCELLED;
859
860         DAG_relations_tag_update(bmain);
861         WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL);
862         WM_event_add_notifier(C, NC_OBJECT | ND_PARENT, NULL);
863
864         return OPERATOR_FINISHED;
865 }
866
867
868 static int parent_set_invoke(bContext *C, wmOperator *UNUSED(op), const wmEvent *UNUSED(event))
869 {
870         Object *ob = ED_object_active_context(C);
871         uiPopupMenu *pup = uiPupMenuBegin(C, IFACE_("Set Parent To"), ICON_NONE);
872         uiLayout *layout = uiPupMenuLayout(pup);
873
874         wmOperatorType *ot = WM_operatortype_find("OBJECT_OT_parent_set", TRUE);
875         PointerRNA opptr;
876
877 #if 0
878         uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_OBJECT);
879 #else
880         opptr = uiItemFullO_ptr(layout, ot, IFACE_("Object"), ICON_NONE, NULL, WM_OP_EXEC_DEFAULT, UI_ITEM_O_RETURN_PROPS);
881         RNA_enum_set(&opptr, "type", PAR_OBJECT);
882         RNA_boolean_set(&opptr, "keep_transform", FALSE);
883
884         opptr = uiItemFullO_ptr(layout, ot, IFACE_("Object (Keep Transform)"), ICON_NONE, NULL, WM_OP_EXEC_DEFAULT,
885                                 UI_ITEM_O_RETURN_PROPS);
886         RNA_enum_set(&opptr, "type", PAR_OBJECT);
887         RNA_boolean_set(&opptr, "keep_transform", TRUE);
888 #endif
889         /* ob becomes parent, make the associated menus */
890         if (ob->type == OB_ARMATURE) {
891                 uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_ARMATURE);
892                 uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_ARMATURE_NAME);
893                 uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_ARMATURE_ENVELOPE);
894                 uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_ARMATURE_AUTO);
895                 uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_BONE);
896                 uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_BONE_RELATIVE);
897         }
898         else if (ob->type == OB_CURVE) {
899                 uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_CURVE);
900                 uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_FOLLOW);
901                 uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_PATH_CONST);
902         }
903         else if (ob->type == OB_LATTICE) {
904                 uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_LATTICE);
905         }
906         
907         /* vertex parenting */
908         if (OB_TYPE_SUPPORT_PARVERT(ob->type)) {
909                 uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_VERTEX);
910                 uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_VERTEX_TRI);
911         }
912
913         uiPupMenuEnd(C, pup);
914         
915         return OPERATOR_CANCELLED;
916 }
917
918 static bool parent_set_draw_check_prop(PointerRNA *ptr, PropertyRNA *prop)
919 {
920         const char *prop_id = RNA_property_identifier(prop);
921         int type = RNA_enum_get(ptr, "type");
922
923         /* Only show XMirror for PAR_ARMATURE_ENVELOPE and PAR_ARMATURE_AUTO! */
924         if (STREQ(prop_id, "xmirror")) {
925                 if (ELEM(type, PAR_ARMATURE_ENVELOPE, PAR_ARMATURE_AUTO))
926                         return true;
927                 else
928                         return false;
929         }
930
931         return true;
932 }
933
934 static void parent_set_ui(bContext *C, wmOperator *op)
935 {
936         uiLayout *layout = op->layout;
937         wmWindowManager *wm = CTX_wm_manager(C);
938         PointerRNA ptr;
939
940         RNA_pointer_create(&wm->id, op->type->srna, op->properties, &ptr);
941
942         /* Main auto-draw call. */
943         uiDefAutoButsRNA(layout, &ptr, parent_set_draw_check_prop, '\0');
944 }
945
946 void OBJECT_OT_parent_set(wmOperatorType *ot)
947 {
948         /* identifiers */
949         ot->name = "Make Parent";
950         ot->description = "Set the object's parenting";
951         ot->idname = "OBJECT_OT_parent_set";
952         
953         /* api callbacks */
954         ot->invoke = parent_set_invoke;
955         ot->exec = parent_set_exec;
956         ot->poll = ED_operator_object_active;
957         ot->ui = parent_set_ui;
958         
959         /* flags */
960         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
961         
962         RNA_def_enum(ot->srna, "type", prop_make_parent_types, 0, "Type", "");
963         RNA_def_boolean(ot->srna, "xmirror", FALSE, "X Mirror",
964                         "Apply weights symmetrically along X axis, for Envelope/Automatic vertex groups creation");
965         RNA_def_boolean(ot->srna, "keep_transform", FALSE, "Keep Transform",
966                         "Apply transformation before parenting");
967
968 }
969
970 /* ************ Make Parent Without Inverse Operator ******************* */
971
972 static int parent_noinv_set_exec(bContext *C, wmOperator *op)
973 {
974         Main *bmain = CTX_data_main(C);
975         Object *par = ED_object_active_context(C);
976         
977         DAG_id_tag_update(&par->id, OB_RECALC_OB);
978         
979         /* context iterator */
980         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
981         {
982                 if (ob != par) {
983                         if (BKE_object_parent_loop_check(par, ob)) {
984                                 BKE_report(op->reports, RPT_ERROR, "Loop in parents");
985                         }
986                         else {
987                                 /* clear inverse matrix and also the object location */
988                                 unit_m4(ob->parentinv);
989                                 memset(ob->loc, 0, 3 * sizeof(float));
990                                 
991                                 /* set recalc flags */
992                                 DAG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA);
993                                 
994                                 /* set parenting type for object - object only... */
995                                 ob->parent = par;
996                                 ob->partype = PAROBJECT; /* note, dna define, not operator property */
997                         }
998                 }
999         }
1000         CTX_DATA_END;
1001         
1002         DAG_relations_tag_update(bmain);
1003         WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL);
1004         
1005         return OPERATOR_FINISHED;
1006 }
1007
1008 void OBJECT_OT_parent_no_inverse_set(wmOperatorType *ot)
1009 {
1010         /* identifiers */
1011         ot->name = "Make Parent without Inverse";
1012         ot->description = "Set the object's parenting without setting the inverse parent correction";
1013         ot->idname = "OBJECT_OT_parent_no_inverse_set";
1014         
1015         /* api callbacks */
1016         ot->invoke = WM_operator_confirm;
1017         ot->exec = parent_noinv_set_exec;
1018         ot->poll = ED_operator_object_active_editable;
1019         
1020         /* flags */
1021         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1022 }
1023
1024 /************************ Clear Slow Parent Operator *********************/
1025
1026 static int object_slow_parent_clear_exec(bContext *C, wmOperator *UNUSED(op))
1027 {
1028         Scene *scene = CTX_data_scene(C);
1029
1030         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
1031         {
1032                 if (ob->parent) {
1033                         if (ob->partype & PARSLOW) {
1034                                 ob->partype -= PARSLOW;
1035                                 BKE_object_where_is_calc(scene, ob);
1036                                 ob->partype |= PARSLOW;
1037                                 DAG_id_tag_update(&ob->id, OB_RECALC_OB);
1038                         }
1039                 }
1040         }
1041         CTX_DATA_END;
1042
1043         WM_event_add_notifier(C, NC_SCENE, scene);
1044         
1045         return OPERATOR_FINISHED;
1046 }
1047
1048 void OBJECT_OT_slow_parent_clear(wmOperatorType *ot)
1049 {
1050         
1051         /* identifiers */
1052         ot->name = "Clear Slow Parent";
1053         ot->description = "Clear the object's slow parent";
1054         ot->idname = "OBJECT_OT_slow_parent_clear";
1055         
1056         /* api callbacks */
1057         ot->invoke = WM_operator_confirm;
1058         ot->exec = object_slow_parent_clear_exec;
1059         ot->poll = ED_operator_view3d_active;
1060         
1061         /* flags */
1062         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1063 }
1064
1065 /********************** Make Slow Parent Operator *********************/
1066
1067 static int object_slow_parent_set_exec(bContext *C, wmOperator *UNUSED(op))
1068 {
1069         Scene *scene = CTX_data_scene(C);
1070
1071         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
1072         {
1073                 if (ob->parent)
1074                         ob->partype |= PARSLOW;
1075
1076                 DAG_id_tag_update(&ob->id, OB_RECALC_OB);
1077                 
1078         }
1079         CTX_DATA_END;
1080
1081         WM_event_add_notifier(C, NC_SCENE, scene);
1082         
1083         return OPERATOR_FINISHED;
1084 }
1085
1086 void OBJECT_OT_slow_parent_set(wmOperatorType *ot)
1087 {
1088         
1089         /* identifiers */
1090         ot->name = "Set Slow Parent";
1091         ot->description = "Set the object's slow parent";
1092         ot->idname = "OBJECT_OT_slow_parent_set";
1093         
1094         /* api callbacks */
1095         ot->invoke = WM_operator_confirm;
1096         ot->exec = object_slow_parent_set_exec;
1097         ot->poll = ED_operator_view3d_active;
1098         
1099         /* flags */
1100         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1101 }
1102
1103 /* ******************** Clear Track Operator ******************* */
1104
1105 static EnumPropertyItem prop_clear_track_types[] = {
1106         {0, "CLEAR", 0, "Clear Track", ""},
1107         {1, "CLEAR_KEEP_TRANSFORM", 0, "Clear and Keep Transformation (Clear Track)", ""},
1108         {0, NULL, 0, NULL, NULL}
1109 };
1110
1111 /* note, poll should check for editable scene */
1112 static int object_track_clear_exec(bContext *C, wmOperator *op)
1113 {
1114         Main *bmain = CTX_data_main(C);
1115         int type = RNA_enum_get(op->ptr, "type");
1116
1117         if (CTX_data_edit_object(C)) {
1118                 BKE_report(op->reports, RPT_ERROR, "Operation cannot be performed in edit mode");
1119                 return OPERATOR_CANCELLED;
1120         }
1121         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
1122         {
1123                 bConstraint *con, *pcon;
1124                 
1125                 /* remove track-object for old track */
1126                 ob->track = NULL;
1127                 DAG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
1128                 
1129                 /* also remove all tracking constraints */
1130                 for (con = ob->constraints.last; con; con = pcon) {
1131                         pcon = con->prev;
1132                         if (ELEM3(con->type, CONSTRAINT_TYPE_TRACKTO, CONSTRAINT_TYPE_LOCKTRACK, CONSTRAINT_TYPE_DAMPTRACK))
1133                                 BKE_remove_constraint(&ob->constraints, con);
1134                 }
1135                 
1136                 if (type == 1)
1137                         BKE_object_apply_mat4(ob, ob->obmat, TRUE, TRUE);
1138         }
1139         CTX_DATA_END;
1140
1141         DAG_relations_tag_update(bmain);
1142         WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL);
1143
1144         return OPERATOR_FINISHED;
1145 }
1146
1147 void OBJECT_OT_track_clear(wmOperatorType *ot)
1148 {
1149         /* identifiers */
1150         ot->name = "Clear Track";
1151         ot->description = "Clear tracking constraint or flag from object";
1152         ot->idname = "OBJECT_OT_track_clear";
1153         
1154         /* api callbacks */
1155         ot->invoke = WM_menu_invoke;
1156         ot->exec = object_track_clear_exec;
1157         
1158         ot->poll = ED_operator_objectmode;
1159         
1160         /* flags */
1161         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1162         
1163         ot->prop = RNA_def_enum(ot->srna, "type", prop_clear_track_types, 0, "Type", "");
1164 }
1165
1166 /************************** Make Track Operator *****************************/
1167
1168 static EnumPropertyItem prop_make_track_types[] = {
1169         {1, "DAMPTRACK", 0, "Damped Track Constraint", ""},
1170         {2, "TRACKTO", 0, "Track To Constraint", ""},
1171         {3, "LOCKTRACK", 0, "Lock Track Constraint", ""},
1172         {0, NULL, 0, NULL, NULL}
1173 };
1174
1175 static int track_set_exec(bContext *C, wmOperator *op)
1176 {
1177         Main *bmain = CTX_data_main(C);
1178         Object *obact = ED_object_active_context(C);
1179         
1180         int type = RNA_enum_get(op->ptr, "type");
1181         
1182         if (type == 1) {
1183                 bConstraint *con;
1184                 bDampTrackConstraint *data;
1185
1186                 CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
1187                 {
1188                         if (ob != obact) {
1189                                 con = BKE_add_ob_constraint(ob, "AutoTrack", CONSTRAINT_TYPE_DAMPTRACK);
1190
1191                                 data = con->data;
1192                                 data->tar = obact;
1193                                 DAG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
1194                                 
1195                                 /* Lamp, Camera and Speaker track differently by default */
1196                                 if (ELEM3(ob->type, OB_LAMP, OB_CAMERA, OB_SPEAKER)) {
1197                                         data->trackflag = TRACK_nZ;
1198                                 }
1199                         }
1200                 }
1201                 CTX_DATA_END;
1202         }
1203         else if (type == 2) {
1204                 bConstraint *con;
1205                 bTrackToConstraint *data;
1206
1207                 CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
1208                 {
1209                         if (ob != obact) {
1210                                 con = BKE_add_ob_constraint(ob, "AutoTrack", CONSTRAINT_TYPE_TRACKTO);
1211
1212                                 data = con->data;
1213                                 data->tar = obact;
1214                                 DAG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
1215                                 
1216                                 /* Lamp, Camera and Speaker track differently by default */
1217                                 if (ELEM3(ob->type, OB_LAMP, OB_CAMERA, OB_SPEAKER)) {
1218                                         data->reserved1 = TRACK_nZ;
1219                                         data->reserved2 = UP_Y;
1220                                 }
1221                         }
1222                 }
1223                 CTX_DATA_END;
1224         }
1225         else if (type == 3) {
1226                 bConstraint *con;
1227                 bLockTrackConstraint *data;
1228
1229                 CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
1230                 {
1231                         if (ob != obact) {
1232                                 con = BKE_add_ob_constraint(ob, "AutoTrack", CONSTRAINT_TYPE_LOCKTRACK);
1233
1234                                 data = con->data;
1235                                 data->tar = obact;
1236                                 DAG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
1237                                 
1238                                 /* Lamp, Camera and Speaker track differently by default */
1239                                 if (ELEM3(ob->type, OB_LAMP, OB_CAMERA, OB_SPEAKER)) {
1240                                         data->trackflag = TRACK_nZ;
1241                                         data->lockflag = LOCK_Y;
1242                                 }
1243                         }
1244                 }
1245                 CTX_DATA_END;
1246         }
1247         
1248         DAG_relations_tag_update(bmain);
1249         WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL);
1250         
1251         return OPERATOR_FINISHED;
1252 }
1253
1254 void OBJECT_OT_track_set(wmOperatorType *ot)
1255 {
1256         /* identifiers */
1257         ot->name = "Make Track";
1258         ot->description = "Make the object track another object, either by constraint or old way or locked track";
1259         ot->idname = "OBJECT_OT_track_set";
1260         
1261         /* api callbacks */
1262         ot->invoke = WM_menu_invoke;
1263         ot->exec = track_set_exec;
1264         
1265         ot->poll = ED_operator_objectmode;
1266         
1267         /* flags */
1268         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1269         
1270         /* properties */
1271         ot->prop = RNA_def_enum(ot->srna, "type", prop_make_track_types, 0, "Type", "");
1272 }
1273
1274 /************************** Move to Layer Operator *****************************/
1275
1276 static unsigned int move_to_layer_init(bContext *C, wmOperator *op)
1277 {
1278         int values[20], a;
1279         unsigned int lay = 0;
1280
1281         if (!RNA_struct_property_is_set(op->ptr, "layers")) {
1282                 /* note: layers are set in bases, library objects work for this */
1283                 CTX_DATA_BEGIN (C, Base *, base, selected_bases)
1284                 {
1285                         lay |= base->lay;
1286                 }
1287                 CTX_DATA_END;
1288
1289                 for (a = 0; a < 20; a++)
1290                         values[a] = (lay & (1 << a));
1291                 
1292                 RNA_boolean_set_array(op->ptr, "layers", values);
1293         }
1294         else {
1295                 RNA_boolean_get_array(op->ptr, "layers", values);
1296
1297                 for (a = 0; a < 20; a++)
1298                         if (values[a])
1299                                 lay |= (1 << a);
1300         }
1301
1302         return lay;
1303 }
1304
1305 static int move_to_layer_invoke(bContext *C, wmOperator *op, const wmEvent *event)
1306 {
1307         View3D *v3d = CTX_wm_view3d(C);
1308         if (v3d && v3d->localvd) {
1309                 return WM_operator_confirm_message(C, op, "Move from localview");
1310         }
1311         else {
1312                 move_to_layer_init(C, op);
1313                 return WM_operator_props_popup(C, op, event);
1314         }
1315 }
1316
1317 static int move_to_layer_exec(bContext *C, wmOperator *op)
1318 {
1319         Main *bmain = CTX_data_main(C);
1320         Scene *scene = CTX_data_scene(C);
1321         View3D *v3d = CTX_wm_view3d(C);
1322         unsigned int lay, local;
1323         /* bool is_lamp = FALSE; */ /* UNUSED */
1324         
1325         lay = move_to_layer_init(C, op);
1326         lay &= 0xFFFFFF;
1327
1328         if (lay == 0) return OPERATOR_CANCELLED;
1329         
1330         if (v3d && v3d->localvd) {
1331                 /* now we can move out of localview. */
1332                 /* note: layers are set in bases, library objects work for this */
1333                 CTX_DATA_BEGIN (C, Base *, base, selected_bases)
1334                 {
1335                         lay = base->lay & ~v3d->lay;
1336                         base->lay = lay;
1337                         base->object->lay = lay;
1338                         base->object->flag &= ~SELECT;
1339                         base->flag &= ~SELECT;
1340                         /* if (base->object->type == OB_LAMP) is_lamp = TRUE; */
1341                 }
1342                 CTX_DATA_END;
1343         }
1344         else {
1345                 /* normal non localview operation */
1346                 /* note: layers are set in bases, library objects work for this */
1347                 CTX_DATA_BEGIN (C, Base *, base, selected_bases)
1348                 {
1349                         /* upper byte is used for local view */
1350                         local = base->lay & 0xFF000000;
1351                         base->lay = lay + local;
1352                         base->object->lay = lay;
1353                         /* if (base->object->type == OB_LAMP) is_lamp = TRUE; */
1354                 }
1355                 CTX_DATA_END;
1356         }
1357         
1358         /* warning, active object may be hidden now */
1359         
1360         WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, scene);
1361         WM_event_add_notifier(C, NC_SCENE | ND_LAYER_CONTENT, scene);
1362
1363         DAG_relations_tag_update(bmain);
1364
1365         return OPERATOR_FINISHED;
1366 }
1367
1368 void OBJECT_OT_move_to_layer(wmOperatorType *ot)
1369 {
1370         /* identifiers */
1371         ot->name = "Move to Layer";
1372         ot->description = "Move the object to different layers";
1373         ot->idname = "OBJECT_OT_move_to_layer";
1374         
1375         /* api callbacks */
1376         ot->invoke = move_to_layer_invoke;
1377         ot->exec = move_to_layer_exec;
1378         ot->poll = ED_operator_objectmode;
1379         
1380         /* flags */
1381         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1382         
1383         /* properties */
1384         RNA_def_boolean_layer_member(ot->srna, "layers", 20, NULL, "Layer", "");
1385 }
1386
1387 /************************** Link to Scene Operator *****************************/
1388
1389 #if 0
1390 static void link_to_scene(Main *UNUSED(bmain), unsigned short UNUSED(nr))
1391 {
1392         Scene *sce = (Scene *) BLI_findlink(&bmain->scene, G.curscreen->scenenr - 1);
1393         Base *base, *nbase;
1394         
1395         if (sce == 0) return;
1396         if (sce->id.lib) return;
1397         
1398         for (base = FIRSTBASE; base; base = base->next) {
1399                 if (TESTBASE(v3d, base)) {
1400                         
1401                         nbase = MEM_mallocN(sizeof(Base), "newbase");
1402                         *nbase = *base;
1403                         BLI_addhead(&(sce->base), nbase);
1404                         id_us_plus((ID *)base->object);
1405                 }
1406         }
1407 }
1408 #endif
1409
1410 Base *ED_object_scene_link(Scene *scene, Object *ob)
1411 {
1412         Base *base;
1413
1414         if (BKE_scene_base_find(scene, ob)) {
1415                 return NULL;
1416         }
1417
1418         base = BKE_scene_base_add(scene, ob);
1419         id_us_plus(&ob->id);
1420
1421         return base;
1422 }
1423
1424 static int make_links_scene_exec(bContext *C, wmOperator *op)
1425 {
1426         Scene *scene_to = BLI_findlink(&CTX_data_main(C)->scene, RNA_enum_get(op->ptr, "scene"));
1427
1428         if (scene_to == NULL) {
1429                 BKE_report(op->reports, RPT_ERROR, "Could not find scene");
1430                 return OPERATOR_CANCELLED;
1431         }
1432
1433         if (scene_to == CTX_data_scene(C)) {
1434                 BKE_report(op->reports, RPT_ERROR, "Cannot link objects into the same scene");
1435                 return OPERATOR_CANCELLED;
1436         }
1437
1438         if (scene_to->id.lib) {
1439                 BKE_report(op->reports, RPT_ERROR, "Cannot link objects into a linked scene");
1440                 return OPERATOR_CANCELLED;
1441         }
1442
1443         CTX_DATA_BEGIN (C, Base *, base, selected_bases)
1444         {
1445                 ED_object_scene_link(scene_to, base->object);
1446         }
1447         CTX_DATA_END;
1448
1449         /* redraw the 3D view because the object center points are colored differently */
1450         WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, NULL);
1451
1452         /* one day multiple scenes will be visible, then we should have some update function for them */
1453         return OPERATOR_FINISHED;
1454 }
1455
1456 enum {
1457         MAKE_LINKS_OBDATA = 1,
1458         MAKE_LINKS_MATERIALS,
1459         MAKE_LINKS_ANIMDATA,
1460         MAKE_LINKS_GROUP,
1461         MAKE_LINKS_DUPLIGROUP,
1462         MAKE_LINKS_MODIFIERS,
1463         MAKE_LINKS_FONTS
1464 };
1465
1466 /* Return 1 if make link data is allow, zero otherwise */
1467 static int allow_make_links_data(const int type, Object *ob_src, Object *ob_dst)
1468 {
1469         switch (type) {
1470                 case MAKE_LINKS_OBDATA:
1471                         if (ob_src->type == ob_dst->type && ob_src->type != OB_EMPTY)
1472                                 return 1;
1473                         break;
1474                 case MAKE_LINKS_MATERIALS:
1475                         if (OB_TYPE_SUPPORT_MATERIAL(ob_src->type) &&
1476                             OB_TYPE_SUPPORT_MATERIAL(ob_dst->type))
1477                         {
1478                                 return 1;
1479                         }
1480                         break;
1481                 case MAKE_LINKS_ANIMDATA:
1482                 case MAKE_LINKS_GROUP:
1483                 case MAKE_LINKS_DUPLIGROUP:
1484                         return 1;
1485                 case MAKE_LINKS_MODIFIERS:
1486                         if (ob_src->type != OB_EMPTY && ob_dst->type != OB_EMPTY)
1487                                 return 1;
1488                         break;
1489                 case MAKE_LINKS_FONTS:
1490                         if ((ob_src->data != ob_dst->data) &&
1491                             (ob_src->type == OB_FONT) &&
1492                             (ob_dst->type == OB_FONT))
1493                         {
1494                                 return 1;
1495                         }
1496                         break;
1497         }
1498         return 0;
1499 }
1500
1501 static int make_links_data_exec(bContext *C, wmOperator *op)
1502 {
1503         Main *bmain = CTX_data_main(C);
1504         Scene *scene = CTX_data_scene(C);
1505         const int type = RNA_enum_get(op->ptr, "type");
1506         Object *ob_src;
1507         ID *obdata_id;
1508         int a;
1509
1510         /* group */
1511         LinkNode *ob_groups = NULL;
1512         bool is_cycle = false;
1513         bool is_lib = false;
1514
1515         ob_src = ED_object_active_context(C);
1516
1517         /* avoid searching all groups in source object each time */
1518         if (type == MAKE_LINKS_GROUP) {
1519                 ob_groups = BKE_object_groups(ob_src);
1520         }
1521
1522         CTX_DATA_BEGIN (C, Base *, base_dst, selected_editable_bases)
1523         {
1524                 Object *ob_dst = base_dst->object;
1525
1526                 if (ob_src != ob_dst) {
1527                         if (allow_make_links_data(type, ob_src, ob_dst)) {
1528                                 obdata_id = ob_dst->data;
1529
1530                                 switch (type) {
1531                                         case MAKE_LINKS_OBDATA: /* obdata */
1532                                                 obdata_id->us--;
1533
1534                                                 obdata_id = ob_src->data;
1535                                                 id_us_plus(obdata_id);
1536                                                 ob_dst->data = obdata_id;
1537
1538                                                 /* if amount of material indices changed: */
1539                                                 test_object_materials(bmain, ob_dst->data);
1540
1541                                                 DAG_id_tag_update(&ob_dst->id, OB_RECALC_DATA);
1542                                                 break;
1543                                         case MAKE_LINKS_MATERIALS:
1544                                                 /* new approach, using functions from kernel */
1545                                                 for (a = 0; a < ob_src->totcol; a++) {
1546                                                         Material *ma = give_current_material(ob_src, a + 1);
1547                                                         assign_material(ob_dst, ma, a + 1, BKE_MAT_ASSIGN_USERPREF); /* also works with ma==NULL */
1548                                                 }
1549                                                 DAG_id_tag_update(&ob_dst->id, 0);
1550                                                 break;
1551                                         case MAKE_LINKS_ANIMDATA:
1552                                                 BKE_copy_animdata_id((ID *)ob_dst, (ID *)ob_src, FALSE);
1553                                                 if (ob_dst->data && ob_src->data) {
1554                                                         if (obdata_id->lib) {
1555                                                                 is_lib = true;
1556                                                                 break;
1557                                                         }
1558                                                         BKE_copy_animdata_id((ID *)ob_dst->data, (ID *)ob_src->data, FALSE);
1559                                                 }
1560                                                 DAG_id_tag_update(&ob_dst->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
1561                                                 break;
1562                                         case MAKE_LINKS_GROUP:
1563                                         {
1564                                                 LinkNode *group_node;
1565
1566                                                 /* first clear groups */
1567                                                 BKE_object_groups_clear(scene, base_dst, ob_dst);
1568
1569                                                 /* now add in the groups from the link nodes */
1570                                                 for (group_node = ob_groups; group_node; group_node = group_node->next) {
1571                                                         if (ob_dst->dup_group != group_node->link) {
1572                                                                 BKE_group_object_add(group_node->link, ob_dst, scene, base_dst);
1573                                                         }
1574                                                         else {
1575                                                                 is_cycle = TRUE;
1576                                                         }
1577                                                 }
1578                                                 break;
1579                                         }
1580                                         case MAKE_LINKS_DUPLIGROUP:
1581                                                 ob_dst->dup_group = ob_src->dup_group;
1582                                                 if (ob_dst->dup_group) {
1583                                                         id_lib_extern(&ob_dst->dup_group->id);
1584                                                         ob_dst->transflag |= OB_DUPLIGROUP;
1585                                                 }
1586                                                 break;
1587                                         case MAKE_LINKS_MODIFIERS:
1588                                                 BKE_object_link_modifiers(ob_dst, ob_src);
1589                                                 DAG_id_tag_update(&ob_dst->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
1590                                                 break;
1591                                         case MAKE_LINKS_FONTS:
1592                                         {
1593                                                 Curve *cu_src = ob_src->data;
1594                                                 Curve *cu_dst = ob_dst->data;
1595
1596                                                 if (obdata_id->lib) {
1597                                                         is_lib = true;
1598                                                         break;
1599                                                 }
1600
1601                                                 if (cu_dst->vfont) cu_dst->vfont->id.us--;
1602                                                 cu_dst->vfont = cu_src->vfont;
1603                                                 id_us_plus((ID *)cu_dst->vfont);
1604                                                 if (cu_dst->vfontb) cu_dst->vfontb->id.us--;
1605                                                 cu_dst->vfontb = cu_src->vfontb;
1606                                                 id_us_plus((ID *)cu_dst->vfontb);
1607                                                 if (cu_dst->vfonti) cu_dst->vfonti->id.us--;
1608                                                 cu_dst->vfonti = cu_src->vfonti;
1609                                                 id_us_plus((ID *)cu_dst->vfonti);
1610                                                 if (cu_dst->vfontbi) cu_dst->vfontbi->id.us--;
1611                                                 cu_dst->vfontbi = cu_src->vfontbi;
1612                                                 id_us_plus((ID *)cu_dst->vfontbi);
1613
1614                                                 DAG_id_tag_update(&ob_dst->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
1615                                                 break;
1616                                         }
1617                                 }
1618                         }
1619                 }
1620         }
1621         CTX_DATA_END;
1622
1623         if (type == MAKE_LINKS_GROUP) {
1624                 if (ob_groups) {
1625                         BLI_linklist_free(ob_groups, NULL);
1626                 }
1627
1628                 if (is_cycle) {
1629                         BKE_report(op->reports, RPT_WARNING, "Skipped some groups because of cycle detected");
1630                 }
1631         }
1632
1633         if (is_lib) {
1634                 BKE_report(op->reports, RPT_WARNING, "Skipped editing library object data");
1635         }
1636
1637         DAG_relations_tag_update(bmain);
1638         WM_event_add_notifier(C, NC_SPACE | ND_SPACE_VIEW3D, CTX_wm_view3d(C));
1639         WM_event_add_notifier(C, NC_OBJECT, NULL);
1640
1641         return OPERATOR_FINISHED;
1642 }
1643
1644
1645 void OBJECT_OT_make_links_scene(wmOperatorType *ot)
1646 {
1647         PropertyRNA *prop;
1648
1649         /* identifiers */
1650         ot->name = "Link Objects to Scene";
1651         ot->description = "Link selection to another scene";
1652         ot->idname = "OBJECT_OT_make_links_scene";
1653
1654         /* api callbacks */
1655         ot->invoke = WM_enum_search_invoke;
1656         ot->exec = make_links_scene_exec;
1657         /* better not run the poll check */
1658
1659         /* flags */
1660         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1661
1662         /* properties */
1663         prop = RNA_def_enum(ot->srna, "scene", DummyRNA_NULL_items, 0, "Scene", "");
1664         RNA_def_enum_funcs(prop, RNA_scene_local_itemf);
1665         ot->prop = prop;
1666 }
1667
1668 void OBJECT_OT_make_links_data(wmOperatorType *ot)
1669 {
1670         static EnumPropertyItem make_links_items[] = {
1671                 {MAKE_LINKS_OBDATA,     "OBDATA", 0, "Object Data", ""},
1672                 {MAKE_LINKS_MATERIALS,  "MATERIAL", 0, "Materials", ""},
1673                 {MAKE_LINKS_ANIMDATA,   "ANIMATION", 0, "Animation Data", ""},
1674                 {MAKE_LINKS_GROUP,      "GROUPS", 0, "Group", ""},
1675                 {MAKE_LINKS_DUPLIGROUP, "DUPLIGROUP", 0, "DupliGroup", ""},
1676                 {MAKE_LINKS_MODIFIERS,  "MODIFIERS", 0, "Modifiers", ""},
1677                 {MAKE_LINKS_FONTS,      "FONTS", 0, "Fonts", ""},
1678                 {0, NULL, 0, NULL, NULL}};
1679
1680         /* identifiers */
1681         ot->name = "Link Data";
1682         ot->description = "Make links from the active object to other selected objects";
1683         ot->idname = "OBJECT_OT_make_links_data";
1684
1685         /* api callbacks */
1686         ot->exec = make_links_data_exec;
1687         ot->poll = ED_operator_object_active;
1688
1689         /* flags */
1690         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1691
1692         /* properties */
1693         ot->prop = RNA_def_enum(ot->srna, "type", make_links_items, 0, "Type", "");
1694 }
1695
1696
1697 /**************************** Make Single User ********************************/
1698
1699 static void single_object_users(Main *bmain, Scene *scene, View3D *v3d, int flag, bool copy_groups)
1700 {
1701         Base *base;
1702         Object *ob, *obn;
1703         Group *group, *groupn;
1704         GroupObject *go;
1705         
1706         clear_sca_new_poins();  /* sensor/contr/act */
1707
1708         /* newid may still have some trash from Outliner tree building,
1709          * so clear that first to avoid errors [#26002] */
1710         for (ob = bmain->object.first; ob; ob = ob->id.next)
1711                 ob->id.newid = NULL;
1712
1713         /* duplicate (must set newid) */
1714         for (base = FIRSTBASE; base; base = base->next) {
1715                 ob = base->object;
1716                 
1717                 if ((base->flag & flag) == flag) {
1718                         if (ob->id.lib == NULL && ob->id.us > 1) {
1719                                 /* base gets copy of object */
1720                                 obn = BKE_object_copy(ob);
1721                                 base->object = obn;
1722                                 ob->id.us--;
1723                         }
1724                 }
1725         }
1726
1727         /* duplicate groups that consist entirely of duplicated objects */
1728         for (group = bmain->group.first; group; group = group->id.next) {
1729                 group->id.newid = NULL;
1730
1731                 if (copy_groups && group->gobject.first) {
1732                         bool all_duplicated = true;
1733
1734                         for (go = group->gobject.first; go; go = go->next) {
1735                                 if (!(go->ob && (go->ob->id.newid))) {
1736                                         all_duplicated = false;
1737                                         break;
1738                                 }
1739                         }
1740
1741                         if (all_duplicated) {
1742                                 groupn = BKE_group_copy(group);
1743
1744                                 for (go = groupn->gobject.first; go; go = go->next)
1745                                         go->ob = (Object *)go->ob->id.newid;
1746                         }
1747                 }
1748         }
1749
1750         /* group pointers in scene */
1751         BKE_scene_groups_relink(scene);
1752         
1753         ID_NEW(scene->camera);
1754         if (v3d) ID_NEW(v3d->camera);
1755         
1756         /* object and group pointers */
1757         for (base = FIRSTBASE; base; base = base->next) {
1758                 BKE_object_relink(base->object);
1759         }
1760
1761         set_sca_new_poins();
1762 }
1763
1764 /* not an especially efficient function, only added so the single user
1765  * button can be functional.*/
1766 void ED_object_single_user(Main *bmain, Scene *scene, Object *ob)
1767 {
1768         Base *base;
1769         bool copy_groups = false;
1770
1771         for (base = FIRSTBASE; base; base = base->next) {
1772                 if (base->object == ob) base->flag |=  OB_DONE;
1773                 else base->flag &= ~OB_DONE;
1774         }
1775
1776         single_object_users(bmain, scene, NULL, OB_DONE, copy_groups);
1777 }
1778
1779 static void new_id_matar(Material **matar, int totcol)
1780 {
1781         ID *id;
1782         int a;
1783         
1784         for (a = 0; a < totcol; a++) {
1785                 id = (ID *)matar[a];
1786                 if (id && id->lib == NULL) {
1787                         if (id->newid) {
1788                                 matar[a] = (Material *)id->newid;
1789                                 id_us_plus(id->newid);
1790                                 id->us--;
1791                         }
1792                         else if (id->us > 1) {
1793                                 matar[a] = BKE_material_copy(matar[a]);
1794                                 id->us--;
1795                                 id->newid = (ID *)matar[a];
1796                         }
1797                 }
1798         }
1799 }
1800
1801 static void single_obdata_users(Main *bmain, Scene *scene, int flag)
1802 {
1803         Object *ob;
1804         Lamp *la;
1805         Curve *cu;
1806         //Camera *cam;
1807         Base *base;
1808         Mesh *me;
1809         Lattice *lat;
1810         ID *id;
1811         int a;
1812
1813         for (base = FIRSTBASE; base; base = base->next) {
1814                 ob = base->object;
1815                 if (ob->id.lib == NULL && (base->flag & flag) == flag) {
1816                         id = ob->data;
1817                         
1818                         if (id && id->us > 1 && id->lib == NULL) {
1819                                 DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
1820
1821                                 switch (ob->type) {
1822                                         case OB_LAMP:
1823                                                 ob->data = la = BKE_lamp_copy(ob->data);
1824                                                 for (a = 0; a < MAX_MTEX; a++) {
1825                                                         if (la->mtex[a]) {
1826                                                                 ID_NEW(la->mtex[a]->object);
1827                                                         }
1828                                                 }
1829                                                 break;
1830                                         case OB_CAMERA:
1831                                                 ob->data = BKE_camera_copy(ob->data);
1832                                                 break;
1833                                         case OB_MESH:
1834                                                 ob->data = me = BKE_mesh_copy(ob->data);
1835                                                 if (me->key)
1836                                                         BKE_copy_animdata_id_action((ID *)me->key);
1837                                                 break;
1838                                         case OB_MBALL:
1839                                                 ob->data = BKE_mball_copy(ob->data);
1840                                                 break;
1841                                         case OB_CURVE:
1842                                         case OB_SURF:
1843                                         case OB_FONT:
1844                                                 ob->data = cu = BKE_curve_copy(ob->data);
1845                                                 ID_NEW(cu->bevobj);
1846                                                 ID_NEW(cu->taperobj);
1847                                                 if (cu->key)
1848                                                         BKE_copy_animdata_id_action((ID *)cu->key);
1849                                                 break;
1850                                         case OB_LATTICE:
1851                                                 ob->data = lat = BKE_lattice_copy(ob->data);
1852                                                 if (lat->key)
1853                                                         BKE_copy_animdata_id_action((ID *)lat->key);
1854                                                 break;
1855                                         case OB_ARMATURE:
1856                                                 DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
1857                                                 ob->data = BKE_armature_copy(ob->data);
1858                                                 BKE_pose_rebuild(ob, ob->data);
1859                                                 break;
1860                                         case OB_SPEAKER:
1861                                                 ob->data = BKE_speaker_copy(ob->data);
1862                                                 break;
1863                                         default:
1864                                                 if (G.debug & G_DEBUG)
1865                                                         printf("ERROR %s: can't copy %s\n", __func__, id->name);
1866                                                 return;
1867                                 }
1868
1869                                 /* Copy animation data after object data became local,
1870                                  * otherwise old and new object data will share the same
1871                                  * AnimData structure, which is not what we want.
1872                                  *                                             (sergey)
1873                                  */
1874                                 BKE_copy_animdata_id_action((ID *)ob->data);
1875
1876                                 id->us--;
1877                                 id->newid = ob->data;
1878                                 
1879                         }
1880                         
1881                 }
1882         }
1883         
1884         me = bmain->mesh.first;
1885         while (me) {
1886                 ID_NEW(me->texcomesh);
1887                 me = me->id.next;
1888         }
1889 }
1890
1891 static void single_object_action_users(Scene *scene, int flag)
1892 {
1893         Object *ob;
1894         Base *base;
1895         
1896         for (base = FIRSTBASE; base; base = base->next) {
1897                 ob = base->object;
1898                 if (ob->id.lib == NULL && (flag == 0 || (base->flag & SELECT)) ) {
1899                         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
1900                         BKE_copy_animdata_id_action(&ob->id);
1901                 }
1902         }
1903 }
1904
1905 static void single_mat_users(Scene *scene, int flag, int do_textures)
1906 {
1907         Object *ob;
1908         Base *base;
1909         Material *ma, *man;
1910         Tex *tex;
1911         int a, b;
1912         
1913         for (base = FIRSTBASE; base; base = base->next) {
1914                 ob = base->object;
1915                 if (ob->id.lib == NULL && (flag == 0 || (base->flag & SELECT)) ) {
1916         
1917                         for (a = 1; a <= ob->totcol; a++) {
1918                                 ma = give_current_material(ob, a);
1919                                 if (ma) {
1920                                         /* do not test for LIB_NEW: this functions guaranteed delivers single_users! */
1921                                         
1922                                         if (ma->id.us > 1) {
1923                                                 man = BKE_material_copy(ma);
1924                                                 BKE_copy_animdata_id_action(&man->id);
1925                                                 
1926                                                 man->id.us = 0;
1927                                                 assign_material(ob, man, a, BKE_MAT_ASSIGN_USERPREF);
1928
1929                                                 if (do_textures) {
1930                                                         for (b = 0; b < MAX_MTEX; b++) {
1931                                                                 if (ma->mtex[b] && (tex = ma->mtex[b]->tex)) {
1932                                                                         if (tex->id.us > 1) {
1933                                                                                 tex->id.us--;
1934                                                                                 tex = BKE_texture_copy(tex);
1935                                                                                 BKE_copy_animdata_id_action(&tex->id);
1936                                                                                 man->mtex[b]->tex = tex;
1937                                                                         }
1938                                                                 }
1939                                                         }
1940                                                 }
1941                                         }
1942                                 }
1943                         }
1944                 }
1945         }
1946 }
1947
1948 static void do_single_tex_user(Tex **from)
1949 {
1950         Tex *tex, *texn;
1951         
1952         tex = *from;
1953         if (tex == NULL) return;
1954         
1955         if (tex->id.newid) {
1956                 *from = (Tex *)tex->id.newid;
1957                 id_us_plus(tex->id.newid);
1958                 tex->id.us--;
1959         }
1960         else if (tex->id.us > 1) {
1961                 texn = BKE_texture_copy(tex);
1962                 BKE_copy_animdata_id_action(&texn->id);
1963                 tex->id.newid = (ID *)texn;
1964                 tex->id.us--;
1965                 *from = texn;
1966         }
1967 }
1968
1969 static void single_tex_users_expand(Main *bmain)
1970 {
1971         /* only when 'parent' blocks are LIB_NEW */
1972         Material *ma;
1973         Lamp *la;
1974         World *wo;
1975         int b;
1976                 
1977         for (ma = bmain->mat.first; ma; ma = ma->id.next) {
1978                 if (ma->id.flag & LIB_NEW) {
1979                         for (b = 0; b < MAX_MTEX; b++) {
1980                                 if (ma->mtex[b] && ma->mtex[b]->tex) {
1981                                         do_single_tex_user(&(ma->mtex[b]->tex));
1982                                 }
1983                         }
1984                 }
1985         }
1986
1987         for (la = bmain->lamp.first; la; la = la->id.next) {
1988                 if (la->id.flag & LIB_NEW) {
1989                         for (b = 0; b < MAX_MTEX; b++) {
1990                                 if (la->mtex[b] && la->mtex[b]->tex) {
1991                                         do_single_tex_user(&(la->mtex[b]->tex));
1992                                 }
1993                         }
1994                 }
1995         }
1996
1997         for (wo = bmain->world.first; wo; wo = wo->id.next) {
1998                 if (wo->id.flag & LIB_NEW) {
1999                         for (b = 0; b < MAX_MTEX; b++) {
2000                                 if (wo->mtex[b] && wo->mtex[b]->tex) {
2001                                         do_single_tex_user(&(wo->mtex[b]->tex));
2002                                 }
2003                         }
2004                 }
2005         }
2006 }
2007
2008 static void single_mat_users_expand(Main *bmain)
2009 {
2010         /* only when 'parent' blocks are LIB_NEW */
2011         Object *ob;
2012         Mesh *me;
2013         Curve *cu;
2014         MetaBall *mb;
2015         Material *ma;
2016         int a;
2017         
2018         for (ob = bmain->object.first; ob; ob = ob->id.next)
2019                 if (ob->id.flag & LIB_NEW)
2020                         new_id_matar(ob->mat, ob->totcol);
2021
2022         for (me = bmain->mesh.first; me; me = me->id.next)
2023                 if (me->id.flag & LIB_NEW)
2024                         new_id_matar(me->mat, me->totcol);
2025
2026         for (cu = bmain->curve.first; cu; cu = cu->id.next)
2027                 if (cu->id.flag & LIB_NEW)
2028                         new_id_matar(cu->mat, cu->totcol);
2029
2030         for (mb = bmain->mball.first; mb; mb = mb->id.next)
2031                 if (mb->id.flag & LIB_NEW)
2032                         new_id_matar(mb->mat, mb->totcol);
2033
2034         /* material imats  */
2035         for (ma = bmain->mat.first; ma; ma = ma->id.next)
2036                 if (ma->id.flag & LIB_NEW)
2037                         for (a = 0; a < MAX_MTEX; a++)
2038                                 if (ma->mtex[a])
2039                                         ID_NEW(ma->mtex[a]->object);
2040 }
2041
2042 /* used for copying scenes */
2043 void ED_object_single_users(Main *bmain, Scene *scene, bool full, bool copy_groups)
2044 {
2045         single_object_users(bmain, scene, NULL, 0, copy_groups);
2046
2047         if (full) {
2048                 single_obdata_users(bmain, scene, 0);
2049                 single_object_action_users(scene, 0);
2050                 single_mat_users_expand(bmain);
2051                 single_tex_users_expand(bmain);
2052         }
2053
2054         BKE_main_id_clear_newpoins(bmain);
2055 }
2056
2057 /******************************* Make Local ***********************************/
2058
2059 /* helper for below, ma was checked to be not NULL */
2060 static void make_local_makelocalmaterial(Material *ma)
2061 {
2062         AnimData *adt;
2063         int b;
2064         
2065         id_make_local(&ma->id, false);
2066         
2067         for (b = 0; b < MAX_MTEX; b++)
2068                 if (ma->mtex[b] && ma->mtex[b]->tex)
2069                         id_make_local(&ma->mtex[b]->tex->id, false);
2070         
2071         adt = BKE_animdata_from_id(&ma->id);
2072         if (adt) BKE_animdata_make_local(adt);
2073
2074         /* nodetree? XXX */
2075 }
2076
2077 enum {
2078         MAKE_LOCAL_SELECT_OB,
2079         MAKE_LOCAL_SELECT_OBDATA,
2080         MAKE_LOCAL_SELECT_OBDATA_MATERIAL,
2081         MAKE_LOCAL_ALL
2082 };
2083
2084 static bool tag_localizable_looper(void *UNUSED(user_data), ID **id_pointer, int UNUSED(cd_flag))
2085 {
2086         if (*id_pointer) {
2087                 (*id_pointer)->flag &= ~LIB_DOIT;
2088         }
2089         return true;
2090 }
2091
2092 static void tag_localizable_objects(bContext *C, int mode)
2093 {
2094         Main *bmain = CTX_data_main(C);
2095         Object *object;
2096
2097         BKE_main_id_tag_all(bmain, false);
2098
2099         /* Set LIB_DOIT flag for all selected objects, so next we can check whether
2100          * object is gonna to become local or not.
2101          */
2102         CTX_DATA_BEGIN (C, Object *, object, selected_objects)
2103         {
2104                 object->id.flag |= LIB_DOIT;
2105
2106                 /* If data is also gonna to become local, mark data we're interested in
2107                  * as gonna-to-be-local.
2108                  */
2109                 if (mode == MAKE_LOCAL_SELECT_OBDATA) {
2110                         ID *data_id = (ID *) object->data;
2111                         data_id->flag |= LIB_DOIT;
2112                 }
2113         }
2114         CTX_DATA_END;
2115
2116         /* Also forbid making objects local if other library objects are using
2117          * them for modifiers or constraints.
2118          */
2119         for (object = bmain->object.first; object; object = object->id.next) {
2120                 if ((object->id.flag & LIB_DOIT) == 0) {
2121                         BKE_library_foreach_ID_link(&object->id, tag_localizable_looper, NULL, IDWALK_READONLY);
2122                 }
2123                 if (object->data) {
2124                         ID *data_id = (ID *) object->data;
2125                         if ((data_id->flag & LIB_DOIT) == 0) {
2126                                 BKE_library_foreach_ID_link(data_id, tag_localizable_looper, NULL, IDWALK_READONLY);
2127                         }
2128                 }
2129         }
2130
2131         /* TODO(sergey): Drivers targets? */
2132 }
2133
2134 static int make_local_exec(bContext *C, wmOperator *op)
2135 {
2136         Main *bmain = CTX_data_main(C);
2137         AnimData *adt;
2138         ParticleSystem *psys;
2139         Material *ma, ***matarar;
2140         Lamp *la;
2141         ID *id;
2142         int a, b, mode = RNA_enum_get(op->ptr, "type");
2143         
2144         if (mode == MAKE_LOCAL_ALL) {
2145                 BKE_library_make_local(bmain, NULL, false); /* NULL is all libs */
2146                 WM_event_add_notifier(C, NC_WINDOW, NULL);
2147                 return OPERATOR_FINISHED;
2148         }
2149
2150         tag_localizable_objects(C, mode);
2151         BKE_main_id_clear_newpoins(bmain);
2152         
2153         CTX_DATA_BEGIN (C, Object *, ob, selected_objects)
2154         {
2155                 if ((ob->id.flag & LIB_DOIT) == 0) {
2156                         continue;
2157                 }
2158
2159                 if (ob->id.lib)
2160                         id_make_local(&ob->id, false);
2161         }
2162         CTX_DATA_END;
2163         
2164         /* maybe object pointers */
2165         CTX_DATA_BEGIN (C, Object *, ob, selected_objects)
2166         {
2167                 if (ob->id.lib == NULL) {
2168                         ID_NEW(ob->parent);
2169                 }
2170         }
2171         CTX_DATA_END;
2172
2173         CTX_DATA_BEGIN (C, Object *, ob, selected_objects)
2174         {
2175                 if ((ob->id.flag & LIB_DOIT) == 0) {
2176                         continue;
2177                 }
2178
2179                 id = ob->data;
2180                         
2181                 if (id && (ELEM(mode, MAKE_LOCAL_SELECT_OBDATA, MAKE_LOCAL_SELECT_OBDATA_MATERIAL))) {
2182                         id_make_local(id, false);
2183                         adt = BKE_animdata_from_id(id);
2184                         if (adt) BKE_animdata_make_local(adt);
2185                         
2186                         /* tag indirect data direct */
2187                         matarar = give_matarar(ob);
2188                         if (matarar) {
2189                                 for (a = 0; a < ob->totcol; a++) {
2190                                         ma = (*matarar)[a];
2191                                         if (ma)
2192                                                 id_lib_extern(&ma->id);
2193                                 }
2194                         }
2195                 }
2196
2197                 for (psys = ob->particlesystem.first; psys; psys = psys->next)
2198                         id_make_local(&psys->part->id, false);
2199
2200                 adt = BKE_animdata_from_id(&ob->id);
2201                 if (adt) BKE_animdata_make_local(adt);
2202         }
2203         CTX_DATA_END;
2204
2205         if (mode == MAKE_LOCAL_SELECT_OBDATA_MATERIAL) {
2206                 CTX_DATA_BEGIN (C, Object *, ob, selected_objects)
2207                 {
2208                         if ((ob->id.flag & LIB_DOIT) == 0) {
2209                                 continue;
2210                         }
2211
2212                         if (ob->type == OB_LAMP) {
2213                                 la = ob->data;
2214
2215                                 for (b = 0; b < MAX_MTEX; b++)
2216                                         if (la->mtex[b] && la->mtex[b]->tex)
2217                                                 id_make_local(&la->mtex[b]->tex->id, false);
2218                         }
2219                         else {
2220                                 for (a = 0; a < ob->totcol; a++) {
2221                                         ma = ob->mat[a];
2222                                         if (ma)
2223                                                 make_local_makelocalmaterial(ma);
2224                                 }
2225                                 
2226                                 matarar = (Material ***)give_matarar(ob);
2227                                 if (matarar) {
2228                                         for (a = 0; a < ob->totcol; a++) {
2229                                                 ma = (*matarar)[a];
2230                                                 if (ma)
2231                                                         make_local_makelocalmaterial(ma);
2232                                         }
2233                                 }
2234                         }
2235                 }
2236                 CTX_DATA_END;
2237         }
2238
2239         WM_event_add_notifier(C, NC_WINDOW, NULL);
2240
2241         return OPERATOR_FINISHED;
2242 }
2243
2244 void OBJECT_OT_make_local(wmOperatorType *ot)
2245 {
2246         static EnumPropertyItem type_items[] = {
2247                 {MAKE_LOCAL_SELECT_OB, "SELECT_OBJECT", 0, "Selected Objects", ""},
2248                 {MAKE_LOCAL_SELECT_OBDATA, "SELECT_OBDATA", 0, "Selected Objects and Data", ""},
2249                 {MAKE_LOCAL_SELECT_OBDATA_MATERIAL, "SELECT_OBDATA_MATERIAL", 0, "Selected Objects, Data and Materials", ""},
2250                 {MAKE_LOCAL_ALL, "ALL", 0, "All", ""},
2251                 {0, NULL, 0, NULL, NULL}
2252         };
2253
2254         /* identifiers */
2255         ot->name = "Make Local";
2256         ot->description = "Make library linked datablocks local to this file";
2257         ot->idname = "OBJECT_OT_make_local";
2258         
2259         /* api callbacks */
2260         ot->invoke = WM_menu_invoke;
2261         ot->exec = make_local_exec;
2262         ot->poll = ED_operator_objectmode;
2263         
2264         /* flags */
2265         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2266         
2267         /* properties */
2268         ot->prop = RNA_def_enum(ot->srna, "type", type_items, 0, "Type", "");
2269 }
2270
2271 static int make_single_user_exec(bContext *C, wmOperator *op)
2272 {
2273         Main *bmain = CTX_data_main(C);
2274         Scene *scene = CTX_data_scene(C);
2275         View3D *v3d = CTX_wm_view3d(C); /* ok if this is NULL */
2276         int flag = RNA_enum_get(op->ptr, "type"); /* 0==ALL, SELECTED==selected objecs */
2277         bool copy_groups = false;
2278
2279         BKE_main_id_clear_newpoins(bmain);
2280
2281         if (RNA_boolean_get(op->ptr, "object"))
2282                 single_object_users(bmain, scene, v3d, flag, copy_groups);
2283
2284         if (RNA_boolean_get(op->ptr, "obdata"))
2285                 single_obdata_users(bmain, scene, flag);
2286
2287         if (RNA_boolean_get(op->ptr, "material"))
2288                 single_mat_users(scene, flag, RNA_boolean_get(op->ptr, "texture"));
2289
2290 #if 0 /* can't do this separate from materials */
2291         if (RNA_boolean_get(op->ptr, "texture"))
2292                 single_mat_users(scene, flag, TRUE);
2293 #endif
2294         if (RNA_boolean_get(op->ptr, "animation"))
2295                 single_object_action_users(scene, flag);
2296
2297         /* TODO(sergey): This should not be needed, however some tool still could rely
2298          *               on the fact, that id->newid is kept NULL by default.
2299          *               Need to make sure all the guys are learing newid before they're
2300          *               using it, not after.
2301          */
2302         BKE_main_id_clear_newpoins(bmain);
2303
2304         WM_event_add_notifier(C, NC_WINDOW, NULL);
2305         return OPERATOR_FINISHED;
2306 }
2307
2308 void OBJECT_OT_make_single_user(wmOperatorType *ot)
2309 {
2310         static EnumPropertyItem type_items[] = {
2311                 {SELECT, "SELECTED_OBJECTS", 0, "Selected Objects", ""},
2312                 {0, "ALL", 0, "All", ""},
2313                 {0, NULL, 0, NULL, NULL}};
2314
2315         /* identifiers */
2316         ot->name = "Make Single User";
2317         ot->description = "Make linked data local to each object";
2318         ot->idname = "OBJECT_OT_make_single_user";
2319
2320         /* api callbacks */
2321         ot->invoke = WM_menu_invoke;
2322         ot->exec = make_single_user_exec;
2323         ot->poll = ED_operator_objectmode;
2324
2325         /* flags */
2326         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2327
2328         /* properties */
2329         ot->prop = RNA_def_enum(ot->srna, "type", type_items, SELECT, "Type", "");
2330
2331         RNA_def_boolean(ot->srna, "object", 0, "Object", "Make single user objects");
2332         RNA_def_boolean(ot->srna, "obdata", 0, "Object Data", "Make single user object data");
2333         RNA_def_boolean(ot->srna, "material", 0, "Materials", "Make materials local to each datablock");
2334         RNA_def_boolean(ot->srna, "texture", 0, "Textures", "Make textures local to each material");
2335         RNA_def_boolean(ot->srna, "animation", 0, "Object Animation", "Make animation data local to each object");
2336 }
2337
2338 static int drop_named_material_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2339 {
2340         Base *base = ED_view3d_give_base_under_cursor(C, event->mval);
2341         Material *ma;
2342         char name[MAX_ID_NAME - 2];
2343         
2344         RNA_string_get(op->ptr, "name", name);
2345         ma = (Material *)BKE_libblock_find_name(ID_MA, name);
2346         if (base == NULL || ma == NULL)
2347                 return OPERATOR_CANCELLED;
2348         
2349         assign_material(base->object, ma, 1, BKE_MAT_ASSIGN_USERPREF);
2350         
2351         WM_event_add_notifier(C, NC_SPACE | ND_SPACE_VIEW3D, CTX_wm_view3d(C));
2352         WM_event_add_notifier(C, NC_MATERIAL | ND_SHADING_LINKS, ma);
2353         
2354         return OPERATOR_FINISHED;
2355 }
2356
2357 /* used for dropbox */
2358 /* assigns to object under cursor, only first material slot */
2359 void OBJECT_OT_drop_named_material(wmOperatorType *ot)
2360 {
2361
2362         /* identifiers */
2363         ot->name = "Drop Named Material on Object";
2364         ot->description = "";
2365         ot->idname = "OBJECT_OT_drop_named_material";
2366         
2367         /* api callbacks */
2368         ot->invoke = drop_named_material_invoke;
2369         ot->poll = ED_operator_objectmode;
2370         
2371         /* flags */
2372         ot->flag = OPTYPE_UNDO | OPTYPE_INTERNAL;
2373         
2374         /* properties */
2375         RNA_def_string(ot->srna, "name", "Material", MAX_ID_NAME - 2, "Name", "Material name to assign");
2376 }