Sync rna_access rna property update cow check with depsgraph
[blender.git] / source / blender / editors / object / object_add.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_add.c
27  *  \ingroup edobj
28  */
29
30
31 #include <stdlib.h>
32 #include <string.h>
33
34 #include "MEM_guardedalloc.h"
35
36 #include "DNA_anim_types.h"
37 #include "DNA_camera_types.h"
38 #include "DNA_curve_types.h"
39 #include "DNA_group_types.h"
40 #include "DNA_lamp_types.h"
41 #include "DNA_key_types.h"
42 #include "DNA_material_types.h"
43 #include "DNA_mesh_types.h"
44 #include "DNA_meta_types.h"
45 #include "DNA_object_fluidsim_types.h"
46 #include "DNA_object_force_types.h"
47 #include "DNA_object_types.h"
48 #include "DNA_lightprobe_types.h"
49 #include "DNA_scene_types.h"
50 #include "DNA_vfont_types.h"
51 #include "DNA_gpencil_types.h"
52
53 #include "BLI_utildefines.h"
54 #include "BLI_ghash.h"
55 #include "BLI_listbase.h"
56 #include "BLI_math.h"
57 #include "BLI_string.h"
58
59 #include "BLT_translation.h"
60
61 #include "BKE_action.h"
62 #include "BKE_anim.h"
63 #include "BKE_animsys.h"
64 #include "BKE_armature.h"
65 #include "BKE_camera.h"
66 #include "BKE_collection.h"
67 #include "BKE_context.h"
68 #include "BKE_constraint.h"
69 #include "BKE_curve.h"
70 #include "BKE_DerivedMesh.h"
71 #include "BKE_displist.h"
72 #include "BKE_effect.h"
73 #include "BKE_font.h"
74 #include "BKE_gpencil.h"
75 #include "BKE_lamp.h"
76 #include "BKE_lattice.h"
77 #include "BKE_layer.h"
78 #include "BKE_library.h"
79 #include "BKE_library_query.h"
80 #include "BKE_library_remap.h"
81 #include "BKE_key.h"
82 #include "BKE_main.h"
83 #include "BKE_material.h"
84 #include "BKE_mball.h"
85 #include "BKE_mesh.h"
86 #include "BKE_mesh_runtime.h"
87 #include "BKE_nla.h"
88 #include "BKE_object.h"
89 #include "BKE_particle.h"
90 #include "BKE_report.h"
91 #include "BKE_scene.h"
92 #include "BKE_screen.h"
93 #include "BKE_speaker.h"
94
95 #include "DEG_depsgraph.h"
96 #include "DEG_depsgraph_build.h"
97
98 #include "RNA_access.h"
99 #include "RNA_define.h"
100 #include "RNA_enum_types.h"
101
102 #include "WM_api.h"
103 #include "WM_types.h"
104
105 #include "ED_armature.h"
106 #include "ED_curve.h"
107 #include "ED_gpencil.h"
108 #include "ED_mball.h"
109 #include "ED_mesh.h"
110 #include "ED_node.h"
111 #include "ED_object.h"
112 #include "ED_physics.h"
113 #include "ED_render.h"
114 #include "ED_screen.h"
115 #include "ED_transform.h"
116 #include "ED_view3d.h"
117
118 #include "UI_resources.h"
119
120 #include "object_intern.h"
121
122 /* this is an exact copy of the define in rna_lamp.c
123  * kept here because of linking order.
124  * Icons are only defined here */
125 const EnumPropertyItem rna_enum_light_type_items[] = {
126         {LA_LOCAL, "POINT", ICON_LIGHT_POINT, "Point", "Omnidirectional point light source"},
127         {LA_SUN, "SUN", ICON_LIGHT_SUN, "Sun", "Constant direction parallel ray light source"},
128         {LA_SPOT, "SPOT", ICON_LIGHT_SPOT, "Spot", "Directional cone light source"},
129         {LA_HEMI, "HEMI", ICON_LIGHT_HEMI, "Hemi", "180 degree constant light source"},
130         {LA_AREA, "AREA", ICON_LIGHT_AREA, "Area", "Directional area light source"},
131         {0, NULL, 0, NULL, NULL}
132 };
133
134 /* copy from rna_object_force.c */
135 static const EnumPropertyItem field_type_items[] = {
136         {PFIELD_FORCE, "FORCE", ICON_FORCE_FORCE, "Force", ""},
137         {PFIELD_WIND, "WIND", ICON_FORCE_WIND, "Wind", ""},
138         {PFIELD_VORTEX, "VORTEX", ICON_FORCE_VORTEX, "Vortex", ""},
139         {PFIELD_MAGNET, "MAGNET", ICON_FORCE_MAGNETIC, "Magnetic", ""},
140         {PFIELD_HARMONIC, "HARMONIC", ICON_FORCE_HARMONIC, "Harmonic", ""},
141         {PFIELD_CHARGE, "CHARGE", ICON_FORCE_CHARGE, "Charge", ""},
142         {PFIELD_LENNARDJ, "LENNARDJ", ICON_FORCE_LENNARDJONES, "Lennard-Jones", ""},
143         {PFIELD_TEXTURE, "TEXTURE", ICON_FORCE_TEXTURE, "Texture", ""},
144         {PFIELD_GUIDE, "GUIDE", ICON_FORCE_CURVE, "Curve Guide", ""},
145         {PFIELD_BOID, "BOID", ICON_FORCE_BOID, "Boid", ""},
146         {PFIELD_TURBULENCE, "TURBULENCE", ICON_FORCE_TURBULENCE, "Turbulence", ""},
147         {PFIELD_DRAG, "DRAG", ICON_FORCE_DRAG, "Drag", ""},
148         {PFIELD_SMOKEFLOW, "SMOKE", ICON_FORCE_SMOKEFLOW, "Smoke Flow", ""},
149         {0, NULL, 0, NULL, NULL}
150 };
151
152 static EnumPropertyItem lightprobe_type_items[] = {
153         {LIGHTPROBE_TYPE_CUBE, "CUBEMAP", ICON_LIGHTPROBE_CUBEMAP, "Reflection Cubemap",
154      "Reflection probe with spherical or cubic attenuation"},
155         {LIGHTPROBE_TYPE_PLANAR, "PLANAR", ICON_LIGHTPROBE_PLANAR, "Reflection Plane",
156      "Planar reflection probe"},
157         {LIGHTPROBE_TYPE_GRID, "GRID", ICON_LIGHTPROBE_GRID, "Irradiance Volume",
158      "Irradiance probe to capture diffuse indirect lighting"},
159         {0, NULL, 0, NULL, NULL}
160 };
161
162 /************************** Exported *****************************/
163
164 void ED_object_location_from_view(bContext *C, float loc[3])
165 {
166         View3D *v3d = CTX_wm_view3d(C);
167         Scene *scene = CTX_data_scene(C);
168         const float *cursor;
169
170         cursor = ED_view3d_cursor3d_get(scene, v3d)->location;
171
172         copy_v3_v3(loc, cursor);
173 }
174
175 void ED_object_rotation_from_quat(float rot[3], const float viewquat[4], const char align_axis)
176 {
177         BLI_assert(align_axis >= 'X' && align_axis <= 'Z');
178
179         switch (align_axis) {
180                 case 'X':
181                 {
182                         /* Same as 'rv3d->viewinv[1]' */
183                         float axis_y[4] = {0.0f, 1.0f, 0.0f};
184                         float quat_y[4], quat[4];
185                         axis_angle_to_quat(quat_y, axis_y, M_PI_2);
186                         mul_qt_qtqt(quat, viewquat, quat_y);
187                         quat_to_eul(rot, quat);
188                         break;
189                 }
190                 case 'Y':
191                 {
192                         quat_to_eul(rot, viewquat);
193                         rot[0] -= (float)M_PI_2;
194                         break;
195                 }
196                 case 'Z':
197                 {
198                         quat_to_eul(rot, viewquat);
199                         break;
200                 }
201         }
202 }
203
204 void ED_object_rotation_from_view(bContext *C, float rot[3], const char align_axis)
205 {
206         RegionView3D *rv3d = CTX_wm_region_view3d(C);
207         BLI_assert(align_axis >= 'X' && align_axis <= 'Z');
208         if (rv3d) {
209                 float viewquat[4];
210                 copy_qt_qt(viewquat, rv3d->viewquat);
211                 viewquat[0] *= -1.0f;
212                 ED_object_rotation_from_quat(rot, viewquat, align_axis);
213         }
214         else {
215                 zero_v3(rot);
216         }
217 }
218
219 void ED_object_base_init_transform(bContext *C, Base *base, const float loc[3], const float rot[3])
220 {
221         Object *ob = base->object;
222         Scene *scene = CTX_data_scene(C);
223         Depsgraph *depsgraph = CTX_data_depsgraph(C);
224
225         if (!scene) return;
226
227         if (loc)
228                 copy_v3_v3(ob->loc, loc);
229
230         if (rot)
231                 copy_v3_v3(ob->rot, rot);
232
233         BKE_object_where_is_calc(depsgraph, scene, ob);
234 }
235
236 /* Uses context to figure out transform for primitive.
237  * Returns standard diameter. */
238 float ED_object_new_primitive_matrix(
239         bContext *C, Object *obedit,
240         const float loc[3], const float rot[3], float primmat[4][4])
241 {
242         Scene *scene = CTX_data_scene(C);
243         View3D *v3d = CTX_wm_view3d(C);
244         float mat[3][3], rmat[3][3], cmat[3][3], imat[3][3];
245
246         unit_m4(primmat);
247
248         eul_to_mat3(rmat, rot);
249         invert_m3(rmat);
250
251         /* inverse transform for initial rotation and object */
252         copy_m3_m4(mat, obedit->obmat);
253         mul_m3_m3m3(cmat, rmat, mat);
254         invert_m3_m3(imat, cmat);
255         copy_m4_m3(primmat, imat);
256
257         /* center */
258         copy_v3_v3(primmat[3], loc);
259         sub_v3_v3v3(primmat[3], primmat[3], obedit->obmat[3]);
260         invert_m3_m3(imat, mat);
261         mul_m3_v3(imat, primmat[3]);
262
263         {
264                 const float dia = v3d ? ED_view3d_grid_scale(scene, v3d, NULL) : ED_scene_grid_scale(scene, NULL);
265                 return dia;
266         }
267
268         // return 1.0f;
269 }
270
271 /********************* Add Object Operator ********************/
272
273 static void view_align_update(struct Main *UNUSED(main), struct Scene *UNUSED(scene), struct PointerRNA *ptr)
274 {
275         RNA_struct_idprops_unset(ptr, "rotation");
276 }
277
278 void ED_object_add_unit_props(wmOperatorType *ot)
279 {
280         RNA_def_float_distance(ot->srna, "radius", 1.0f, 0.0, OBJECT_ADD_SIZE_MAXF, "Radius", "", 0.001, 100.00);
281 }
282
283 void ED_object_add_generic_props(wmOperatorType *ot, bool do_editmode)
284 {
285         PropertyRNA *prop;
286
287         /* note: this property gets hidden for add-camera operator */
288         prop = RNA_def_boolean(ot->srna, "view_align", 0, "Align to View", "Align the new object to the view");
289         RNA_def_property_update_runtime(prop, view_align_update);
290
291         if (do_editmode) {
292                 prop = RNA_def_boolean(ot->srna, "enter_editmode", 0, "Enter Editmode",
293                                        "Enter editmode when adding this object");
294                 RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
295         }
296
297         prop = RNA_def_float_vector_xyz(ot->srna, "location", 3, NULL, -OBJECT_ADD_SIZE_MAXF, OBJECT_ADD_SIZE_MAXF,
298                                         "Location", "Location for the newly added object", -1000.0f, 1000.0f);
299         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
300         prop = RNA_def_float_rotation(ot->srna, "rotation", 3, NULL, -OBJECT_ADD_SIZE_MAXF, OBJECT_ADD_SIZE_MAXF,
301                                       "Rotation", "Rotation for the newly added object",
302                                       DEG2RADF(-360.0f), DEG2RADF(360.0f));
303         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
304
305         prop = RNA_def_boolean_layer_member(ot->srna, "layers", 20, NULL, "Layer", "");
306         RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
307 }
308
309 void ED_object_add_mesh_props(wmOperatorType *ot)
310 {
311         RNA_def_boolean(ot->srna, "calc_uvs", true, "Generate UVs", "Generate a default UV map");
312 }
313
314 bool ED_object_add_generic_get_opts(bContext *C, wmOperator *op, const char view_align_axis,
315                                     float loc[3], float rot[3],
316                                     bool *enter_editmode, unsigned int *layer, bool *is_view_aligned)
317 {
318         View3D *v3d = CTX_wm_view3d(C);
319         unsigned int _layer;
320         PropertyRNA *prop;
321
322         /* Switch to Edit mode? optional prop */
323         if ((prop = RNA_struct_find_property(op->ptr, "enter_editmode"))) {
324                 bool _enter_editmode;
325                 if (!enter_editmode)
326                         enter_editmode = &_enter_editmode;
327
328                 if (RNA_property_is_set(op->ptr, prop) && enter_editmode)
329                         *enter_editmode = RNA_property_boolean_get(op->ptr, prop);
330                 else {
331                         *enter_editmode = (U.flag & USER_ADD_EDITMODE) != 0;
332                         RNA_property_boolean_set(op->ptr, prop, *enter_editmode);
333                 }
334         }
335
336         /* Get layers! */
337         {
338                 int a;
339                 bool layer_values[20];
340                 if (!layer)
341                         layer = &_layer;
342
343                 prop = RNA_struct_find_property(op->ptr, "layers");
344                 if (RNA_property_is_set(op->ptr, prop)) {
345                         RNA_property_boolean_get_array(op->ptr, prop, layer_values);
346                         *layer = 0;
347                         for (a = 0; a < 20; a++) {
348                                 if (layer_values[a])
349                                         *layer |= (1 << a);
350                         }
351                 }
352                 else {
353                         Scene *scene = CTX_data_scene(C);
354                         *layer = BKE_screen_view3d_layer_active_ex(v3d, scene, false);
355                         for (a = 0; a < 20; a++) {
356                                 layer_values[a] = (*layer & (1 << a)) != 0;
357                         }
358                         RNA_property_boolean_set_array(op->ptr, prop, layer_values);
359                 }
360
361                 /* in local view we additionally add local view layers,
362                  * not part of operator properties */
363                 if (v3d && v3d->localvd)
364                         *layer |= v3d->lay;
365         }
366
367         /* Location! */
368         {
369                 float _loc[3];
370                 if (!loc)
371                         loc = _loc;
372
373                 if (RNA_struct_property_is_set(op->ptr, "location")) {
374                         RNA_float_get_array(op->ptr, "location", loc);
375                 }
376                 else {
377                         ED_object_location_from_view(C, loc);
378                         RNA_float_set_array(op->ptr, "location", loc);
379                 }
380         }
381
382         /* Rotation! */
383         {
384                 bool _is_view_aligned;
385                 float _rot[3];
386                 if (!is_view_aligned)
387                         is_view_aligned = &_is_view_aligned;
388                 if (!rot)
389                         rot = _rot;
390
391                 if (RNA_struct_property_is_set(op->ptr, "rotation"))
392                         *is_view_aligned = false;
393                 else if (RNA_struct_property_is_set(op->ptr, "view_align"))
394                         *is_view_aligned = RNA_boolean_get(op->ptr, "view_align");
395                 else {
396                         *is_view_aligned = (U.flag & USER_ADD_VIEWALIGNED) != 0;
397                         RNA_boolean_set(op->ptr, "view_align", *is_view_aligned);
398                 }
399
400                 if (*is_view_aligned) {
401                         ED_object_rotation_from_view(C, rot, view_align_axis);
402                         RNA_float_set_array(op->ptr, "rotation", rot);
403                 }
404                 else
405                         RNA_float_get_array(op->ptr, "rotation", rot);
406         }
407
408         if (layer && *layer == 0) {
409                 BKE_report(op->reports, RPT_ERROR, "Property 'layer' has no values set");
410                 return false;
411         }
412
413         return true;
414 }
415
416 /* For object add primitive operators.
417  * Do not call undo push in this function (users of this function have to). */
418 Object *ED_object_add_type(
419         bContext *C,
420         int type, const char *name,
421         const float loc[3], const float rot[3],
422         bool enter_editmode, unsigned int UNUSED(layer))
423 {
424         Main *bmain = CTX_data_main(C);
425         Scene *scene = CTX_data_scene(C);
426         ViewLayer *view_layer = CTX_data_view_layer(C);
427         Object *ob;
428
429         /* for as long scene has editmode... */
430         if (CTX_data_edit_object(C)) {
431                 ED_object_editmode_exit(C, EM_FREEDATA | EM_WAITCURSOR);
432         }
433
434         /* deselects all, sets scene->basact */
435         ob = BKE_object_add(bmain, scene, view_layer, type, name);
436         /* editor level activate, notifiers */
437         ED_object_base_activate(C, view_layer->basact);
438
439         /* more editor stuff */
440         ED_object_base_init_transform(C, view_layer->basact, loc, rot);
441
442         /* TODO(sergey): This is weird to manually tag objects for update, better to
443          * use DEG_id_tag_update here perhaps.
444          */
445         DEG_id_type_tag(bmain, ID_OB);
446         DEG_relations_tag_update(bmain);
447         if (ob->data != NULL) {
448                 DEG_id_tag_update_ex(bmain, (ID *)ob->data, DEG_TAG_EDITORS_UPDATE);
449         }
450
451         if (enter_editmode)
452                 ED_object_editmode_enter(C, EM_IGNORE_LAYER);
453
454         WM_event_add_notifier(C, NC_SCENE | ND_LAYER_CONTENT, scene);
455
456         /* TODO(sergey): Use proper flag for tagging here. */
457         DEG_id_tag_update(&scene->id, 0);
458
459         return ob;
460 }
461
462 /* for object add operator */
463 static int object_add_exec(bContext *C, wmOperator *op)
464 {
465         Object *ob;
466         bool enter_editmode;
467         unsigned int layer;
468         float loc[3], rot[3], radius;
469
470         WM_operator_view3d_unit_defaults(C, op);
471         if (!ED_object_add_generic_get_opts(C, op, 'Z', loc, rot, &enter_editmode, &layer, NULL))
472                 return OPERATOR_CANCELLED;
473
474         radius = RNA_float_get(op->ptr, "radius");
475         ob = ED_object_add_type(C, RNA_enum_get(op->ptr, "type"), NULL, loc, rot, enter_editmode, layer);
476
477         if (ob->type == OB_LATTICE) {
478                 /* lattice is a special case!
479                  * we never want to scale the obdata since that is the rest-state */
480                 copy_v3_fl(ob->size, radius);
481         }
482         else {
483                 BKE_object_obdata_size_init(ob, radius);
484         }
485
486         return OPERATOR_FINISHED;
487 }
488
489 void OBJECT_OT_add(wmOperatorType *ot)
490 {
491         /* identifiers */
492         ot->name = "Add Object";
493         ot->description = "Add an object to the scene";
494         ot->idname = "OBJECT_OT_add";
495
496         /* api callbacks */
497         ot->exec = object_add_exec;
498         ot->poll = ED_operator_objectmode;
499
500         /* flags */
501         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
502
503         /* properties */
504         ED_object_add_unit_props(ot);
505         RNA_def_enum(ot->srna, "type", rna_enum_object_type_items, 0, "Type", "");
506
507         ED_object_add_generic_props(ot, true);
508 }
509
510 /********************** Add Probe Operator **********************/
511
512 /* for object add operator */
513 static int lightprobe_add_exec(bContext *C, wmOperator *op)
514 {
515         Object *ob;
516         LightProbe *probe;
517         int type;
518         bool enter_editmode;
519         unsigned int layer;
520         float loc[3], rot[3];
521         float radius;
522
523         WM_operator_view3d_unit_defaults(C, op);
524         if (!ED_object_add_generic_get_opts(C, op, 'Z', loc, rot, &enter_editmode, &layer, NULL))
525                 return OPERATOR_CANCELLED;
526
527         type = RNA_enum_get(op->ptr, "type");
528         radius = RNA_float_get(op->ptr, "radius");
529
530         const char *name = CTX_DATA_(BLT_I18NCONTEXT_ID_OBJECT, "Light Probe");
531         ob = ED_object_add_type(C, OB_LIGHTPROBE, name, loc, rot, false, layer);
532         BKE_object_obdata_size_init(ob, radius);
533
534         probe = (LightProbe *)ob->data;
535         probe->type = type;
536
537         switch (type) {
538                 case LIGHTPROBE_TYPE_GRID:
539                         probe->distinf = 0.3f;
540                         probe->falloff = 1.0f;
541                         probe->clipsta = 0.01f;
542                         break;
543                 case LIGHTPROBE_TYPE_PLANAR:
544                         probe->distinf = 0.1f;
545                         probe->falloff = 0.5f;
546                         probe->clipsta = 0.001f;
547                         ob->empty_drawsize = 0.5f;
548                         break;
549                 case LIGHTPROBE_TYPE_CUBE:
550                         probe->attenuation_type = LIGHTPROBE_SHAPE_ELIPSOID;
551                         break;
552                 default:
553                         BLI_assert(!"Lightprobe type not configured.");
554                         break;
555         }
556
557         DEG_relations_tag_update(CTX_data_main(C));
558
559         return OPERATOR_FINISHED;
560 }
561
562 void OBJECT_OT_lightprobe_add(wmOperatorType *ot)
563 {
564         /* identifiers */
565         ot->name = "Add Light Probe";
566         ot->description = "Add a light probe object";
567         ot->idname = "OBJECT_OT_lightprobe_add";
568
569         /* api callbacks */
570         ot->exec = lightprobe_add_exec;
571         ot->poll = ED_operator_objectmode;
572
573         /* flags */
574         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
575
576         /* properties */
577         ot->prop = RNA_def_enum(ot->srna, "type", lightprobe_type_items, 0, "Type", "");
578
579         ED_object_add_unit_props(ot);
580         ED_object_add_generic_props(ot, true);
581 }
582
583 /********************* Add Effector Operator ********************/
584
585 /* for object add operator */
586 static int effector_add_exec(bContext *C, wmOperator *op)
587 {
588         Object *ob;
589         int type;
590         bool enter_editmode;
591         unsigned int layer;
592         float loc[3], rot[3];
593         float mat[4][4];
594         float dia;
595
596         WM_operator_view3d_unit_defaults(C, op);
597         if (!ED_object_add_generic_get_opts(C, op, 'Z', loc, rot, &enter_editmode, &layer, NULL))
598                 return OPERATOR_CANCELLED;
599
600         type = RNA_enum_get(op->ptr, "type");
601         dia = RNA_float_get(op->ptr, "radius");
602
603         if (type == PFIELD_GUIDE) {
604                 Curve *cu;
605                 const char *name = CTX_DATA_(BLT_I18NCONTEXT_ID_OBJECT, "CurveGuide");
606                 ob = ED_object_add_type(C, OB_CURVE, name, loc, rot, false, layer);
607
608                 cu = ob->data;
609                 cu->flag |= CU_PATH | CU_3D;
610                 ED_object_editmode_enter(C, 0);
611                 ED_object_new_primitive_matrix(C, ob, loc, rot, mat);
612                 BLI_addtail(&cu->editnurb->nurbs, ED_curve_add_nurbs_primitive(C, ob, mat, CU_NURBS | CU_PRIM_PATH, dia));
613                 if (!enter_editmode)
614                         ED_object_editmode_exit(C, EM_FREEDATA);
615         }
616         else {
617                 const char *name = CTX_DATA_(BLT_I18NCONTEXT_ID_OBJECT, "Field");
618                 ob = ED_object_add_type(C, OB_EMPTY, name, loc, rot, false, layer);
619                 BKE_object_obdata_size_init(ob, dia);
620                 if (ELEM(type, PFIELD_WIND, PFIELD_VORTEX))
621                         ob->empty_drawtype = OB_SINGLE_ARROW;
622         }
623
624         ob->pd = object_add_collision_fields(type);
625
626         DEG_relations_tag_update(CTX_data_main(C));
627
628         return OPERATOR_FINISHED;
629 }
630
631 void OBJECT_OT_effector_add(wmOperatorType *ot)
632 {
633         /* identifiers */
634         ot->name = "Add Effector";
635         ot->description = "Add an empty object with a physics effector to the scene";
636         ot->idname = "OBJECT_OT_effector_add";
637
638         /* api callbacks */
639         ot->exec = effector_add_exec;
640         ot->poll = ED_operator_objectmode;
641
642         /* flags */
643         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
644
645         /* properties */
646         ot->prop = RNA_def_enum(ot->srna, "type", field_type_items, 0, "Type", "");
647
648         ED_object_add_unit_props(ot);
649         ED_object_add_generic_props(ot, true);
650 }
651
652 /********************* Add Camera Operator ********************/
653
654 static int object_camera_add_exec(bContext *C, wmOperator *op)
655 {
656         View3D *v3d = CTX_wm_view3d(C);
657         Scene *scene = CTX_data_scene(C);
658         Object *ob;
659         Camera *cam;
660         bool enter_editmode;
661         unsigned int layer;
662         float loc[3], rot[3];
663
664         /* force view align for cameras */
665         RNA_boolean_set(op->ptr, "view_align", true);
666
667         if (!ED_object_add_generic_get_opts(C, op, 'Z', loc, rot, &enter_editmode, &layer, NULL))
668                 return OPERATOR_CANCELLED;
669
670         ob = ED_object_add_type(C, OB_CAMERA, NULL, loc, rot, false, layer);
671
672         if (v3d) {
673                 if (v3d->camera == NULL)
674                         v3d->camera = ob;
675                 if (v3d->scenelock && scene->camera == NULL) {
676                         scene->camera = ob;
677                 }
678         }
679
680         cam = ob->data;
681         cam->drawsize = v3d ? ED_view3d_grid_scale(scene, v3d, NULL) : ED_scene_grid_scale(scene, NULL);
682
683         return OPERATOR_FINISHED;
684 }
685
686 void OBJECT_OT_camera_add(wmOperatorType *ot)
687 {
688         PropertyRNA *prop;
689
690         /* identifiers */
691         ot->name = "Add Camera";
692         ot->description = "Add a camera object to the scene";
693         ot->idname = "OBJECT_OT_camera_add";
694
695         /* api callbacks */
696         ot->exec = object_camera_add_exec;
697         ot->poll = ED_operator_objectmode;
698
699         /* flags */
700         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
701
702         ED_object_add_generic_props(ot, true);
703
704         /* hide this for cameras, default */
705         prop = RNA_struct_type_find_property(ot->srna, "view_align");
706         RNA_def_property_flag(prop, PROP_HIDDEN);
707 }
708
709
710 /********************* Add Metaball Operator ********************/
711
712 static int object_metaball_add_exec(bContext *C, wmOperator *op)
713 {
714         Object *obedit = CTX_data_edit_object(C);
715         bool newob = false;
716         bool enter_editmode;
717         unsigned int layer;
718         float loc[3], rot[3];
719         float mat[4][4];
720         float dia;
721
722         WM_operator_view3d_unit_defaults(C, op);
723         if (!ED_object_add_generic_get_opts(C, op, 'Z', loc, rot, &enter_editmode, &layer, NULL))
724                 return OPERATOR_CANCELLED;
725
726         if (obedit == NULL || obedit->type != OB_MBALL) {
727                 obedit = ED_object_add_type(C, OB_MBALL, NULL, loc, rot, true, layer);
728                 newob = true;
729         }
730         else {
731                 DEG_id_tag_update(&obedit->id, OB_RECALC_DATA);
732         }
733
734         ED_object_new_primitive_matrix(C, obedit, loc, rot, mat);
735         dia = RNA_float_get(op->ptr, "radius");
736
737         ED_mball_add_primitive(C, obedit, mat, dia, RNA_enum_get(op->ptr, "type"));
738
739         /* userdef */
740         if (newob && !enter_editmode) {
741                 ED_object_editmode_exit(C, EM_FREEDATA);
742         }
743
744         WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, obedit);
745
746         return OPERATOR_FINISHED;
747 }
748
749 void OBJECT_OT_metaball_add(wmOperatorType *ot)
750 {
751         /* identifiers */
752         ot->name = "Add Metaball";
753         ot->description = "Add an metaball object to the scene";
754         ot->idname = "OBJECT_OT_metaball_add";
755
756         /* api callbacks */
757         ot->invoke = WM_menu_invoke;
758         ot->exec = object_metaball_add_exec;
759         ot->poll = ED_operator_scene_editable;
760
761         /* flags */
762         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
763
764         ot->prop = RNA_def_enum(ot->srna, "type", rna_enum_metaelem_type_items, 0, "Primitive", "");
765
766         ED_object_add_unit_props(ot);
767         ED_object_add_generic_props(ot, true);
768 }
769
770 /********************* Add Text Operator ********************/
771
772 static int object_add_text_exec(bContext *C, wmOperator *op)
773 {
774         Object *obedit = CTX_data_edit_object(C);
775         bool enter_editmode;
776         unsigned int layer;
777         float loc[3], rot[3];
778
779         WM_operator_view3d_unit_defaults(C, op);
780         if (!ED_object_add_generic_get_opts(C, op, 'Z', loc, rot, &enter_editmode, &layer, NULL))
781                 return OPERATOR_CANCELLED;
782
783         if (obedit && obedit->type == OB_FONT)
784                 return OPERATOR_CANCELLED;
785
786         obedit = ED_object_add_type(C, OB_FONT, NULL, loc, rot, enter_editmode, layer);
787         BKE_object_obdata_size_init(obedit, RNA_float_get(op->ptr, "radius"));
788
789         WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, obedit);
790
791         return OPERATOR_FINISHED;
792 }
793
794 void OBJECT_OT_text_add(wmOperatorType *ot)
795 {
796         /* identifiers */
797         ot->name = "Add Text";
798         ot->description = "Add a text object to the scene";
799         ot->idname = "OBJECT_OT_text_add";
800
801         /* api callbacks */
802         ot->exec = object_add_text_exec;
803         ot->poll = ED_operator_objectmode;
804
805         /* flags */
806         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
807
808         /* properties */
809         ED_object_add_unit_props(ot);
810         ED_object_add_generic_props(ot, true);
811 }
812
813 /********************* Add Armature Operator ********************/
814
815 static int object_armature_add_exec(bContext *C, wmOperator *op)
816 {
817         Object *obedit = CTX_data_edit_object(C);
818         RegionView3D *rv3d = CTX_wm_region_view3d(C);
819         bool newob = false;
820         bool enter_editmode;
821         unsigned int layer;
822         float loc[3], rot[3], dia;
823         bool view_aligned = rv3d && (U.flag & USER_ADD_VIEWALIGNED);
824
825         WM_operator_view3d_unit_defaults(C, op);
826         if (!ED_object_add_generic_get_opts(C, op, 'Z', loc, rot, &enter_editmode, &layer, NULL))
827                 return OPERATOR_CANCELLED;
828
829         if ((obedit == NULL) || (obedit->type != OB_ARMATURE)) {
830                 obedit = ED_object_add_type(C, OB_ARMATURE, NULL, loc, rot, true, layer);
831                 ED_object_editmode_enter(C, 0);
832                 newob = true;
833         }
834         else {
835                 DEG_id_tag_update(&obedit->id, OB_RECALC_DATA);
836         }
837
838         if (obedit == NULL) {
839                 BKE_report(op->reports, RPT_ERROR, "Cannot create editmode armature");
840                 return OPERATOR_CANCELLED;
841         }
842
843         dia = RNA_float_get(op->ptr, "radius");
844         ED_armature_ebone_add_primitive(obedit, dia, view_aligned);
845
846         /* userdef */
847         if (newob && !enter_editmode)
848                 ED_object_editmode_exit(C, EM_FREEDATA);
849
850         WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, obedit);
851
852         return OPERATOR_FINISHED;
853 }
854
855 void OBJECT_OT_armature_add(wmOperatorType *ot)
856 {
857         /* identifiers */
858         ot->name = "Add Armature";
859         ot->description = "Add an armature object to the scene";
860         ot->idname = "OBJECT_OT_armature_add";
861
862         /* api callbacks */
863         ot->exec = object_armature_add_exec;
864         ot->poll = ED_operator_objectmode;
865
866         /* flags */
867         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
868
869         /* properties */
870         ED_object_add_unit_props(ot);
871         ED_object_add_generic_props(ot, true);
872 }
873
874 /********************* Add Empty Operator ********************/
875
876 static int object_empty_add_exec(bContext *C, wmOperator *op)
877 {
878         Object *ob;
879         int type = RNA_enum_get(op->ptr, "type");
880         unsigned int layer;
881         float loc[3], rot[3];
882
883         WM_operator_view3d_unit_defaults(C, op);
884         if (!ED_object_add_generic_get_opts(C, op, 'Z', loc, rot, NULL, &layer, NULL))
885                 return OPERATOR_CANCELLED;
886
887         ob = ED_object_add_type(C, OB_EMPTY, NULL, loc, rot, false, layer);
888
889         BKE_object_empty_draw_type_set(ob, type);
890         BKE_object_obdata_size_init(ob, RNA_float_get(op->ptr, "radius"));
891
892         return OPERATOR_FINISHED;
893 }
894
895 void OBJECT_OT_empty_add(wmOperatorType *ot)
896 {
897         /* identifiers */
898         ot->name = "Add Empty";
899         ot->description = "Add an empty object to the scene";
900         ot->idname = "OBJECT_OT_empty_add";
901
902         /* api callbacks */
903         ot->invoke = WM_menu_invoke;
904         ot->exec = object_empty_add_exec;
905         ot->poll = ED_operator_objectmode;
906
907         /* flags */
908         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
909
910         /* properties */
911         ot->prop = RNA_def_enum(ot->srna, "type", rna_enum_object_empty_drawtype_items, 0, "Type", "");
912
913         ED_object_add_unit_props(ot);
914         ED_object_add_generic_props(ot, false);
915 }
916
917 static int empty_drop_named_image_invoke(bContext *C, wmOperator *op, const wmEvent *event)
918 {
919         Scene *scene = CTX_data_scene(C);
920
921         Base *base = NULL;
922         Image *ima = NULL;
923         Object *ob = NULL;
924
925         ima = (Image *)WM_operator_drop_load_path(C, op, ID_IM);
926         if (!ima) {
927                 return OPERATOR_CANCELLED;
928         }
929         /* handled below */
930         id_us_min((ID *)ima);
931
932         base = ED_view3d_give_base_under_cursor(C, event->mval);
933
934         /* if empty under cursor, then set object */
935         if (base && base->object->type == OB_EMPTY) {
936                 ob = base->object;
937                 DEG_id_tag_update(&scene->id, DEG_TAG_SELECT_UPDATE);
938                 WM_event_add_notifier(C, NC_SCENE | ND_OB_ACTIVE, scene);
939         }
940         else {
941                 /* add new empty */
942                 unsigned int layer;
943                 float rot[3];
944
945                 if (!ED_object_add_generic_get_opts(C, op, 'Z', NULL, rot, NULL, &layer, NULL))
946                         return OPERATOR_CANCELLED;
947
948                 ob = ED_object_add_type(C, OB_EMPTY, NULL, NULL, rot, false, layer);
949
950                 /* add under the mouse */
951                 ED_object_location_from_view(C, ob->loc);
952                 ED_view3d_cursor3d_position(C, event->mval, false, ob->loc);
953         }
954
955         BKE_object_empty_draw_type_set(ob, OB_EMPTY_IMAGE);
956
957         id_us_min(ob->data);
958         ob->data = ima;
959         id_us_plus(ob->data);
960
961         return OPERATOR_FINISHED;
962 }
963
964 void OBJECT_OT_drop_named_image(wmOperatorType *ot)
965 {
966         PropertyRNA *prop;
967
968         /* identifiers */
969         ot->name = "Add Empty Image/Drop Image To Empty";
970         ot->description = "Add an empty image type to scene with data";
971         ot->idname = "OBJECT_OT_drop_named_image";
972
973         /* api callbacks */
974         ot->invoke = empty_drop_named_image_invoke;
975         ot->poll = ED_operator_objectmode;
976
977         /* flags */
978         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
979
980         /* properties */
981         prop = RNA_def_string(ot->srna, "filepath", NULL, FILE_MAX, "Filepath", "Path to image file");
982         RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
983         RNA_def_boolean(ot->srna, "relative_path", true, "Relative Path", "Select the file relative to the blend file");
984         RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
985         prop = RNA_def_string(ot->srna, "name", NULL, MAX_ID_NAME - 2, "Name", "Image name to assign");
986         RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
987         ED_object_add_generic_props(ot, false);
988 }
989
990 /********************* Add Gpencil Operator ********************/
991
992 static int object_gpencil_add_exec(bContext *C, wmOperator *op)
993 {
994         Object *ob = CTX_data_active_object(C);
995         bGPdata *gpd = (ob && (ob->type == OB_GPENCIL)) ? ob->data : NULL;
996
997         const int type = RNA_enum_get(op->ptr, "type");
998
999         float loc[3], rot[3];
1000         unsigned int layer;
1001         bool newob = false;
1002
1003         /* Hack: Force view-align to be on by default
1004          * since it's not nice for adding shapes in 2D
1005          * for them to end up aligned oddly, but only for Monkey
1006          */
1007         if ((RNA_struct_property_is_set(op->ptr, "view_align") == false) &&
1008             (type == GP_MONKEY))
1009         {
1010                 RNA_boolean_set(op->ptr, "view_align", true);
1011         }
1012
1013         /* Note: We use 'Y' here (not 'Z'), as */
1014         WM_operator_view3d_unit_defaults(C, op);
1015         if (!ED_object_add_generic_get_opts(C, op, 'Y', loc, rot, NULL, &layer, NULL))
1016                 return OPERATOR_CANCELLED;
1017
1018         /* add new object if not currently editing a GP object,
1019          * or if "empty" was chosen (i.e. user wants a blank GP canvas)
1020          */
1021         if ((gpd == NULL) || (GPENCIL_ANY_MODE(gpd) == false) || (type == GP_EMPTY)) {
1022                 const char *ob_name = (type == GP_MONKEY) ? "Suzanne" : NULL;
1023                 float radius = RNA_float_get(op->ptr, "radius");
1024
1025                 ob = ED_object_add_type(C, OB_GPENCIL, ob_name, loc, rot, true, layer);
1026                 gpd = ob->data;
1027                 newob = true;
1028
1029                 BKE_object_obdata_size_init(ob, GP_OBGPENCIL_DEFAULT_SIZE * radius);
1030         }
1031         else {
1032                 DEG_id_tag_update(&ob->id, OB_RECALC_DATA);
1033                 WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_ADDED, NULL);
1034         }
1035
1036         /* create relevant geometry */
1037         switch (type) {
1038                 case GP_STROKE:
1039                 {
1040                         float radius = RNA_float_get(op->ptr, "radius");
1041                         float mat[4][4];
1042
1043                         ED_object_new_primitive_matrix(C, ob, loc, rot, mat);
1044                         mul_v3_fl(mat[0], radius);
1045                         mul_v3_fl(mat[1], radius);
1046                         mul_v3_fl(mat[2], radius);
1047
1048                         ED_gpencil_create_stroke(C, mat);
1049                         break;
1050                 }
1051                 case GP_MONKEY:
1052                 {
1053                         float radius = RNA_float_get(op->ptr, "radius");
1054                         float mat[4][4];
1055
1056                         ED_object_new_primitive_matrix(C, ob, loc, rot, mat);
1057                         mul_v3_fl(mat[0], radius);
1058                         mul_v3_fl(mat[1], radius);
1059                         mul_v3_fl(mat[2], radius);
1060
1061                         ED_gpencil_create_monkey(C, mat);
1062                         break;
1063                 }
1064                 case GP_EMPTY:
1065                         /* do nothing */
1066                         break;
1067
1068                 default:
1069                         BKE_report(op->reports, RPT_WARNING, "Not implemented");
1070                         break;
1071         }
1072
1073         /* if this is a new object, initialise default stuff (colors, etc.) */
1074         if (newob) {
1075                 ED_gpencil_add_defaults(C);
1076         }
1077
1078         return OPERATOR_FINISHED;
1079 }
1080
1081 void OBJECT_OT_gpencil_add(wmOperatorType *ot)
1082 {
1083         /* identifiers */
1084         ot->name = "Add GPencil";
1085         ot->description = "Add a grease pencil object to the scene";
1086         ot->idname = "OBJECT_OT_gpencil_add";
1087
1088         /* api callbacks */
1089         ot->invoke = WM_menu_invoke;
1090         ot->exec = object_gpencil_add_exec;
1091         ot->poll = ED_operator_scene_editable;
1092
1093         /* flags */
1094         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1095
1096         /* properties */
1097         ED_object_add_unit_props(ot);
1098         ED_object_add_generic_props(ot, false);
1099
1100         ot->prop = RNA_def_enum(ot->srna, "type", rna_enum_object_gpencil_type_items, 0, "Type", "");
1101 }
1102
1103 /********************* Add Light Operator ********************/
1104
1105 static const char *get_light_defname(int type)
1106 {
1107         switch (type) {
1108                 case LA_LOCAL: return CTX_DATA_(BLT_I18NCONTEXT_ID_LAMP, "Point");
1109                 case LA_SUN: return CTX_DATA_(BLT_I18NCONTEXT_ID_LAMP, "Sun");
1110                 case LA_SPOT: return CTX_DATA_(BLT_I18NCONTEXT_ID_LAMP, "Spot");
1111                 case LA_HEMI: return CTX_DATA_(BLT_I18NCONTEXT_ID_LAMP, "Hemi");
1112                 case LA_AREA: return CTX_DATA_(BLT_I18NCONTEXT_ID_LAMP, "Area");
1113                 default:
1114                         return CTX_DATA_(BLT_I18NCONTEXT_ID_LAMP, "Light");
1115         }
1116 }
1117
1118 static int object_light_add_exec(bContext *C, wmOperator *op)
1119 {
1120         Scene *scene = CTX_data_scene(C);
1121         Object *ob;
1122         Lamp *la;
1123         int type = RNA_enum_get(op->ptr, "type");
1124         unsigned int layer;
1125         float loc[3], rot[3];
1126
1127         WM_operator_view3d_unit_defaults(C, op);
1128         if (!ED_object_add_generic_get_opts(C, op, 'Z', loc, rot, NULL, &layer, NULL))
1129                 return OPERATOR_CANCELLED;
1130
1131         ob = ED_object_add_type(C, OB_LAMP, get_light_defname(type), loc, rot, false, layer);
1132
1133         float size = RNA_float_get(op->ptr, "radius");
1134         /* Better defaults for light size. */
1135         switch (type) {
1136                 case LA_LOCAL:
1137                 case LA_SPOT:
1138                         break;
1139                 case LA_AREA:
1140                         size *= 4.0f;
1141                         break;
1142                 default:
1143                         size *= 0.5f;
1144                         break;
1145         }
1146         BKE_object_obdata_size_init(ob, size);
1147
1148         la = (Lamp *)ob->data;
1149         la->type = type;
1150
1151         if (BKE_scene_uses_cycles(scene)) {
1152                 ED_node_shader_default(C, &la->id);
1153                 la->use_nodes = true;
1154         }
1155
1156         return OPERATOR_FINISHED;
1157 }
1158
1159 void OBJECT_OT_light_add(wmOperatorType *ot)
1160 {
1161         /* identifiers */
1162         ot->name = "Add Light";
1163         ot->description = "Add a light object to the scene";
1164         ot->idname = "OBJECT_OT_light_add";
1165
1166         /* api callbacks */
1167         ot->invoke = WM_menu_invoke;
1168         ot->exec = object_light_add_exec;
1169         ot->poll = ED_operator_objectmode;
1170
1171         /* flags */
1172         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1173
1174         /* properties */
1175         ot->prop = RNA_def_enum(ot->srna, "type", rna_enum_light_type_items, 0, "Type", "");
1176         RNA_def_property_translation_context(ot->prop, BLT_I18NCONTEXT_ID_LAMP);
1177
1178         ED_object_add_unit_props(ot);
1179         ED_object_add_generic_props(ot, false);
1180 }
1181
1182 /********************* Add Collection Instance Operator ********************/
1183
1184 static int collection_instance_add_exec(bContext *C, wmOperator *op)
1185 {
1186         Main *bmain = CTX_data_main(C);
1187         Collection *collection;
1188         unsigned int layer;
1189         float loc[3], rot[3];
1190
1191         if (RNA_struct_property_is_set(op->ptr, "name")) {
1192                 char name[MAX_ID_NAME - 2];
1193
1194                 RNA_string_get(op->ptr, "name", name);
1195                 collection = (Collection *)BKE_libblock_find_name(bmain, ID_GR, name);
1196
1197                 if (0 == RNA_struct_property_is_set(op->ptr, "location")) {
1198                         const wmEvent *event = CTX_wm_window(C)->eventstate;
1199                         ARegion *ar = CTX_wm_region(C);
1200                         const int mval[2] = {event->x - ar->winrct.xmin,
1201                                              event->y - ar->winrct.ymin};
1202                         ED_object_location_from_view(C, loc);
1203                         ED_view3d_cursor3d_position(C, mval, false, loc);
1204                         RNA_float_set_array(op->ptr, "location", loc);
1205                 }
1206         }
1207         else
1208                 collection = BLI_findlink(&CTX_data_main(C)->collection, RNA_enum_get(op->ptr, "collection"));
1209
1210         if (!ED_object_add_generic_get_opts(C, op, 'Z', loc, rot, NULL, &layer, NULL))
1211                 return OPERATOR_CANCELLED;
1212
1213         if (collection) {
1214                 Scene *scene = CTX_data_scene(C);
1215                 ViewLayer *view_layer = CTX_data_view_layer(C);
1216
1217                 /* Avoid dependency cycles. */
1218                 LayerCollection *active_lc = BKE_layer_collection_get_active(view_layer);
1219                 while (BKE_collection_find_cycle(active_lc->collection, collection)) {
1220                         active_lc = BKE_layer_collection_activate_parent(view_layer, active_lc);
1221                 }
1222
1223                 Object *ob = ED_object_add_type(C, OB_EMPTY, collection->id.name + 2, loc, rot, false, layer);
1224                 ob->dup_group = collection;
1225                 ob->transflag |= OB_DUPLICOLLECTION;
1226                 id_us_plus(&collection->id);
1227
1228                 /* works without this except if you try render right after, see: 22027 */
1229                 DEG_relations_tag_update(bmain);
1230                 DEG_id_tag_update(&scene->id, DEG_TAG_SELECT_UPDATE);
1231                 WM_event_add_notifier(C, NC_SCENE | ND_OB_ACTIVE, scene);
1232
1233                 return OPERATOR_FINISHED;
1234         }
1235
1236         return OPERATOR_CANCELLED;
1237 }
1238
1239 /* only used as menu */
1240 void OBJECT_OT_collection_instance_add(wmOperatorType *ot)
1241 {
1242         PropertyRNA *prop;
1243
1244         /* identifiers */
1245         ot->name = "Add Collection Instance";
1246         ot->description = "Add a collection instance";
1247         ot->idname = "OBJECT_OT_collection_instance_add";
1248
1249         /* api callbacks */
1250         ot->invoke = WM_enum_search_invoke;
1251         ot->exec = collection_instance_add_exec;
1252         ot->poll = ED_operator_objectmode;
1253
1254         /* flags */
1255         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1256
1257         /* properties */
1258         RNA_def_string(ot->srna, "name", "Collection", MAX_ID_NAME - 2, "Name", "Collection name to add");
1259         prop = RNA_def_enum(ot->srna, "collection", DummyRNA_NULL_items, 0, "Collection", "");
1260         RNA_def_enum_funcs(prop, RNA_collection_itemf);
1261         RNA_def_property_flag(prop, PROP_ENUM_NO_TRANSLATE);
1262         ot->prop = prop;
1263         ED_object_add_generic_props(ot, false);
1264 }
1265
1266 /********************* Add Speaker Operator ********************/
1267
1268 static int object_speaker_add_exec(bContext *C, wmOperator *op)
1269 {
1270         Object *ob;
1271         unsigned int layer;
1272         float loc[3], rot[3];
1273         Scene *scene = CTX_data_scene(C);
1274
1275         if (!ED_object_add_generic_get_opts(C, op, 'Z', loc, rot, NULL, &layer, NULL))
1276                 return OPERATOR_CANCELLED;
1277
1278         ob = ED_object_add_type(C, OB_SPEAKER, NULL, loc, rot, false, layer);
1279
1280         /* to make it easier to start using this immediately in NLA, a default sound clip is created
1281          * ready to be moved around to retime the sound and/or make new sound clips
1282          */
1283         {
1284                 /* create new data for NLA hierarchy */
1285                 AnimData *adt = BKE_animdata_add_id(&ob->id);
1286                 NlaTrack *nlt = BKE_nlatrack_add(adt, NULL);
1287                 NlaStrip *strip = BKE_nla_add_soundstrip(scene, ob->data);
1288                 strip->start = CFRA;
1289                 strip->end += strip->start;
1290
1291                 /* hook them up */
1292                 BKE_nlatrack_add_strip(nlt, strip);
1293
1294                 /* auto-name the strip, and give the track an interesting name  */
1295                 BLI_strncpy(nlt->name, DATA_("SoundTrack"), sizeof(nlt->name));
1296                 BKE_nlastrip_validate_name(adt, strip);
1297
1298                 WM_event_add_notifier(C, NC_ANIMATION | ND_NLA | NA_EDITED, NULL);
1299         }
1300
1301         return OPERATOR_FINISHED;
1302 }
1303
1304 void OBJECT_OT_speaker_add(wmOperatorType *ot)
1305 {
1306         /* identifiers */
1307         ot->name = "Add Speaker";
1308         ot->description = "Add a speaker object to the scene";
1309         ot->idname = "OBJECT_OT_speaker_add";
1310
1311         /* api callbacks */
1312         ot->exec = object_speaker_add_exec;
1313         ot->poll = ED_operator_objectmode;
1314
1315         /* flags */
1316         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1317
1318         ED_object_add_generic_props(ot, true);
1319 }
1320
1321 /**************************** Delete Object *************************/
1322
1323 /* remove base from a specific scene */
1324 /* note: now unlinks constraints as well */
1325 void ED_object_base_free_and_unlink(Main *bmain, Scene *scene, Object *ob)
1326 {
1327         if (BKE_library_ID_is_indirectly_used(bmain, ob) &&
1328             ID_REAL_USERS(ob) <= 1 && ID_EXTRA_USERS(ob) == 0)
1329         {
1330                 /* We cannot delete indirectly used object... */
1331                 printf("WARNING, undeletable object '%s', should have been catched before reaching this function!",
1332                        ob->id.name + 2);
1333                 return;
1334         }
1335
1336         DEG_id_tag_update_ex(bmain, &ob->id, DEG_TAG_BASE_FLAGS_UPDATE);
1337
1338         BKE_scene_collections_object_remove(bmain, scene, ob, true);
1339 }
1340
1341 static int object_delete_exec(bContext *C, wmOperator *op)
1342 {
1343         Main *bmain = CTX_data_main(C);
1344         Scene *scene = CTX_data_scene(C);
1345         wmWindowManager *wm = CTX_wm_manager(C);
1346         wmWindow *win;
1347         const bool use_global = RNA_boolean_get(op->ptr, "use_global");
1348         bool changed = false;
1349
1350         if (CTX_data_edit_object(C))
1351                 return OPERATOR_CANCELLED;
1352
1353         CTX_DATA_BEGIN (C, Object *, ob, selected_objects)
1354         {
1355                 const bool is_indirectly_used = BKE_library_ID_is_indirectly_used(bmain, ob);
1356                 if (ob->id.tag & LIB_TAG_INDIRECT) {
1357                         /* Can this case ever happen? */
1358                         BKE_reportf(op->reports, RPT_WARNING, "Cannot delete indirectly linked object '%s'", ob->id.name + 2);
1359                         continue;
1360                 }
1361                 else if (is_indirectly_used && ID_REAL_USERS(ob) <= 1 && ID_EXTRA_USERS(ob) == 0) {
1362                         BKE_reportf(op->reports, RPT_WARNING,
1363                                 "Cannot delete object '%s' from scene '%s', indirectly used objects need at least one user",
1364                                 ob->id.name + 2, scene->id.name + 2);
1365                         continue;
1366                 }
1367
1368                 /* This is sort of a quick hack to address T51243 - Proper thing to do here would be to nuke most of all this
1369                  * custom scene/object/base handling, and use generic lib remap/query for that.
1370                  * But this is for later (aka 2.8, once layers & co are settled and working).
1371                  */
1372                 if (use_global && ob->id.lib == NULL) {
1373                         /* We want to nuke the object, let's nuke it the easy way (not for linked data though)... */
1374                         BKE_libblock_delete(bmain, &ob->id);
1375                         changed = true;
1376                         continue;
1377                 }
1378
1379                 /* remove from Grease Pencil parent */
1380                 /* XXX This is likely not correct? Will also remove parent from grease pencil from other scenes,
1381                  *     even when use_global is false... */
1382                 for (bGPdata *gpd = bmain->gpencil.first; gpd; gpd = gpd->id.next) {
1383                         for (bGPDlayer *gpl = gpd->layers.first; gpl; gpl = gpl->next) {
1384                                 if (gpl->parent != NULL) {
1385                                         if (gpl->parent == ob) {
1386                                                 gpl->parent = NULL;
1387                                         }
1388                                 }
1389                         }
1390                 }
1391
1392                 /* remove from current scene only */
1393                 ED_object_base_free_and_unlink(bmain, scene, ob);
1394                 changed = true;
1395
1396                 if (use_global) {
1397                         Scene *scene_iter;
1398                         for (scene_iter = bmain->scene.first; scene_iter; scene_iter = scene_iter->id.next) {
1399                                 if (scene_iter != scene && !ID_IS_LINKED(scene_iter)) {
1400                                         if (is_indirectly_used && ID_REAL_USERS(ob) <= 1 && ID_EXTRA_USERS(ob) == 0) {
1401                                                 BKE_reportf(op->reports, RPT_WARNING,
1402                                                             "Cannot delete object '%s' from scene '%s', indirectly used objects need at least one user",
1403                                                             ob->id.name + 2, scene_iter->id.name + 2);
1404                                                 break;
1405                                         }
1406                                         ED_object_base_free_and_unlink(bmain, scene_iter, ob);
1407                                 }
1408                         }
1409                 }
1410                 /* end global */
1411         }
1412         CTX_DATA_END;
1413
1414         if (!changed)
1415                 return OPERATOR_CANCELLED;
1416
1417         /* delete has to handle all open scenes */
1418         BKE_main_id_tag_listbase(&bmain->scene, LIB_TAG_DOIT, true);
1419         for (win = wm->windows.first; win; win = win->next) {
1420                 scene = WM_window_get_active_scene(win);
1421
1422                 if (scene->id.tag & LIB_TAG_DOIT) {
1423                         scene->id.tag &= ~LIB_TAG_DOIT;
1424
1425                         DEG_relations_tag_update(bmain);
1426
1427                         DEG_id_tag_update(&scene->id, DEG_TAG_SELECT_UPDATE);
1428                         WM_event_add_notifier(C, NC_SCENE | ND_OB_ACTIVE, scene);
1429                         WM_event_add_notifier(C, NC_SCENE | ND_LAYER_CONTENT, scene);
1430                 }
1431         }
1432
1433         return OPERATOR_FINISHED;
1434 }
1435
1436 void OBJECT_OT_delete(wmOperatorType *ot)
1437 {
1438         /* identifiers */
1439         ot->name = "Delete";
1440         ot->description = "Delete selected objects";
1441         ot->idname = "OBJECT_OT_delete";
1442
1443         /* api callbacks */
1444         ot->invoke = WM_operator_confirm;
1445         ot->exec = object_delete_exec;
1446         ot->poll = ED_operator_objectmode;
1447
1448         /* flags */
1449         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1450
1451         RNA_def_boolean(ot->srna, "use_global", 0, "Delete Globally", "Remove object from all scenes");
1452 }
1453
1454 /**************************** Copy Utilities ******************************/
1455
1456 /* after copying objects, copied data should get new pointers */
1457 static void copy_object_set_idnew(bContext *C)
1458 {
1459         Main *bmain = CTX_data_main(C);
1460
1461         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
1462         {
1463                 BKE_libblock_relink_to_newid(&ob->id);
1464         }
1465         CTX_DATA_END;
1466
1467         BKE_main_id_clear_newpoins(bmain);
1468 }
1469
1470 /********************* Make Duplicates Real ************************/
1471
1472 /**
1473  * \note regarding hashing dupli-objects when using OB_DUPLICOLLECTION, skip the first member of #DupliObject.persistent_id
1474  * since its a unique index and we only want to know if the group objects are from the same dupli-group instance.
1475  */
1476 static unsigned int dupliobject_group_hash(const void *ptr)
1477 {
1478         const DupliObject *dob = ptr;
1479         unsigned int hash = BLI_ghashutil_ptrhash(dob->ob);
1480         unsigned int i;
1481         for (i = 1; (i < MAX_DUPLI_RECUR) && dob->persistent_id[i] != INT_MAX; i++) {
1482                 hash ^= (dob->persistent_id[i] ^ i);
1483         }
1484         return hash;
1485 }
1486
1487 /**
1488  * \note regarding hashing dupli-objects when NOT using OB_DUPLICOLLECTION, include the first member of #DupliObject.persistent_id
1489  * since its the index of the vertex/face the object is instantiated on and we want to identify objects on the same vertex/face.
1490  */
1491 static unsigned int dupliobject_hash(const void *ptr)
1492 {
1493         const DupliObject *dob = ptr;
1494         unsigned int hash = BLI_ghashutil_ptrhash(dob->ob);
1495         hash ^= (dob->persistent_id[0] ^ 0);
1496         return hash;
1497 }
1498
1499 /* Compare function that matches dupliobject_group_hash */
1500 static bool dupliobject_group_cmp(const void *a_, const void *b_)
1501 {
1502         const DupliObject *a = a_;
1503         const DupliObject *b = b_;
1504         unsigned int i;
1505
1506         if (a->ob != b->ob) {
1507                 return true;
1508         }
1509
1510         for (i = 1; (i < MAX_DUPLI_RECUR); i++) {
1511                 if (a->persistent_id[i] != b->persistent_id[i]) {
1512                         return true;
1513                 }
1514                 else if (a->persistent_id[i] == INT_MAX) {
1515                         break;
1516                 }
1517         }
1518
1519         /* matching */
1520         return false;
1521 }
1522
1523 /* Compare function that matches dupliobject_hash */
1524 static bool dupliobject_cmp(const void *a_, const void *b_)
1525 {
1526         const DupliObject *a = a_;
1527         const DupliObject *b = b_;
1528
1529         if (a->ob != b->ob) {
1530                 return true;
1531         }
1532
1533         if (a->persistent_id[0] != b->persistent_id[0]) {
1534                 return true;
1535         }
1536
1537         /* matching */
1538         return false;
1539 }
1540
1541 static void make_object_duplilist_real(bContext *C, Scene *scene, Base *base,
1542                                        const bool use_base_parent,
1543                                        const bool use_hierarchy)
1544 {
1545         Main *bmain = CTX_data_main(C);
1546         ViewLayer *view_layer = CTX_data_view_layer(C);
1547         Depsgraph *depsgraph = CTX_data_depsgraph(C);
1548         ListBase *lb_duplis;
1549         DupliObject *dob;
1550         GHash *dupli_gh, *parent_gh = NULL;
1551
1552         if (!(base->object->transflag & OB_DUPLI)) {
1553                 return;
1554         }
1555
1556         lb_duplis = object_duplilist(depsgraph, scene, base->object);
1557
1558         dupli_gh = BLI_ghash_ptr_new(__func__);
1559         if (use_hierarchy) {
1560                 if (base->object->transflag & OB_DUPLICOLLECTION) {
1561                         parent_gh = BLI_ghash_new(dupliobject_group_hash, dupliobject_group_cmp, __func__);
1562                 }
1563                 else {
1564                         parent_gh = BLI_ghash_new(dupliobject_hash, dupliobject_cmp, __func__);
1565                 }
1566         }
1567
1568         for (dob = lb_duplis->first; dob; dob = dob->next) {
1569                 Object *ob_src = dob->ob;
1570                 Object *ob_dst = ID_NEW_SET(dob->ob, BKE_object_copy(bmain, ob_src));
1571                 Base *base_dst;
1572
1573                 /* font duplis can have a totcol without material, we get them from parent
1574                  * should be implemented better...
1575                  */
1576                 if (ob_dst->mat == NULL) {
1577                         ob_dst->totcol = 0;
1578                 }
1579
1580                 BKE_collection_object_add_from(bmain, scene, base->object, ob_dst);
1581                 base_dst = BKE_view_layer_base_find(view_layer, ob_dst);
1582                 BLI_assert(base_dst != NULL);
1583
1584                 BKE_scene_object_base_flag_sync_from_base(base_dst);
1585
1586                 /* make sure apply works */
1587                 BKE_animdata_free(&ob_dst->id, true);
1588                 ob_dst->adt = NULL;
1589
1590                 /* Proxies are not to be copied. */
1591                 ob_dst->proxy_from = NULL;
1592                 ob_dst->proxy_group = NULL;
1593                 ob_dst->proxy = NULL;
1594
1595                 ob_dst->parent = NULL;
1596                 BKE_constraints_free(&ob_dst->constraints);
1597                 ob_dst->runtime.curve_cache = NULL;
1598                 ob_dst->transflag &= ~OB_DUPLI;
1599
1600                 copy_m4_m4(ob_dst->obmat, dob->mat);
1601                 BKE_object_apply_mat4(ob_dst, ob_dst->obmat, false, false);
1602
1603                 BLI_ghash_insert(dupli_gh, dob, ob_dst);
1604                 if (parent_gh) {
1605                         void **val;
1606                         /* Due to nature of hash/comparison of this ghash, a lot of duplis may be considered as 'the same',
1607                          * this avoids trying to insert same key several time and raise asserts in debug builds... */
1608                         if (!BLI_ghash_ensure_p(parent_gh, dob, &val)) {
1609                                 *val = ob_dst;
1610                         }
1611                 }
1612         }
1613
1614         for (dob = lb_duplis->first; dob; dob = dob->next) {
1615                 Object *ob_src = dob->ob;
1616                 Object *ob_dst = BLI_ghash_lookup(dupli_gh, dob);
1617
1618                 /* Remap new object to itself, and clear again newid pointer of orig object. */
1619                 BKE_libblock_relink_to_newid(&ob_dst->id);
1620
1621                 DEG_id_tag_update(&ob_dst->id, OB_RECALC_DATA);
1622
1623                 if (use_hierarchy) {
1624                         /* original parents */
1625                         Object *ob_src_par = ob_src->parent;
1626                         Object *ob_dst_par = NULL;
1627
1628                         /* find parent that was also made real */
1629                         if (ob_src_par) {
1630                                 /* OK to keep most of the members uninitialized,
1631                                  * they won't be read, this is simply for a hash lookup. */
1632                                 DupliObject dob_key;
1633                                 dob_key.ob = ob_src_par;
1634                                 if (base->object->transflag & OB_DUPLICOLLECTION) {
1635                                         memcpy(&dob_key.persistent_id[1],
1636                                                &dob->persistent_id[1],
1637                                                sizeof(dob->persistent_id[1]) * (MAX_DUPLI_RECUR - 1));
1638                                 }
1639                                 else {
1640                                         dob_key.persistent_id[0] = dob->persistent_id[0];
1641                                 }
1642                                 ob_dst_par = BLI_ghash_lookup(parent_gh, &dob_key);
1643                         }
1644
1645                         if (ob_dst_par) {
1646                                 /* allow for all possible parent types */
1647                                 ob_dst->partype = ob_src->partype;
1648                                 BLI_strncpy(ob_dst->parsubstr, ob_src->parsubstr, sizeof(ob_dst->parsubstr));
1649                                 ob_dst->par1 = ob_src->par1;
1650                                 ob_dst->par2 = ob_src->par2;
1651                                 ob_dst->par3 = ob_src->par3;
1652
1653                                 copy_m4_m4(ob_dst->parentinv, ob_src->parentinv);
1654
1655                                 ob_dst->parent = ob_dst_par;
1656                         }
1657                         else if (use_base_parent) {
1658                                 ob_dst->parent = base->object;
1659                                 ob_dst->partype = PAROBJECT;
1660                         }
1661                 }
1662                 else if (use_base_parent) {
1663                         /* since we are ignoring the internal hierarchy - parent all to the
1664                          * base object */
1665                         ob_dst->parent = base->object;
1666                         ob_dst->partype = PAROBJECT;
1667                 }
1668
1669                 if (ob_dst->parent) {
1670                         /* note, this may be the parent of other objects, but it should
1671                          * still work out ok */
1672                         BKE_object_apply_mat4(ob_dst, dob->mat, false, true);
1673
1674                         /* to set ob_dst->orig and in case theres any other discrepicies */
1675                         DEG_id_tag_update(&ob_dst->id, OB_RECALC_OB);
1676                 }
1677         }
1678
1679         if (base->object->transflag & OB_DUPLICOLLECTION && base->object->dup_group) {
1680                 for (Object *ob = bmain->object.first; ob; ob = ob->id.next) {
1681                         if (ob->proxy_group == base->object) {
1682                                 ob->proxy = NULL;
1683                                 ob->proxy_from = NULL;
1684                                 DEG_id_tag_update(&ob->id, OB_RECALC_OB);
1685                         }
1686                 }
1687         }
1688
1689         BLI_ghash_free(dupli_gh, NULL, NULL);
1690         if (parent_gh) {
1691                 BLI_ghash_free(parent_gh, NULL, NULL);
1692         }
1693
1694         free_object_duplilist(lb_duplis);
1695
1696         BKE_main_id_clear_newpoins(bmain);
1697
1698         base->object->transflag &= ~OB_DUPLI;
1699 }
1700
1701 static int object_duplicates_make_real_exec(bContext *C, wmOperator *op)
1702 {
1703         Main *bmain = CTX_data_main(C);
1704         Scene *scene = CTX_data_scene(C);
1705
1706         const bool use_base_parent = RNA_boolean_get(op->ptr, "use_base_parent");
1707         const bool use_hierarchy = RNA_boolean_get(op->ptr, "use_hierarchy");
1708
1709         BKE_main_id_clear_newpoins(bmain);
1710
1711         CTX_DATA_BEGIN (C, Base *, base, selected_editable_bases)
1712         {
1713                 make_object_duplilist_real(C, scene, base, use_base_parent, use_hierarchy);
1714
1715                 /* dependencies were changed */
1716                 WM_event_add_notifier(C, NC_OBJECT | ND_PARENT, base->object);
1717         }
1718         CTX_DATA_END;
1719
1720         DEG_relations_tag_update(bmain);
1721         WM_event_add_notifier(C, NC_SCENE, scene);
1722         WM_main_add_notifier(NC_OBJECT | ND_DRAW, NULL);
1723
1724         return OPERATOR_FINISHED;
1725 }
1726
1727 void OBJECT_OT_duplicates_make_real(wmOperatorType *ot)
1728 {
1729         /* identifiers */
1730         ot->name = "Make Duplicates Real";
1731         ot->description = "Make dupli objects attached to this object real";
1732         ot->idname = "OBJECT_OT_duplicates_make_real";
1733
1734         /* api callbacks */
1735         ot->exec = object_duplicates_make_real_exec;
1736
1737         ot->poll = ED_operator_objectmode;
1738
1739         /* flags */
1740         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1741
1742         RNA_def_boolean(ot->srna, "use_base_parent", 0, "Parent", "Parent newly created objects to the original duplicator");
1743         RNA_def_boolean(ot->srna, "use_hierarchy", 0, "Keep Hierarchy", "Maintain parent child relationships");
1744 }
1745
1746 /**************************** Convert **************************/
1747
1748 static const EnumPropertyItem convert_target_items[] = {
1749         {OB_CURVE, "CURVE", ICON_OUTLINER_OB_CURVE, "Curve from Mesh/Text", ""},
1750         {OB_MESH, "MESH", ICON_OUTLINER_OB_MESH, "Mesh from Curve/Meta/Surf/Text", ""},
1751         {0, NULL, 0, NULL, NULL}
1752 };
1753
1754 static void convert_ensure_curve_cache(Depsgraph *depsgraph, Scene *scene, Object *ob)
1755 {
1756         if (ob->runtime.curve_cache == NULL) {
1757                 /* Force creation. This is normally not needed but on operator
1758                  * redo we might end up with an object which isn't evaluated yet.
1759                  */
1760                 if (ELEM(ob->type, OB_SURF, OB_CURVE, OB_FONT)) {
1761                         BKE_displist_make_curveTypes(depsgraph, scene, ob, false);
1762                 }
1763                 else if (ob->type == OB_MBALL) {
1764                         BKE_displist_make_mball(depsgraph, scene, ob);
1765                 }
1766         }
1767 }
1768
1769 static void curvetomesh(Main *bmain, Depsgraph *depsgraph, Scene *scene, Object *ob)
1770 {
1771         convert_ensure_curve_cache(depsgraph, scene, ob);
1772         BKE_mesh_from_nurbs(bmain, ob); /* also does users */
1773
1774         if (ob->type == OB_MESH) {
1775                 BKE_object_free_modifiers(ob, 0);
1776         }
1777 }
1778
1779 static bool convert_poll(bContext *C)
1780 {
1781         Scene *scene = CTX_data_scene(C);
1782         Base *base_act = CTX_data_active_base(C);
1783         Object *obact = base_act ? base_act->object : NULL;
1784
1785         return (!ID_IS_LINKED(scene) && obact && (BKE_object_is_in_editmode(obact) == false) &&
1786                 (base_act->flag & BASE_SELECTED) && !ID_IS_LINKED(obact));
1787 }
1788
1789 /* Helper for convert_exec */
1790 static Base *duplibase_for_convert(Main *bmain, Scene *scene, ViewLayer *view_layer, Base *base, Object *ob)
1791 {
1792         Object *obn;
1793         Base *basen;
1794
1795         if (ob == NULL) {
1796                 ob = base->object;
1797         }
1798
1799         obn = BKE_object_copy(bmain, ob);
1800         DEG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
1801         BKE_collection_object_add_from(bmain, scene, ob, obn);
1802
1803         basen = BKE_view_layer_base_find(view_layer, obn);
1804         ED_object_base_select(basen, BA_SELECT);
1805         ED_object_base_select(basen, BA_DESELECT);
1806         return basen;
1807 }
1808
1809 static int convert_exec(bContext *C, wmOperator *op)
1810 {
1811         Main *bmain = CTX_data_main(C);
1812         Depsgraph *depsgraph = CTX_data_depsgraph(C);
1813         Scene *scene = CTX_data_scene(C);
1814         ViewLayer *view_layer = CTX_data_view_layer(C);
1815         Base *basen = NULL, *basact = NULL;
1816         Object *ob1, *newob, *obact = CTX_data_active_object(C);
1817         DerivedMesh *dm;
1818         Curve *cu;
1819         Nurb *nu;
1820         MetaBall *mb;
1821         Mesh *me;
1822         const short target = RNA_enum_get(op->ptr, "target");
1823         bool keep_original = RNA_boolean_get(op->ptr, "keep_original");
1824         int a, mballConverted = 0;
1825
1826         /* don't forget multiple users! */
1827
1828         {
1829                 FOREACH_SCENE_OBJECT_BEGIN(scene, ob)
1830                 {
1831                         ob->flag &= ~OB_DONE;
1832
1833                         /* flag data thats not been edited (only needed for !keep_original) */
1834                         if (ob->data) {
1835                                 ((ID *)ob->data)->tag |= LIB_TAG_DOIT;
1836                         }
1837
1838                         /* possible metaball basis is not in this scene */
1839                         if (ob->type == OB_MBALL && target == OB_MESH) {
1840                                 if (BKE_mball_is_basis(ob) == false) {
1841                                         Object *ob_basis;
1842                                         ob_basis = BKE_mball_basis_find(scene, ob);
1843                                         if (ob_basis) {
1844                                                 ob_basis->flag &= ~OB_DONE;
1845                                         }
1846                                 }
1847                         }
1848                 }
1849                 FOREACH_SCENE_OBJECT_END;
1850         }
1851
1852         ListBase selected_editable_bases = CTX_data_collection_get(C, "selected_editable_bases");
1853
1854         /* Ensure we get all meshes calculated with a sufficient data-mask,
1855          * needed since re-evaluating single modifiers causes bugs if they depend
1856          * on other objects data masks too, see: T50950. */
1857         {
1858                 for (CollectionPointerLink *link = selected_editable_bases.first; link; link = link->next) {
1859                         Base *base = link->ptr.data;
1860                         Object *ob = base->object;
1861
1862                         /* The way object type conversion works currently (enforcing conversion of *all* objetcs using converted
1863                          * obdata, even some un-selected/hidden/inother scene ones, sounds totally bad to me.
1864                          * However, changing this is more design than bugfix, not to mention convoluted code below,
1865                          * so that will be for later.
1866                          * But at the very least, do not do that with linked IDs! */
1867                         if ((ID_IS_LINKED(ob) || (ob->data && ID_IS_LINKED(ob->data))) && !keep_original) {
1868                                 keep_original = true;
1869                                 BKE_reportf(op->reports, RPT_INFO,
1870                                             "Converting some linked object/object data, enforcing 'Keep Original' option to True");
1871                         }
1872
1873                         DEG_id_tag_update(&base->object->id, OB_RECALC_DATA);
1874                 }
1875
1876                 uint64_t customdata_mask_prev = scene->customdata_mask;
1877                 scene->customdata_mask |= CD_MASK_MESH;
1878                 BKE_scene_graph_update_tagged(depsgraph, bmain);
1879                 scene->customdata_mask = customdata_mask_prev;
1880         }
1881
1882         for (CollectionPointerLink *link = selected_editable_bases.first; link; link = link->next) {
1883                 Base *base = link->ptr.data;
1884                 Object *ob = base->object;
1885
1886                 if (ob->flag & OB_DONE || !IS_TAGGED(ob->data)) {
1887                         if (ob->type != target) {
1888                                 base->flag &= ~SELECT;
1889                                 ob->flag &= ~SELECT;
1890                         }
1891
1892                         /* obdata already modified */
1893                         if (!IS_TAGGED(ob->data)) {
1894                                 /* When 2 objects with linked data are selected, converting both
1895                                  * would keep modifiers on all but the converted object [#26003] */
1896                                 if (ob->type == OB_MESH) {
1897                                         BKE_object_free_modifiers(ob, 0);  /* after derivedmesh calls! */
1898                                 }
1899                                 if (ob->type == OB_GPENCIL) {
1900                                         BKE_object_free_modifiers(ob, 0);  /* after derivedmesh calls! */
1901                                         BKE_object_free_shaderfx(ob, 0);
1902                                 }
1903                         }
1904                 }
1905                 else if (ob->type == OB_MESH && target == OB_CURVE) {
1906                         ob->flag |= OB_DONE;
1907
1908                         if (keep_original) {
1909                                 basen = duplibase_for_convert(bmain, scene, view_layer, base, NULL);
1910                                 newob = basen->object;
1911
1912                                 /* decrement original mesh's usage count  */
1913                                 me = newob->data;
1914                                 id_us_min(&me->id);
1915
1916                                 /* make a new copy of the mesh */
1917                                 newob->data = BKE_mesh_copy(bmain, me);
1918                         }
1919                         else {
1920                                 newob = ob;
1921                         }
1922
1923                         BKE_mesh_to_curve(bmain, depsgraph, scene, newob);
1924
1925                         if (newob->type == OB_CURVE) {
1926                                 BKE_object_free_modifiers(newob, 0);   /* after derivedmesh calls! */
1927                                 ED_rigidbody_object_remove(bmain, scene, newob);
1928                         }
1929                 }
1930                 else if (ob->type == OB_MESH) {
1931                         ob->flag |= OB_DONE;
1932
1933                         if (keep_original) {
1934                                 basen = duplibase_for_convert(bmain, scene, view_layer, base, NULL);
1935                                 newob = basen->object;
1936
1937                                 /* decrement original mesh's usage count  */
1938                                 me = newob->data;
1939                                 id_us_min(&me->id);
1940
1941                                 /* make a new copy of the mesh */
1942                                 newob->data = BKE_mesh_copy(bmain, me);
1943                         }
1944                         else {
1945                                 newob = ob;
1946                                 DEG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
1947                         }
1948
1949                         /* make new mesh data from the original copy */
1950                         /* note: get the mesh from the original, not from the copy in some
1951                          * cases this doesnt give correct results (when MDEF is used for eg)
1952                          */
1953                         dm = mesh_get_derived_final(depsgraph, scene, newob, CD_MASK_MESH);
1954
1955                         DM_to_mesh(dm, newob->data, newob, CD_MASK_MESH, true);
1956
1957                         /* re-tessellation is called by DM_to_mesh */
1958
1959                         BKE_object_free_modifiers(newob, 0);   /* after derivedmesh calls! */
1960                 }
1961                 else if (ob->type == OB_FONT) {
1962                         ob->flag |= OB_DONE;
1963
1964                         if (keep_original) {
1965                                 basen = duplibase_for_convert(bmain, scene, view_layer, base, NULL);
1966                                 newob = basen->object;
1967
1968                                 /* decrement original curve's usage count  */
1969                                 id_us_min(&((Curve *)newob->data)->id);
1970
1971                                 /* make a new copy of the curve */
1972                                 newob->data = BKE_curve_copy(bmain, ob->data);
1973                         }
1974                         else {
1975                                 newob = ob;
1976                         }
1977
1978                         cu = newob->data;
1979
1980                         /* TODO(sergey): Ideally DAG will create nurbs list for a curve data
1981                          *               datablock, but for until we've got granular update
1982                          *               lets take care by selves.
1983                          */
1984                         BKE_vfont_to_curve(newob, FO_EDIT);
1985
1986                         newob->type = OB_CURVE;
1987                         cu->type = OB_CURVE;
1988
1989                         if (cu->vfont) {
1990                                 id_us_min(&cu->vfont->id);
1991                                 cu->vfont = NULL;
1992                         }
1993                         if (cu->vfontb) {
1994                                 id_us_min(&cu->vfontb->id);
1995                                 cu->vfontb = NULL;
1996                         }
1997                         if (cu->vfonti) {
1998                                 id_us_min(&cu->vfonti->id);
1999                                 cu->vfonti = NULL;
2000                         }
2001                         if (cu->vfontbi) {
2002                                 id_us_min(&cu->vfontbi->id);
2003                                 cu->vfontbi = NULL;
2004                         }
2005
2006                         if (!keep_original) {
2007                                 /* other users */
2008                                 if (cu->id.us > 1) {
2009                                         for (ob1 = bmain->object.first; ob1; ob1 = ob1->id.next) {
2010                                                 if (ob1->data == ob->data) {
2011                                                         ob1->type = OB_CURVE;
2012                                                         DEG_id_tag_update(&ob1->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
2013                                                 }
2014                                         }
2015                                 }
2016                         }
2017
2018                         for (nu = cu->nurb.first; nu; nu = nu->next)
2019                                 nu->charidx = 0;
2020
2021                         cu->flag &= ~CU_3D;
2022                         BKE_curve_curve_dimension_update(cu);
2023
2024                         if (target == OB_MESH) {
2025                                 curvetomesh(bmain, depsgraph, scene, newob);
2026
2027                                 /* meshes doesn't use displist */
2028                                 BKE_object_free_curve_cache(newob);
2029                         }
2030                 }
2031                 else if (ELEM(ob->type, OB_CURVE, OB_SURF)) {
2032                         ob->flag |= OB_DONE;
2033
2034                         if (target == OB_MESH) {
2035                                 if (keep_original) {
2036                                         basen = duplibase_for_convert(bmain, scene, view_layer, base, NULL);
2037                                         newob = basen->object;
2038
2039                                         /* decrement original curve's usage count  */
2040                                         id_us_min(&((Curve *)newob->data)->id);
2041
2042                                         /* make a new copy of the curve */
2043                                         newob->data = BKE_curve_copy(bmain, ob->data);
2044                                 }
2045                                 else {
2046                                         newob = ob;
2047                                 }
2048
2049                                 curvetomesh(bmain, depsgraph, scene, newob);
2050
2051                                 /* meshes doesn't use displist */
2052                                 BKE_object_free_curve_cache(newob);
2053                         }
2054                 }
2055                 else if (ob->type == OB_MBALL && target == OB_MESH) {
2056                         Object *baseob;
2057
2058                         base->flag &= ~BASE_SELECTED;
2059                         ob->base_flag &= ~BASE_SELECTED;
2060
2061                         baseob = BKE_mball_basis_find(scene, ob);
2062
2063                         if (ob != baseob) {
2064                                 /* if motherball is converting it would be marked as done later */
2065                                 ob->flag |= OB_DONE;
2066                         }
2067
2068                         if (!(baseob->flag & OB_DONE)) {
2069                                 baseob->flag |= OB_DONE;
2070
2071                                 basen = duplibase_for_convert(bmain, scene, view_layer, base, baseob);
2072                                 newob = basen->object;
2073
2074                                 mb = newob->data;
2075                                 id_us_min(&mb->id);
2076
2077                                 newob->data = BKE_mesh_add(bmain, "Mesh");
2078                                 newob->type = OB_MESH;
2079
2080                                 me = newob->data;
2081                                 me->totcol = mb->totcol;
2082                                 if (newob->totcol) {
2083                                         me->mat = MEM_dupallocN(mb->mat);
2084                                         for (a = 0; a < newob->totcol; a++) id_us_plus((ID *)me->mat[a]);
2085                                 }
2086
2087                                 convert_ensure_curve_cache(depsgraph, scene, baseob);
2088                                 BKE_mesh_from_metaball(&baseob->runtime.curve_cache->disp, newob->data);
2089
2090                                 if (obact->type == OB_MBALL) {
2091                                         basact = basen;
2092                                 }
2093
2094                                 mballConverted = 1;
2095                         }
2096                 }
2097                 else {
2098                         continue;
2099                 }
2100
2101                 /* Ensure new object has consistent material data with its new obdata. */
2102                 test_object_materials(bmain, newob, newob->data);
2103
2104                 /* tag obdata if it was been changed */
2105
2106                 /* If the original object is active then make this object active */
2107                 if (basen) {
2108                         if (ob == obact) {
2109                                 /* store new active base to update BASACT */
2110                                 basact = basen;
2111                         }
2112
2113                         basen = NULL;
2114                 }
2115
2116                 if (!keep_original && (ob->flag & OB_DONE)) {
2117                         DEG_id_tag_update(&ob->id, OB_RECALC_DATA);
2118                         ((ID *)ob->data)->tag &= ~LIB_TAG_DOIT; /* flag not to convert this datablock again */
2119                 }
2120         }
2121         BLI_freelistN(&selected_editable_bases);
2122
2123         if (!keep_original) {
2124                 if (mballConverted) {
2125                         FOREACH_SCENE_OBJECT_BEGIN(scene, ob_mball)
2126                         {
2127                                 if (ob_mball->type == OB_MBALL) {
2128                                         if (ob_mball->flag & OB_DONE) {
2129                                                 Object *ob_basis = NULL;
2130                                                 if (BKE_mball_is_basis(ob_mball) ||
2131                                                     ((ob_basis = BKE_mball_basis_find(scene, ob_mball)) && (ob_basis->flag & OB_DONE)))
2132                                                 {
2133                                                         ED_object_base_free_and_unlink(bmain, scene, ob_mball);
2134                                                 }
2135                                         }
2136                                 }
2137                         }
2138                         FOREACH_SCENE_OBJECT_END;
2139                 }
2140         }
2141
2142 // XXX  ED_object_editmode_enter(C, 0);
2143 // XXX  exit_editmode(C, EM_FREEDATA|EM_WAITCURSOR); /* freedata, but no undo */
2144
2145         if (basact) {
2146                 /* active base was changed */
2147                 ED_object_base_activate(C, basact);
2148                 BASACT(view_layer) = basact;
2149         }
2150         else if (BASACT(view_layer)->object->flag & OB_DONE) {
2151                 WM_event_add_notifier(C, NC_OBJECT | ND_MODIFIER, BASACT(view_layer)->object);
2152                 WM_event_add_notifier(C, NC_OBJECT | ND_DATA, BASACT(view_layer)->object);
2153         }
2154
2155         DEG_relations_tag_update(bmain);
2156         DEG_id_tag_update(&scene->id, DEG_TAG_SELECT_UPDATE);
2157         WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, scene);
2158         WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene);
2159
2160         return OPERATOR_FINISHED;
2161 }
2162
2163
2164 void OBJECT_OT_convert(wmOperatorType *ot)
2165 {
2166         /* identifiers */
2167         ot->name = "Convert to";
2168         ot->description = "Convert selected objects to another type";
2169         ot->idname = "OBJECT_OT_convert";
2170
2171         /* api callbacks */
2172         ot->invoke = WM_menu_invoke;
2173         ot->exec = convert_exec;
2174         ot->poll = convert_poll;
2175
2176         /* flags */
2177         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2178
2179         /* properties */
2180         ot->prop = RNA_def_enum(ot->srna, "target", convert_target_items, OB_MESH, "Target", "Type of object to convert to");
2181         RNA_def_boolean(ot->srna, "keep_original", 0, "Keep Original", "Keep original objects instead of replacing them");
2182 }
2183
2184 /**************************** Duplicate ************************/
2185
2186 /*
2187  * dupflag: a flag made from constants declared in DNA_userdef_types.h
2188  * The flag tells adduplicate() whether to copy data linked to the object, or to reference the existing data.
2189  * U.dupflag for default operations or you can construct a flag as python does
2190  * if the dupflag is 0 then no data will be copied (linked duplicate) */
2191
2192 /* used below, assumes id.new is correct */
2193 /* leaves selection of base/object unaltered */
2194 /* Does set ID->newid pointers. */
2195 static Base *object_add_duplicate_internal(Main *bmain, Scene *scene, ViewLayer *view_layer, Object *ob, int dupflag)
2196 {
2197 #define ID_NEW_REMAP_US(a)      if (      (a)->id.newid) { (a) = (void *)(a)->id.newid;       (a)->id.us++; }
2198 #define ID_NEW_REMAP_US2(a)     if (((ID *)a)->newid)    { (a) = ((ID  *)a)->newid;     ((ID *)a)->us++;    }
2199
2200         Base *base, *basen = NULL;
2201         Material ***matarar;
2202         Object *obn;
2203         ID *id;
2204         int a, didit;
2205
2206         if (ob->mode & OB_MODE_POSE) {
2207                 ; /* nothing? */
2208         }
2209         else {
2210                 obn = ID_NEW_SET(ob, BKE_object_copy(bmain, ob));
2211                 DEG_id_tag_update(&obn->id, OB_RECALC_OB | OB_RECALC_DATA);
2212
2213                 base = BKE_view_layer_base_find(view_layer, ob);
2214                 if ((base != NULL) && (base->flag & BASE_VISIBLE)) {
2215                         BKE_collection_object_add_from(bmain, scene, ob, obn);
2216                 }
2217                 else {
2218                         LayerCollection *layer_collection = BKE_layer_collection_get_active(view_layer);
2219                         BKE_collection_object_add(bmain, layer_collection->collection, obn);
2220                 }
2221                 basen = BKE_view_layer_base_find(view_layer, obn);
2222
2223                 /* 1) duplis should end up in same collection as the original
2224                  * 2) Rigid Body sim participants MUST always be part of a collection...
2225                  */
2226                 // XXX: is 2) really a good measure here?
2227                 if (ob->rigidbody_object || ob->rigidbody_constraint) {
2228                         Collection *collection;
2229                         for (collection = bmain->collection.first; collection; collection = collection->id.next) {
2230                                 if (BKE_collection_has_object(collection, ob))
2231                                         BKE_collection_object_add(bmain, collection, obn);
2232                         }
2233                 }
2234
2235                 /* duplicates using userflags */
2236                 if (dupflag & USER_DUP_ACT) {
2237                         BKE_animdata_copy_id_action(bmain, &obn->id, true);
2238                 }
2239
2240                 if (dupflag & USER_DUP_MAT) {
2241                         for (a = 0; a < obn->totcol; a++) {
2242                                 id = (ID *)obn->mat[a];
2243                                 if (id) {
2244                                         ID_NEW_REMAP_US(obn->mat[a])
2245                                         else {
2246                                                 obn->mat[a] = ID_NEW_SET(obn->mat[a], BKE_material_copy(bmain, obn->mat[a]));
2247                                                 /* duplicate grease pencil settings */
2248                                                 if (ob->mat[a]->gp_style) {
2249                                                         obn->mat[a]->gp_style = MEM_dupallocN(ob->mat[a]->gp_style);
2250                                                 }
2251                                         }
2252                                         id_us_min(id);
2253
2254                                         if (dupflag & USER_DUP_ACT) {
2255                                                 BKE_animdata_copy_id_action(bmain, &obn->mat[a]->id, true);
2256                                         }
2257                                 }
2258                         }
2259                 }
2260                 if (dupflag & USER_DUP_PSYS) {
2261                         ParticleSystem *psys;
2262                         for (psys = obn->particlesystem.first; psys; psys = psys->next) {
2263                                 id = (ID *) psys->part;
2264                                 if (id) {
2265                                         ID_NEW_REMAP_US(psys->part)
2266                                         else {
2267                                                 psys->part = ID_NEW_SET(psys->part, BKE_particlesettings_copy(bmain, psys->part));
2268                                         }
2269
2270                                         if (dupflag & USER_DUP_ACT) {
2271                                                 BKE_animdata_copy_id_action(bmain, &psys->part->id, true);
2272                                         }
2273
2274                                         id_us_min(id);
2275                                 }
2276                         }
2277                 }
2278
2279                 id = obn->data;
2280                 didit = 0;
2281
2282                 switch (obn->type) {
2283                         case OB_MESH:
2284                                 if (dupflag & USER_DUP_MESH) {
2285                                         ID_NEW_REMAP_US2(obn->data)
2286                                         else {
2287                                                 obn->data = ID_NEW_SET(obn->data, BKE_mesh_copy(bmain, obn->data));
2288                                                 didit = 1;
2289                                         }
2290                                         id_us_min(id);
2291                                 }
2292                                 break;
2293                         case OB_CURVE:
2294                                 if (dupflag & USER_DUP_CURVE) {
2295                                         ID_NEW_REMAP_US2(obn->data)
2296                                         else {
2297                                                 obn->data = ID_NEW_SET(obn->data, BKE_curve_copy(bmain, obn->data));
2298                                                 didit = 1;
2299                                         }
2300                                         id_us_min(id);
2301                                 }
2302                                 break;
2303                         case OB_SURF:
2304                                 if (dupflag & USER_DUP_SURF) {
2305                                         ID_NEW_REMAP_US2(obn->data)
2306                                         else {
2307                                                 obn->data = ID_NEW_SET(obn->data, BKE_curve_copy(bmain, obn->data));
2308                                                 didit = 1;
2309                                         }
2310                                         id_us_min(id);
2311                                 }
2312                                 break;
2313                         case OB_FONT:
2314                                 if (dupflag & USER_DUP_FONT) {
2315                                         ID_NEW_REMAP_US2(obn->data)
2316                                         else {
2317                                                 obn->data = ID_NEW_SET(obn->data, BKE_curve_copy(bmain, obn->data));
2318                                                 didit = 1;
2319                                         }
2320                                         id_us_min(id);
2321                                 }
2322                                 break;
2323                         case OB_MBALL:
2324                                 if (dupflag & USER_DUP_MBALL) {
2325                                         ID_NEW_REMAP_US2(obn->data)
2326                                         else {
2327                                                 obn->data = ID_NEW_SET(obn->data, BKE_mball_copy(bmain, obn->data));
2328                                                 didit = 1;
2329                                         }
2330                                         id_us_min(id);
2331                                 }
2332                                 break;
2333                         case OB_LAMP:
2334                                 if (dupflag & USER_DUP_LAMP) {
2335                                         ID_NEW_REMAP_US2(obn->data)
2336                                         else {
2337                                                 obn->data = ID_NEW_SET(obn->data, BKE_lamp_copy(bmain, obn->data));
2338                                                 didit = 1;
2339                                         }
2340                                         id_us_min(id);
2341                                 }
2342                                 break;
2343                         case OB_ARMATURE:
2344                                 DEG_id_tag_update(&obn->id, OB_RECALC_DATA);
2345                                 if (obn->pose)
2346                                         BKE_pose_tag_recalc(bmain, obn->pose);
2347                                 if (dupflag & USER_DUP_ARM) {
2348                                         ID_NEW_REMAP_US2(obn->data)
2349                                         else {
2350                                                 obn->data = ID_NEW_SET(obn->data, BKE_armature_copy(bmain, obn->data));
2351                                                 BKE_pose_rebuild(bmain, obn, obn->data, true);
2352                                                 didit = 1;
2353                                         }
2354                                         id_us_min(id);
2355                                 }
2356                                 break;
2357                         case OB_LATTICE:
2358                                 if (dupflag != 0) {
2359                                         ID_NEW_REMAP_US2(obn->data)
2360                                         else {
2361                                                 obn->data = ID_NEW_SET(obn->data, BKE_lattice_copy(bmain, obn->data));
2362                                                 didit = 1;
2363                                         }
2364                                         id_us_min(id);
2365                                 }
2366                                 break;
2367                         case OB_CAMERA:
2368                                 if (dupflag != 0) {
2369                                         ID_NEW_REMAP_US2(obn->data)
2370                                         else {
2371                                                 obn->data = ID_NEW_SET(obn->data, BKE_camera_copy(bmain, obn->data));
2372                                                 didit = 1;
2373                                         }
2374                                         id_us_min(id);
2375                                 }
2376                                 break;
2377                         case OB_SPEAKER:
2378                                 if (dupflag != 0) {
2379                                         ID_NEW_REMAP_US2(obn->data)
2380                                         else {
2381                                                 obn->data = ID_NEW_SET(obn->data, BKE_speaker_copy(bmain, obn->data));
2382                                                 didit = 1;
2383                                         }
2384                                         id_us_min(id);
2385                                 }
2386                                 break;
2387                         case OB_GPENCIL:
2388                                 if (dupflag != 0) {
2389                                         ID_NEW_REMAP_US2(obn->data)
2390                                         else {
2391                                                 obn->data = ID_NEW_SET(obn->data, BKE_gpencil_copy(bmain, obn->data));
2392                                                 didit = 1;
2393                                         }
2394                                         id_us_min(id);
2395                                 }
2396                                 break;
2397                 }
2398
2399                 /* check if obdata is copied */
2400                 if (didit) {
2401                         Key *key = BKE_key_from_object(obn);
2402
2403                         Key *oldkey = BKE_key_from_object(ob);
2404                         if (oldkey != NULL) {
2405                                 ID_NEW_SET(oldkey, key);
2406                         }
2407
2408                         if (dupflag & USER_DUP_ACT) {
2409                                 BKE_animdata_copy_id_action(bmain, (ID *)obn->data, true);
2410                                 if (key) {
2411                                         BKE_animdata_copy_id_action(bmain, (ID *)key, true);
2412                                 }
2413                         }
2414
2415                         if (dupflag & USER_DUP_MAT) {
2416                                 matarar = give_matarar(obn);
2417                                 if (matarar) {
2418                                         for (a = 0; a < obn->totcol; a++) {
2419                                                 id = (ID *)(*matarar)[a];
2420                                                 if (id) {
2421                                                         ID_NEW_REMAP_US((*matarar)[a])
2422                                                         else {
2423                                                                 (*matarar)[a] = ID_NEW_SET((*matarar)[a], BKE_material_copy(bmain, (*matarar)[a]));
2424                                                         }
2425                                                         id_us_min(id);
2426                                                 }
2427                                         }
2428                                 }
2429                         }
2430                 }
2431         }
2432         return basen;
2433
2434 #undef ID_NEW_REMAP_US
2435 #undef ID_NEW_REMAP_US2
2436 }
2437
2438 /* single object duplicate, if dupflag==0, fully linked, else it uses the flags given */
2439 /* leaves selection of base/object unaltered.
2440  * note: don't call this within a loop since clear_* funcs loop over the entire database.
2441  * note: caller must do DAG_relations_tag_update(bmain);
2442  *       this is not done automatic since we may duplicate many objects in a batch */
2443 Base *ED_object_add_duplicate(Main *bmain, Scene *scene, ViewLayer *view_layer, Base *base, int dupflag)
2444 {
2445         Base *basen;
2446         Object *ob;
2447
2448         basen = object_add_duplicate_internal(bmain, scene, view_layer, base->object, dupflag);
2449         if (basen == NULL) {
2450                 return NULL;
2451         }
2452
2453         ob = basen->object;
2454
2455         /* link own references to the newly duplicated data [#26816] */
2456         BKE_libblock_relink_to_newid(&ob->id);
2457
2458         /* DAG_relations_tag_update(bmain); */ /* caller must do */
2459
2460         if (ob->data != NULL) {
2461                 DEG_id_tag_update_ex(bmain, (ID *)ob->data, DEG_TAG_EDITORS_UPDATE);
2462         }
2463
2464         BKE_main_id_clear_newpoins(bmain);
2465
2466         return basen;
2467 }
2468
2469 /* contextual operator dupli */
2470 static int duplicate_exec(bContext *C, wmOperator *op)
2471 {
2472         Main *bmain = CTX_data_main(C);
2473         Scene *scene = CTX_data_scene(C);
2474         ViewLayer *view_layer = CTX_data_view_layer(C);
2475         const bool linked = RNA_boolean_get(op->ptr, "linked");
2476         int dupflag = (linked) ? 0 : U.dupflag;
2477
2478         CTX_DATA_BEGIN (C, Base *, base, selected_bases)
2479         {
2480                 Base *basen = object_add_duplicate_internal(bmain, scene, view_layer, base->object, dupflag);
2481
2482                 /* note that this is safe to do with this context iterator,
2483                  * the list is made in advance */
2484                 ED_object_base_select(base, BA_DESELECT);
2485                 ED_object_base_select(basen, BA_SELECT);
2486
2487                 if (basen == NULL) {
2488                         continue;
2489                 }
2490
2491                 /* new object becomes active */
2492                 if (BASACT(view_layer) == base)
2493                         ED_object_base_activate(C, basen);
2494
2495                 if (basen->object->data) {
2496                         DEG_id_tag_update(basen->object->data, 0);
2497                 }
2498         }
2499         CTX_DATA_END;
2500
2501         copy_object_set_idnew(C);
2502
2503         BKE_main_id_clear_newpoins(bmain);
2504
2505         DEG_relations_tag_update(bmain);
2506         DEG_id_tag_update(&scene->id, DEG_TAG_COPY_ON_WRITE | DEG_TAG_SELECT_UPDATE);
2507
2508         WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene);
2509
2510         return OPERATOR_FINISHED;
2511 }
2512
2513 void OBJECT_OT_duplicate(wmOperatorType *ot)
2514 {
2515         PropertyRNA *prop;
2516
2517         /* identifiers */
2518         ot->name = "Duplicate Objects";
2519         ot->description = "Duplicate selected objects";
2520         ot->idname = "OBJECT_OT_duplicate";
2521
2522         /* api callbacks */
2523         ot->exec = duplicate_exec;
2524         ot->poll = ED_operator_objectmode;
2525
2526         /* flags */
2527         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2528
2529         /* to give to transform */
2530         RNA_def_boolean(ot->srna, "linked", 0, "Linked", "Duplicate object but not object data, linking to the original data");
2531         prop = RNA_def_enum(ot->srna, "mode", rna_enum_transform_mode_types, TFM_TRANSLATION, "Mode", "");
2532         RNA_def_property_flag(prop, PROP_HIDDEN);
2533 }
2534
2535 /* **************** add named object, for dragdrop ************* */
2536
2537 static int add_named_exec(bContext *C, wmOperator *op)
2538 {
2539         wmWindow *win = CTX_wm_window(C);
2540         const wmEvent *event = win ? win->eventstate : NULL;
2541         Main *bmain = CTX_data_main(C);
2542         Scene *scene = CTX_data_scene(C);
2543         ViewLayer *view_layer = CTX_data_view_layer(C);
2544         Base *basen;
2545         Object *ob;
2546         const bool linked = RNA_boolean_get(op->ptr, "linked");
2547         int dupflag = (linked) ? 0 : U.dupflag;
2548         char name[MAX_ID_NAME - 2];
2549
2550         /* find object, create fake base */
2551         RNA_string_get(op->ptr, "name", name);
2552         ob = (Object *)BKE_libblock_find_name(bmain, ID_OB, name);
2553
2554         if (ob == NULL) {
2555                 BKE_report(op->reports, RPT_ERROR, "Object not found");
2556                 return OPERATOR_CANCELLED;
2557         }
2558
2559         /* prepare dupli */
2560         basen = object_add_duplicate_internal(bmain, scene, view_layer, ob, dupflag);
2561
2562         if (basen == NULL) {
2563                 BKE_report(op->reports, RPT_ERROR, "Object could not be duplicated");
2564                 return OPERATOR_CANCELLED;
2565         }
2566
2567         BKE_scene_object_base_flag_sync_from_object(basen);
2568         basen->object->restrictflag &= ~OB_RESTRICT_VIEW;
2569
2570         if (event) {
2571                 ARegion *ar = CTX_wm_region(C);
2572                 const int mval[2] = {event->x - ar->winrct.xmin,
2573                                      event->y - ar->winrct.ymin};
2574                 ED_object_location_from_view(C, basen->object->loc);
2575                 ED_view3d_cursor3d_position(C, mval, false, basen->object->loc);
2576         }
2577
2578         ED_object_base_select(basen, BA_SELECT);
2579         ED_object_base_activate(C, basen);
2580
2581         copy_object_set_idnew(C);
2582
2583         BKE_main_id_clear_newpoins(bmain);
2584
2585         /* TODO(sergey): Only update relations for the current scene. */
2586         DEG_relations_tag_update(bmain);
2587
2588         DEG_id_tag_update(&scene->id, DEG_TAG_SELECT_UPDATE);
2589         WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene);
2590         WM_event_add_notifier(C, NC_SCENE | ND_OB_ACTIVE, scene);
2591
2592         return OPERATOR_FINISHED;
2593 }
2594
2595 void OBJECT_OT_add_named(wmOperatorType *ot)
2596 {
2597         /* identifiers */
2598         ot->name = "Add Named Object";
2599         ot->description = "Add named object";
2600         ot->idname = "OBJECT_OT_add_named";
2601
2602         /* api callbacks */
2603         ot->exec = add_named_exec;
2604         ot->poll = ED_operator_objectmode;
2605
2606         /* flags */
2607         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2608
2609         RNA_def_boolean(ot->srna, "linked", 0, "Linked", "Duplicate object but not object data, linking to the original data");
2610         RNA_def_string(ot->srna, "name", NULL, MAX_ID_NAME - 2, "Name", "Object name to add");
2611 }
2612
2613 /**************************** Join *************************/
2614
2615 static bool join_poll(bContext *C)
2616 {
2617         Object *ob = CTX_data_active_object(C);
2618
2619         if (!ob || ID_IS_LINKED(ob)) return 0;
2620
2621         if (ELEM(ob->type, OB_MESH, OB_CURVE, OB_SURF, OB_ARMATURE, OB_GPENCIL))
2622                 return ED_operator_screenactive(C);
2623         else
2624                 return 0;
2625 }
2626
2627 static int join_exec(bContext *C, wmOperator *op)
2628 {
2629         Object *ob = CTX_data_active_object(C);
2630
2631         if (ob->mode & OB_MODE_EDIT) {
2632                 BKE_report(op->reports, RPT_ERROR, "This data does not support joining in edit mode");
2633                 return OPERATOR_CANCELLED;
2634         }
2635         else if (BKE_object_obdata_is_libdata(ob)) {
2636                 BKE_report(op->reports, RPT_ERROR, "Cannot edit external libdata");
2637                 return OPERATOR_CANCELLED;
2638         }
2639         else if (ob->type == OB_GPENCIL) {
2640                 bGPdata *gpd = (bGPdata *)ob->data;
2641                 if ((!gpd) || GPENCIL_ANY_MODE(gpd)) {
2642                         BKE_report(op->reports, RPT_ERROR, "This data does not support joining in this mode");
2643                         return OPERATOR_CANCELLED;
2644                 }
2645         }
2646
2647         if (ob->type == OB_MESH)
2648                 return join_mesh_exec(C, op);
2649         else if (ELEM(ob->type, OB_CURVE, OB_SURF))
2650                 return join_curve_exec(C, op);
2651         else if (ob->type == OB_ARMATURE)
2652                 return join_armature_exec(C, op);
2653         else if (ob->type == OB_GPENCIL)
2654                 return ED_gpencil_join_objects_exec(C, op);
2655
2656         return OPERATOR_CANCELLED;
2657 }
2658
2659 void OBJECT_OT_join(wmOperatorType *ot)
2660 {
2661         /* identifiers */
2662         ot->name = "Join";
2663         ot->description = "Join selected objects into active object";
2664         ot->idname = "OBJECT_OT_join";
2665
2666         /* api callbacks */
2667         ot->exec = join_exec;
2668         ot->poll = join_poll;
2669
2670         /* flags */
2671         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2672 }
2673
2674 /**************************** Join as Shape Key*************************/
2675
2676 static bool join_shapes_poll(bContext *C)
2677 {
2678         Object *ob = CTX_data_active_object(C);
2679
2680         if (!ob || ID_IS_LINKED(ob)) return 0;
2681
2682         /* only meshes supported at the moment */
2683         if (ob->type == OB_MESH)
2684                 return ED_operator_screenactive(C);
2685         else
2686                 return 0;
2687 }
2688
2689 static int join_shapes_exec(bContext *C, wmOperator *op)
2690 {
2691         Object *ob = CTX_data_active_object(C);
2692
2693         if (ob->mode & OB_MODE_EDIT) {
2694                 BKE_report(op->reports, RPT_ERROR, "This data does not support joining in edit mode");
2695                 return OPERATOR_CANCELLED;
2696         }
2697         else if (BKE_object_obdata_is_libdata(ob)) {
2698                 BKE_report(op->reports, RPT_ERROR, "Cannot edit external libdata");
2699                 return OPERATOR_CANCELLED;
2700         }
2701
2702         if (ob->type == OB_MESH)
2703                 return join_mesh_shapes_exec(C, op);
2704
2705         return OPERATOR_CANCELLED;
2706 }
2707
2708 void OBJECT_OT_join_shapes(wmOperatorType *ot)
2709 {
2710         /* identifiers */
2711         ot->name = "Join as Shapes";
2712         ot->description = "Merge selected objects to shapes of active object";
2713         ot->idname = "OBJECT_OT_join_shapes";
2714
2715         /* api callbacks */
2716         ot->exec = join_shapes_exec;
2717         ot->poll = join_shapes_poll;
2718
2719         /* flags */
2720         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2721 }