Merge branch 'master' into blender2.8
[blender.git] / source / blender / editors / object / object_edit.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_edit.c
27  *  \ingroup edobj
28  */
29
30 #include <stdlib.h>
31 #include <string.h>
32 #include <math.h>
33 #include <time.h>
34 #include <float.h>
35 #include <ctype.h>
36 #include <stddef.h> //for offsetof
37
38 #include "MEM_guardedalloc.h"
39
40 #include "BLI_blenlib.h"
41 #include "BLI_math.h"
42 #include "BLI_utildefines.h"
43 #include "BLI_ghash.h"
44 #include "BLI_string_utils.h"
45
46 #include "BLT_translation.h"
47
48 #include "DNA_armature_types.h"
49 #include "DNA_curve_types.h"
50 #include "DNA_gpencil_types.h"
51 #include "DNA_group_types.h"
52 #include "DNA_material_types.h"
53 #include "DNA_meta_types.h"
54 #include "DNA_scene_types.h"
55 #include "DNA_object_types.h"
56 #include "DNA_object_force_types.h"
57 #include "DNA_meshdata_types.h"
58 #include "DNA_vfont_types.h"
59 #include "DNA_mesh_types.h"
60 #include "DNA_lattice_types.h"
61 #include "DNA_workspace_types.h"
62
63 #include "IMB_imbuf_types.h"
64
65 #include "BKE_anim.h"
66 #include "BKE_collection.h"
67 #include "BKE_constraint.h"
68 #include "BKE_context.h"
69 #include "BKE_curve.h"
70 #include "BKE_effect.h"
71 #include "BKE_global.h"
72 #include "BKE_image.h"
73 #include "BKE_lattice.h"
74 #include "BKE_library.h"
75 #include "BKE_main.h"
76 #include "BKE_material.h"
77 #include "BKE_mball.h"
78 #include "BKE_mesh.h"
79 #include "BKE_object.h"
80 #include "BKE_paint.h"
81 #include "BKE_pointcache.h"
82 #include "BKE_softbody.h"
83 #include "BKE_modifier.h"
84 #include "BKE_editlattice.h"
85 #include "BKE_editmesh.h"
86 #include "BKE_report.h"
87 #include "BKE_workspace.h"
88 #include "BKE_layer.h"
89
90 #include "DEG_depsgraph.h"
91 #include "DEG_depsgraph_build.h"
92
93 #include "ED_armature.h"
94 #include "ED_curve.h"
95 #include "ED_mesh.h"
96 #include "ED_mball.h"
97 #include "ED_lattice.h"
98 #include "ED_object.h"
99 #include "ED_screen.h"
100 #include "ED_undo.h"
101 #include "ED_image.h"
102
103 #include "RNA_access.h"
104 #include "RNA_define.h"
105 #include "RNA_enum_types.h"
106
107 /* for menu/popup icons etc etc*/
108
109 #include "UI_interface.h"
110 #include "UI_resources.h"
111
112 #include "WM_api.h"
113 #include "WM_types.h"
114 #include "WM_message.h"
115 #include "WM_toolsystem.h"
116
117 #include "object_intern.h"  // own include
118
119 /* prototypes */
120 typedef struct MoveToCollectionData MoveToCollectionData;
121 static void move_to_collection_menus_items(struct uiLayout *layout, struct MoveToCollectionData *menu);
122
123 /* ************* XXX **************** */
124 static void error(const char *UNUSED(arg)) {}
125 static void waitcursor(int UNUSED(val)) {}
126 static int pupmenu(const char *UNUSED(msg)) { return 0; }
127
128 /* port over here */
129 static void error_libdata(void) {}
130
131 Object *ED_object_context(bContext *C)
132 {
133         return CTX_data_pointer_get_type(C, "object", &RNA_Object).data;
134 }
135
136 /* find the correct active object per context
137  * note: context can be NULL when called from a enum with PROP_ENUM_NO_CONTEXT */
138 Object *ED_object_active_context(bContext *C)
139 {
140         Object *ob = NULL;
141         if (C) {
142                 ob = ED_object_context(C);
143                 if (!ob) ob = CTX_data_active_object(C);
144         }
145         return ob;
146 }
147
148
149 /* ******************* toggle editmode operator  ***************** */
150
151 static bool mesh_needs_keyindex(const Mesh *me)
152 {
153         if (me->key) {
154                 return false;  /* will be added */
155         }
156
157         for (const Object *ob = G.main->object.first; ob; ob = ob->id.next) {
158                 if ((ob->parent) && (ob->parent->data == me) && ELEM(ob->partype, PARVERT1, PARVERT3)) {
159                         return true;
160                 }
161                 if (ob->data == me) {
162                         for (const ModifierData *md = ob->modifiers.first; md; md = md->next) {
163                                 if (md->type == eModifierType_Hook) {
164                                         return true;
165                                 }
166                         }
167                 }
168         }
169         return false;
170 }
171
172 /**
173  * Load EditMode data back into the object,
174  * optionally freeing the editmode data.
175  */
176 static bool ED_object_editmode_load_ex(Main *bmain, Object *obedit, const bool freedata)
177 {
178         if (obedit == NULL) {
179                 return false;
180         }
181
182         if (obedit->type == OB_MESH) {
183                 Mesh *me = obedit->data;
184                 if (me->edit_btmesh == NULL) {
185                         return false;
186                 }
187
188                 if (me->edit_btmesh->bm->totvert > MESH_MAX_VERTS) {
189                         error("Too many vertices");
190                         return false;
191                 }
192
193                 EDBM_mesh_load(obedit);
194
195                 if (freedata) {
196                         EDBM_mesh_free(me->edit_btmesh);
197                         MEM_freeN(me->edit_btmesh);
198                         me->edit_btmesh = NULL;
199                 }
200                 /* will be recalculated as needed. */
201                 {
202                         ED_mesh_mirror_spatial_table(NULL, NULL, NULL, NULL, 'e');
203                         ED_mesh_mirror_topo_table(NULL, NULL, 'e');
204                 }
205         }
206         else if (obedit->type == OB_ARMATURE) {
207                 const bArmature *arm = obedit->data;
208                 if (arm->edbo == NULL) {
209                         return false;
210                 }
211                 ED_armature_from_edit(obedit->data);
212                 if (freedata) {
213                         ED_armature_edit_free(obedit->data);
214                 }
215                 /* TODO(sergey): Pose channels might have been changed, so need
216                  * to inform dependency graph about this. But is it really the
217                  * best place to do this?
218                  */
219                 DEG_relations_tag_update(bmain);
220         }
221         else if (ELEM(obedit->type, OB_CURVE, OB_SURF)) {
222                 const Curve *cu = obedit->data;
223                 if (cu->editnurb == NULL) {
224                         return false;
225                 }
226                 ED_curve_editnurb_load(obedit);
227                 if (freedata) {
228                         ED_curve_editnurb_free(obedit);
229                 }
230         }
231         else if (obedit->type == OB_FONT) {
232                 const Curve *cu = obedit->data;
233                 if (cu->editfont == NULL) {
234                         return false;
235                 }
236                 ED_curve_editfont_load(obedit);
237                 if (freedata) {
238                         ED_curve_editfont_free(obedit);
239                 }
240         }
241         else if (obedit->type == OB_LATTICE) {
242                 const Lattice *lt = obedit->data;
243                 if (lt->editlatt == NULL) {
244                         return false;
245                 }
246                 BKE_editlattice_load(obedit);
247                 if (freedata) {
248                         BKE_editlattice_free(obedit);
249                 }
250         }
251         else if (obedit->type == OB_MBALL) {
252                 const MetaBall *mb = obedit->data;
253                 if (mb->editelems == NULL) {
254                         return false;
255                 }
256                 ED_mball_editmball_load(obedit);
257                 if (freedata) {
258                         ED_mball_editmball_free(obedit);
259                 }
260         }
261
262         return true;
263 }
264
265 bool ED_object_editmode_load(Object *obedit)
266 {
267         /* TODO(sergey): use proper main here? */
268         return ED_object_editmode_load_ex(G.main, obedit, false);
269 }
270
271 /**
272  * \param flag:
273  * - If #EM_FREEDATA isn't in the flag, use ED_object_editmode_load directly.
274  */
275 void ED_object_editmode_exit_ex(Scene *scene, Object *obedit, int flag)
276 {
277         const bool freedata = (flag & EM_FREEDATA) != 0;
278
279         if (flag & EM_WAITCURSOR) waitcursor(1);
280
281         if (ED_object_editmode_load_ex(G.main, obedit, freedata) == false) {
282                 /* in rare cases (background mode) its possible active object
283                  * is flagged for editmode, without 'obedit' being set [#35489] */
284                 if (UNLIKELY(obedit && obedit->mode & OB_MODE_EDIT)) {
285                         obedit->mode &= ~OB_MODE_EDIT;
286                 }
287                 if (flag & EM_WAITCURSOR) waitcursor(0);
288                 return;
289         }
290
291         /* freedata only 0 now on file saves and render */
292         if (freedata) {
293                 ListBase pidlist;
294                 PTCacheID *pid;
295
296                 /* flag object caches as outdated */
297                 BKE_ptcache_ids_from_object(&pidlist, obedit, scene, 0);
298                 for (pid = pidlist.first; pid; pid = pid->next) {
299                         if (pid->type != PTCACHE_TYPE_PARTICLES) /* particles don't need reset on geometry change */
300                                 pid->cache->flag |= PTCACHE_OUTDATED;
301                 }
302                 BLI_freelistN(&pidlist);
303                 
304                 BKE_ptcache_object_reset(scene, obedit, PTCACHE_RESET_OUTDATED);
305
306                 /* also flush ob recalc, doesn't take much overhead, but used for particles */
307                 DEG_id_tag_update(&obedit->id, OB_RECALC_OB | OB_RECALC_DATA);
308
309                 WM_main_add_notifier(NC_SCENE | ND_MODE | NS_MODE_OBJECT, scene);
310
311
312                 obedit->mode &= ~OB_MODE_EDIT;
313         }
314
315         if (flag & EM_WAITCURSOR) waitcursor(0);
316 }
317
318 void ED_object_editmode_exit(bContext *C, int flag)
319 {
320         Scene *scene = CTX_data_scene(C);
321         Object *obedit = CTX_data_edit_object(C);
322         ED_object_editmode_exit_ex(scene, obedit, flag);
323 }
324
325 void ED_object_editmode_enter_ex(Scene *scene, Object *ob, int flag)
326 {
327         bool ok = false;
328
329         if (ELEM(NULL, ob, ob->data)) return;
330         if (ID_IS_LINKED(ob)) return;
331
332         /* this checks actual object->data, for cases when other scenes have it in editmode context */
333         if (BKE_object_is_in_editmode(ob))
334                 return;
335         
336         if (BKE_object_obdata_is_libdata(ob)) {
337                 error_libdata();
338                 return;
339         }
340
341         if (flag & EM_WAITCURSOR) waitcursor(1);
342
343         ob->restore_mode = ob->mode;
344
345         ob->mode = OB_MODE_EDIT;
346
347         if (ob->type == OB_MESH) {
348                 BMEditMesh *em;
349                 ok = 1;
350                 const bool use_key_index = mesh_needs_keyindex(ob->data);
351
352                 EDBM_mesh_make(ob, scene->toolsettings->selectmode, use_key_index);
353
354                 em = BKE_editmesh_from_object(ob);
355                 if (LIKELY(em)) {
356                         /* order doesn't matter */
357                         EDBM_mesh_normals_update(em);
358                         BKE_editmesh_tessface_calc(em);
359                 }
360
361                 WM_main_add_notifier(NC_SCENE | ND_MODE | NS_EDITMODE_MESH, NULL);
362         }
363         else if (ob->type == OB_ARMATURE) {
364                 bArmature *arm = ob->data;
365                 if (!arm) return;
366                 /*
367                  * The function BKE_object_obdata_is_libdata make a problem here, the
368                  * check for ob->proxy return 0 and let blender enter to edit mode
369                  * this causes a crash when you try leave the edit mode.
370                  * The problem is that i can't remove the ob->proxy check from
371                  * BKE_object_obdata_is_libdata that prevent the bugfix #6614, so
372                  * i add this little hack here.
373                  */
374                 if (ID_IS_LINKED(arm)) {
375                         error_libdata();
376                         return;
377                 }
378                 ok = 1;
379                 ED_armature_to_edit(arm);
380                 /* to ensure all goes in restposition and without striding */
381                 DEG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME); /* XXX: should this be OB_RECALC_DATA? */
382
383                 WM_main_add_notifier(NC_SCENE | ND_MODE | NS_EDITMODE_ARMATURE, scene);
384         }
385         else if (ob->type == OB_FONT) {
386                 ok = 1;
387                 ED_curve_editfont_make(ob);
388
389                 WM_main_add_notifier(NC_SCENE | ND_MODE | NS_EDITMODE_TEXT, scene);
390         }
391         else if (ob->type == OB_MBALL) {
392                 ok = 1;
393                 ED_mball_editmball_make(ob);
394
395                 WM_main_add_notifier(NC_SCENE | ND_MODE | NS_EDITMODE_MBALL, scene);
396         }
397         else if (ob->type == OB_LATTICE) {
398                 ok = 1;
399                 BKE_editlattice_make(ob);
400
401                 WM_main_add_notifier(NC_SCENE | ND_MODE | NS_EDITMODE_LATTICE, scene);
402         }
403         else if (ob->type == OB_SURF || ob->type == OB_CURVE) {
404                 ok = 1;
405                 ED_curve_editnurb_make(ob);
406
407                 WM_main_add_notifier(NC_SCENE | ND_MODE | NS_EDITMODE_CURVE, scene);
408         }
409
410         if (ok) {
411                 DEG_id_tag_update(&ob->id, OB_RECALC_DATA);
412         }
413         else {
414                 if ((flag & EM_NO_CONTEXT) == 0) {
415                         ob->mode &= ~OB_MODE_EDIT;
416                 }
417                 WM_main_add_notifier(NC_SCENE | ND_MODE | NS_MODE_OBJECT, scene);
418         }
419
420         if (flag & EM_WAITCURSOR) waitcursor(0);
421 }
422
423 void ED_object_editmode_enter(bContext *C, int flag)
424 {
425         Scene *scene = CTX_data_scene(C);
426         ViewLayer *view_layer = CTX_data_view_layer(C);
427         Object *ob;
428
429         if ((flag & EM_IGNORE_LAYER) == 0) {
430                 ob = CTX_data_active_object(C); /* active layer checked here for view3d */
431         }
432         else {
433                 ob = view_layer->basact->object;
434         }
435         if (ob == NULL) return;
436         if (ID_IS_LINKED(ob)) return;
437
438         ED_object_editmode_enter_ex(scene, ob, flag);
439 }
440
441 static int editmode_toggle_exec(bContext *C, wmOperator *op)
442 {
443         struct wmMsgBus *mbus = CTX_wm_message_bus(C);
444         const int mode_flag = OB_MODE_EDIT;
445         const bool is_mode_set = (CTX_data_edit_object(C) != NULL);
446         Scene *scene =  CTX_data_scene(C);
447         ViewLayer *view_layer = CTX_data_view_layer(C);
448         Object *obact = OBACT(view_layer);
449
450         if (!is_mode_set) {
451                 if (!ED_object_mode_compat_set(C, obact, mode_flag, op->reports)) {
452                         return OPERATOR_CANCELLED;
453                 }
454         }
455
456         if (!is_mode_set) {
457                 ED_object_editmode_enter(C, EM_WAITCURSOR);
458                 if (obact->mode & mode_flag) {
459                         FOREACH_SELECTED_OBJECT_BEGIN(view_layer, ob)
460                         {
461                                 if ((ob != obact) && (ob->type == obact->type)) {
462                                         ED_object_editmode_enter_ex(scene, ob, EM_WAITCURSOR | EM_NO_CONTEXT);
463                                 }
464                         }
465                         FOREACH_SELECTED_OBJECT_END;
466                 }
467         }
468         else {
469                 ED_object_editmode_exit(C, EM_FREEDATA | EM_WAITCURSOR);
470                 if ((obact->mode & mode_flag) == 0) {
471                         FOREACH_OBJECT_BEGIN(view_layer, ob)
472                         {
473                                 if ((ob != obact) && (ob->type == obact->type)) {
474                                         ED_object_editmode_exit_ex(scene, ob, EM_FREEDATA | EM_WAITCURSOR);
475                                 }
476                         }
477                         FOREACH_OBJECT_END;
478                 }
479         }
480
481         ED_space_image_uv_sculpt_update(CTX_wm_manager(C), scene);
482
483         WM_msg_publish_rna_prop(mbus, &obact->id, obact, Object, mode);
484
485         WM_toolsystem_update_from_context_view3d(C);
486
487         return OPERATOR_FINISHED;
488 }
489
490 static int editmode_toggle_poll(bContext *C)
491 {
492         Object *ob = CTX_data_active_object(C);
493
494         /* covers proxies too */
495         if (ELEM(NULL, ob, ob->data) || ID_IS_LINKED(ob->data))
496                 return 0;
497
498         /* if hidden but in edit mode, we still display */
499         if ((ob->restrictflag & OB_RESTRICT_VIEW) && !(ob->mode & OB_MODE_EDIT)) {
500                 return 0;
501         }
502
503         return OB_TYPE_SUPPORT_EDITMODE(ob->type);
504 }
505
506 void OBJECT_OT_editmode_toggle(wmOperatorType *ot)
507 {
508         
509         /* identifiers */
510         ot->name = "Toggle Editmode";
511         ot->description = "Toggle object's editmode";
512         ot->idname = "OBJECT_OT_editmode_toggle";
513         
514         /* api callbacks */
515         ot->exec = editmode_toggle_exec;
516         ot->poll = editmode_toggle_poll;
517         
518         /* flags */
519         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
520 }
521
522 /* *************************** */
523
524 static int posemode_exec(bContext *C, wmOperator *op)
525 {
526         struct wmMsgBus *mbus = CTX_wm_message_bus(C);
527         Base *base = CTX_data_active_base(C);
528         Object *obact = base->object;
529         const int mode_flag = OB_MODE_POSE;
530         bool is_mode_set = (obact->mode & mode_flag) != 0;
531         
532         if (!is_mode_set) {
533                 if (!ED_object_mode_compat_set(C, obact, mode_flag, op->reports)) {
534                         return OPERATOR_CANCELLED;
535                 }
536         }
537
538         if (obact->type != OB_ARMATURE) {
539                 return OPERATOR_PASS_THROUGH;
540         }
541
542         if (obact == CTX_data_edit_object(C)) {
543                 ED_object_editmode_exit(C, EM_FREEDATA);
544                 is_mode_set = false;
545         }
546
547         if (is_mode_set) {
548                 bool ok = ED_object_posemode_exit(C, obact);
549                 if (ok) {
550                         struct Main *bmain = CTX_data_main(C);
551                         ViewLayer *view_layer = CTX_data_view_layer(C);
552                         FOREACH_OBJECT_BEGIN(view_layer, ob)
553                         {
554                                 if ((ob != obact) &&
555                                     (ob->type == OB_ARMATURE) &&
556                                     (ob->mode & mode_flag))
557                                 {
558                                         ED_object_posemode_exit_ex(bmain, ob);
559                                 }
560                         }
561                         FOREACH_OBJECT_END;
562                 }
563         }
564         else {
565                 bool ok = ED_object_posemode_enter(C, obact);
566                 if (ok) {
567                         struct Main *bmain = CTX_data_main(C);
568                         ViewLayer *view_layer = CTX_data_view_layer(C);
569                         FOREACH_SELECTED_OBJECT_BEGIN(view_layer, ob)
570                         {
571                                 if ((ob != obact) &&
572                                     (ob->type == OB_ARMATURE) &&
573                                     (ob->mode == OB_MODE_OBJECT) &&
574                                     (!ID_IS_LINKED(ob)))
575                                 {
576                                         ED_object_posemode_enter_ex(bmain, ob);
577                                 }
578                         }
579                         FOREACH_SELECTED_OBJECT_END;
580                 }
581         }
582
583         WM_msg_publish_rna_prop(mbus, &obact->id, obact, Object, mode);
584
585         WM_toolsystem_update_from_context_view3d(C);
586
587         return OPERATOR_FINISHED;
588 }
589
590 void OBJECT_OT_posemode_toggle(wmOperatorType *ot) 
591 {
592         /* identifiers */
593         ot->name = "Toggle Pose Mode";
594         ot->idname = "OBJECT_OT_posemode_toggle";
595         ot->description = "Enable or disable posing/selecting bones";
596         
597         /* api callbacks */
598         ot->exec = posemode_exec;
599         ot->poll = ED_operator_object_active_editable;
600         
601         /* flag */
602         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
603 }
604
605 /* both pointers should exist */
606 static void copy_texture_space(Object *to, Object *ob)
607 {
608         float *poin1 = NULL, *poin2 = NULL;
609         short texflag = 0;
610         
611         if (ob->type == OB_MESH) {
612                 texflag = ((Mesh *)ob->data)->texflag;
613                 poin2 = ((Mesh *)ob->data)->loc;
614         }
615         else if (ELEM(ob->type, OB_CURVE, OB_SURF, OB_FONT)) {
616                 texflag = ((Curve *)ob->data)->texflag;
617                 poin2 = ((Curve *)ob->data)->loc;
618         }
619         else if (ob->type == OB_MBALL) {
620                 texflag = ((MetaBall *)ob->data)->texflag;
621                 poin2 = ((MetaBall *)ob->data)->loc;
622         }
623         else
624                 return;
625                 
626         if (to->type == OB_MESH) {
627                 ((Mesh *)to->data)->texflag = texflag;
628                 poin1 = ((Mesh *)to->data)->loc;
629         }
630         else if (ELEM(to->type, OB_CURVE, OB_SURF, OB_FONT)) {
631                 ((Curve *)to->data)->texflag = texflag;
632                 poin1 = ((Curve *)to->data)->loc;
633         }
634         else if (to->type == OB_MBALL) {
635                 ((MetaBall *)to->data)->texflag = texflag;
636                 poin1 = ((MetaBall *)to->data)->loc;
637         }
638         else
639                 return;
640         
641         memcpy(poin1, poin2, 9 * sizeof(float));  /* this was noted in DNA_mesh, curve, mball */
642         
643         if (to->type == OB_MESH) {
644                 /* pass */
645         }
646         else if (to->type == OB_MBALL) {
647                 BKE_mball_texspace_calc(to);
648         }
649         else {
650                 BKE_curve_texspace_calc(to->data);
651         }
652         
653 }
654
655 /* UNUSED, keep in case we want to copy functionality for use elsewhere */
656 static void copy_attr(Main *bmain, Scene *scene, ViewLayer *view_layer, short event)
657 {
658         Object *ob;
659         Base *base;
660         Curve *cu, *cu1;
661         Nurb *nu;
662         bool do_depgraph_update = false;
663         
664         if (ID_IS_LINKED(scene)) return;
665
666         if (!(ob = OBACT(view_layer))) return;
667         
668         if (BKE_object_is_in_editmode(ob)) {
669                 /* obedit_copymenu(); */
670                 return;
671         }
672
673         if (event == 24) {
674                 /* moved to BKE_object_link_modifiers */
675                 /* copymenu_modifiers(bmain, scene, v3d, ob); */
676                 return;
677         }
678
679         for (base = FIRSTBASE(view_layer); base; base = base->next) {
680                 if (base != BASACT(view_layer)) {
681                         if (TESTBASELIB(base)) {
682                                 DEG_id_tag_update(&base->object->id, OB_RECALC_DATA);
683                                 
684                                 if (event == 1) {  /* loc */
685                                         copy_v3_v3(base->object->loc, ob->loc);
686                                         copy_v3_v3(base->object->dloc, ob->dloc);
687                                 }
688                                 else if (event == 2) {  /* rot */
689                                         copy_v3_v3(base->object->rot, ob->rot);
690                                         copy_v3_v3(base->object->drot, ob->drot);
691
692                                         copy_qt_qt(base->object->quat, ob->quat);
693                                         copy_qt_qt(base->object->dquat, ob->dquat);
694                                 }
695                                 else if (event == 3) {  /* size */
696                                         copy_v3_v3(base->object->size, ob->size);
697                                         copy_v3_v3(base->object->dscale, ob->dscale);
698                                 }
699                                 else if (event == 4) {  /* drawtype */
700                                         base->object->dt = ob->dt;
701                                         base->object->dtx = ob->dtx;
702                                         base->object->empty_drawtype = ob->empty_drawtype;
703                                         base->object->empty_drawsize = ob->empty_drawsize;
704                                 }
705                                 else if (event == 5) {  /* time offs */
706                                         base->object->sf = ob->sf;
707                                 }
708                                 else if (event == 6) {  /* dupli */
709                                         base->object->dupon = ob->dupon;
710                                         base->object->dupoff = ob->dupoff;
711                                         base->object->dupsta = ob->dupsta;
712                                         base->object->dupend = ob->dupend;
713                                         
714                                         base->object->transflag &= ~OB_DUPLI;
715                                         base->object->transflag |= (ob->transflag & OB_DUPLI);
716
717                                         base->object->dup_group = ob->dup_group;
718                                         if (ob->dup_group)
719                                                 id_us_plus(&ob->dup_group->id);
720                                 }
721                                 else if (event == 17) {   /* tex space */
722                                         copy_texture_space(base->object, ob);
723                                 }
724                                 else if (event == 18) {   /* font settings */
725                                         
726                                         if (base->object->type == ob->type) {
727                                                 cu = ob->data;
728                                                 cu1 = base->object->data;
729
730                                                 cu1->spacemode = cu->spacemode;
731                                                 cu1->align_y = cu->align_y;
732                                                 cu1->spacing = cu->spacing;
733                                                 cu1->linedist = cu->linedist;
734                                                 cu1->shear = cu->shear;
735                                                 cu1->fsize = cu->fsize;
736                                                 cu1->xof = cu->xof;
737                                                 cu1->yof = cu->yof;
738                                                 cu1->textoncurve = cu->textoncurve;
739                                                 cu1->wordspace = cu->wordspace;
740                                                 cu1->ulpos = cu->ulpos;
741                                                 cu1->ulheight = cu->ulheight;
742                                                 if (cu1->vfont)
743                                                         id_us_min(&cu1->vfont->id);
744                                                 cu1->vfont = cu->vfont;
745                                                 id_us_plus((ID *)cu1->vfont);
746                                                 if (cu1->vfontb)
747                                                         id_us_min(&cu1->vfontb->id);
748                                                 cu1->vfontb = cu->vfontb;
749                                                 id_us_plus((ID *)cu1->vfontb);
750                                                 if (cu1->vfonti)
751                                                         id_us_min(&cu1->vfonti->id);
752                                                 cu1->vfonti = cu->vfonti;
753                                                 id_us_plus((ID *)cu1->vfonti);
754                                                 if (cu1->vfontbi)
755                                                         id_us_min(&cu1->vfontbi->id);
756                                                 cu1->vfontbi = cu->vfontbi;
757                                                 id_us_plus((ID *)cu1->vfontbi);
758                                                 
759                                                 BLI_strncpy(cu1->family, cu->family, sizeof(cu1->family));
760                                                 
761                                                 DEG_id_tag_update(&base->object->id, OB_RECALC_DATA);
762                                         }
763                                 }
764                                 else if (event == 19) {   /* bevel settings */
765                                         
766                                         if (ELEM(base->object->type, OB_CURVE, OB_FONT)) {
767                                                 cu = ob->data;
768                                                 cu1 = base->object->data;
769                                                 
770                                                 cu1->bevobj = cu->bevobj;
771                                                 cu1->taperobj = cu->taperobj;
772                                                 cu1->width = cu->width;
773                                                 cu1->bevresol = cu->bevresol;
774                                                 cu1->ext1 = cu->ext1;
775                                                 cu1->ext2 = cu->ext2;
776                                                 
777                                                 DEG_id_tag_update(&base->object->id, OB_RECALC_DATA);
778                                         }
779                                 }
780                                 else if (event == 25) {   /* curve resolution */
781
782                                         if (ELEM(base->object->type, OB_CURVE, OB_FONT)) {
783                                                 cu = ob->data;
784                                                 cu1 = base->object->data;
785                                                 
786                                                 cu1->resolu = cu->resolu;
787                                                 cu1->resolu_ren = cu->resolu_ren;
788                                                 
789                                                 nu = cu1->nurb.first;
790                                                 
791                                                 while (nu) {
792                                                         nu->resolu = cu1->resolu;
793                                                         nu = nu->next;
794                                                 }
795                                                 
796                                                 DEG_id_tag_update(&base->object->id, OB_RECALC_DATA);
797                                         }
798                                 }
799                                 else if (event == 21) {
800                                         if (base->object->type == OB_MESH) {
801                                                 ModifierData *md = modifiers_findByType(ob, eModifierType_Subsurf);
802
803                                                 if (md) {
804                                                         ModifierData *tmd = modifiers_findByType(base->object, eModifierType_Subsurf);
805
806                                                         if (!tmd) {
807                                                                 tmd = modifier_new(eModifierType_Subsurf);
808                                                                 BLI_addtail(&base->object->modifiers, tmd);
809                                                         }
810
811                                                         modifier_copyData(md, tmd);
812                                                         DEG_id_tag_update(&base->object->id, OB_RECALC_DATA);
813                                                 }
814                                         }
815                                 }
816                                 else if (event == 22) {
817                                         /* Copy the constraint channels over */
818                                         BKE_constraints_copy(&base->object->constraints, &ob->constraints, true);
819                                         
820                                         do_depgraph_update = true;
821                                 }
822                                 else if (event == 23) {
823                                         base->object->softflag = ob->softflag;
824                                         if (base->object->soft) sbFree(base->object->soft);
825                                         
826                                         base->object->soft = copy_softbody(ob->soft, 0);
827
828                                         if (!modifiers_findByType(base->object, eModifierType_Softbody)) {
829                                                 BLI_addhead(&base->object->modifiers, modifier_new(eModifierType_Softbody));
830                                         }
831                                 }
832                                 else if (event == 26) {
833 #if 0 // XXX old animation system
834                                         BKE_nlastrip_copy(s(&base->object->nlastrips, &ob->nlastrips);
835 #endif // XXX old animation system
836                                 }
837                                 else if (event == 27) {   /* autosmooth */
838                                         if (base->object->type == OB_MESH) {
839                                                 Mesh *me = ob->data;
840                                                 Mesh *cme = base->object->data;
841                                                 cme->smoothresh = me->smoothresh;
842                                                 if (me->flag & ME_AUTOSMOOTH)
843                                                         cme->flag |= ME_AUTOSMOOTH;
844                                                 else
845                                                         cme->flag &= ~ME_AUTOSMOOTH;
846                                         }
847                                 }
848                                 else if (event == 28) { /* UV orco */
849                                         if (ELEM(base->object->type, OB_CURVE, OB_SURF)) {
850                                                 cu = ob->data;
851                                                 cu1 = base->object->data;
852                                                 
853                                                 if (cu->flag & CU_UV_ORCO)
854                                                         cu1->flag |= CU_UV_ORCO;
855                                                 else
856                                                         cu1->flag &= ~CU_UV_ORCO;
857                                         }
858                                 }
859                                 else if (event == 29) { /* protected bits */
860                                         base->object->protectflag = ob->protectflag;
861                                 }
862                                 else if (event == 30) { /* index object */
863                                         base->object->index = ob->index;
864                                 }
865                                 else if (event == 31) { /* object color */
866                                         copy_v4_v4(base->object->col, ob->col);
867                                 }
868                         }
869                 }
870         }
871         
872         if (do_depgraph_update)
873                 DEG_relations_tag_update(bmain);
874 }
875
876 static void UNUSED_FUNCTION(copy_attr_menu) (Main *bmain, Scene *scene, ViewLayer *view_layer, Object *obedit)
877 {
878         Object *ob;
879         short event;
880         char str[512];
881         
882         if (!(ob = OBACT(view_layer))) return;
883         
884         if (obedit) {
885 /*              if (ob->type == OB_MESH) */
886 /* XXX                  mesh_copy_menu(); */
887                 return;
888         }
889         
890         /* Object Mode */
891         
892         /* If you change this menu, don't forget to update the menu in header_view3d.c
893          * view3d_edit_object_copyattrmenu() and in toolbox.c
894          */
895         
896         strcpy(str,
897                "Copy Attributes %t|Location %x1|Rotation %x2|Size %x3|Draw Options %x4|"
898                "Time Offset %x5|Dupli %x6|Object Color %x31|%l|Mass %x7|Damping %x8|All Physical Attributes %x11|Properties %x9|"
899                "Logic Bricks %x10|Protected Transform %x29|%l");
900         
901         strcat(str, "|Object Constraints %x22");
902         strcat(str, "|NLA Strips %x26");
903         
904 /* XXX  if (OB_TYPE_SUPPORT_MATERIAL(ob->type)) { */
905 /*              strcat(str, "|Texture Space %x17"); */
906 /*      } */
907         
908         if (ob->type == OB_FONT) strcat(str, "|Font Settings %x18|Bevel Settings %x19");
909         if (ob->type == OB_CURVE) strcat(str, "|Bevel Settings %x19|UV Orco %x28");
910         
911         if ((ob->type == OB_FONT) || (ob->type == OB_CURVE)) {
912                 strcat(str, "|Curve Resolution %x25");
913         }
914
915         if (ob->type == OB_MESH) {
916                 strcat(str, "|Subsurf Settings %x21|AutoSmooth %x27");
917         }
918
919         if (ob->soft) strcat(str, "|Soft Body Settings %x23");
920         
921         strcat(str, "|Pass Index %x30");
922         
923         if (ob->type == OB_MESH || ob->type == OB_CURVE || ob->type == OB_LATTICE || ob->type == OB_SURF) {
924                 strcat(str, "|Modifiers ... %x24");
925         }
926
927         event = pupmenu(str);
928         if (event <= 0) return;
929         
930         copy_attr(bmain, scene, view_layer, event);
931 }
932
933 /* ******************* force field toggle operator ***************** */
934
935 void ED_object_check_force_modifiers(Main *bmain, Scene *scene, Object *object)
936 {
937         PartDeflect *pd = object->pd;
938         ModifierData *md = modifiers_findByType(object, eModifierType_Surface);
939
940         /* add/remove modifier as needed */
941         if (!md) {
942                 if (pd && (pd->shape == PFIELD_SHAPE_SURFACE) && !ELEM(pd->forcefield, 0, PFIELD_GUIDE, PFIELD_TEXTURE)) {
943                         if (ELEM(object->type, OB_MESH, OB_SURF, OB_FONT, OB_CURVE)) {
944                                 ED_object_modifier_add(NULL, bmain, scene, object, NULL, eModifierType_Surface);
945                         }
946                 }
947         }
948         else {
949                 if (!pd || (pd->shape != PFIELD_SHAPE_SURFACE) || ELEM(pd->forcefield, 0, PFIELD_GUIDE, PFIELD_TEXTURE)) {
950                         ED_object_modifier_remove(NULL, bmain, object, md);
951                 }
952         }
953 }
954
955 static int forcefield_toggle_exec(bContext *C, wmOperator *UNUSED(op))
956 {
957         Object *ob = CTX_data_active_object(C);
958
959         if (ob->pd == NULL)
960                 ob->pd = object_add_collision_fields(PFIELD_FORCE);
961         else if (ob->pd->forcefield == 0)
962                 ob->pd->forcefield = PFIELD_FORCE;
963         else
964                 ob->pd->forcefield = 0;
965
966         ED_object_check_force_modifiers(CTX_data_main(C), CTX_data_scene(C), ob);
967         WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, ob);
968         WM_event_add_notifier(C, NC_OBJECT | ND_MODIFIER, ob);
969
970         return OPERATOR_FINISHED;
971 }
972
973 void OBJECT_OT_forcefield_toggle(wmOperatorType *ot)
974 {
975         
976         /* identifiers */
977         ot->name = "Toggle Force Field";
978         ot->description = "Toggle object's force field";
979         ot->idname = "OBJECT_OT_forcefield_toggle";
980         
981         /* api callbacks */
982         ot->exec = forcefield_toggle_exec;
983         ot->poll = ED_operator_object_active_editable;
984         
985         /* flags */
986         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
987 }
988
989 /* ********************************************** */
990 /* Motion Paths */
991
992 /* For the objects with animation: update paths for those that have got them
993  * This should selectively update paths that exist...
994  *
995  * To be called from various tools that do incremental updates 
996  */
997 void ED_objects_recalculate_paths(bContext *C, Scene *scene)
998 {
999         struct Main *bmain = CTX_data_main(C);
1000         Depsgraph *depsgraph = CTX_data_depsgraph(C);
1001         ListBase targets = {NULL, NULL};
1002         
1003         /* loop over objects in scene */
1004         CTX_DATA_BEGIN(C, Object *, ob, selected_editable_objects)
1005         {
1006                 /* set flag to force recalc, then grab path(s) from object */
1007                 ob->avs.recalc |= ANIMVIZ_RECALC_PATHS;
1008                 animviz_get_object_motionpaths(ob, &targets);
1009         }
1010         CTX_DATA_END;
1011         
1012         /* recalculate paths, then free */
1013         animviz_calc_motionpaths(depsgraph, bmain, scene, &targets);
1014         BLI_freelistN(&targets);
1015 }
1016
1017
1018 /* show popup to determine settings */
1019 static int object_calculate_paths_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1020 {
1021         Object *ob = CTX_data_active_object(C);
1022         
1023         if (ob == NULL)
1024                 return OPERATOR_CANCELLED;
1025         
1026         /* set default settings from existing/stored settings */
1027         {
1028                 bAnimVizSettings *avs = &ob->avs;
1029                 
1030                 RNA_int_set(op->ptr, "start_frame", avs->path_sf);
1031                 RNA_int_set(op->ptr, "end_frame", avs->path_ef);
1032         }
1033         
1034         /* show popup dialog to allow editing of range... */
1035         /* FIXME: hardcoded dimensions here are just arbitrary */
1036         return WM_operator_props_dialog_popup(C, op, 10 * UI_UNIT_X, 10 * UI_UNIT_Y);
1037 }
1038
1039 /* Calculate/recalculate whole paths (avs.path_sf to avs.path_ef) */
1040 static int object_calculate_paths_exec(bContext *C, wmOperator *op)
1041 {
1042         Scene *scene = CTX_data_scene(C);
1043         int start = RNA_int_get(op->ptr, "start_frame");
1044         int end = RNA_int_get(op->ptr, "end_frame");
1045         
1046         /* set up path data for bones being calculated */
1047         CTX_DATA_BEGIN(C, Object *, ob, selected_editable_objects)
1048         {
1049                 bAnimVizSettings *avs = &ob->avs;
1050                 
1051                 /* grab baking settings from operator settings */
1052                 avs->path_sf = start;
1053                 avs->path_ef = end;
1054                 
1055                 /* verify that the selected object has the appropriate settings */
1056                 animviz_verify_motionpaths(op->reports, scene, ob, NULL);
1057         }
1058         CTX_DATA_END;
1059         
1060         /* calculate the paths for objects that have them (and are tagged to get refreshed) */
1061         ED_objects_recalculate_paths(C, scene);
1062         
1063         /* notifiers for updates */
1064         WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL);
1065         
1066         return OPERATOR_FINISHED; 
1067 }
1068
1069 void OBJECT_OT_paths_calculate(wmOperatorType *ot)
1070 {
1071         /* identifiers */
1072         ot->name = "Calculate Object Paths";
1073         ot->idname = "OBJECT_OT_paths_calculate";
1074         ot->description = "Calculate motion paths for the selected objects";
1075         
1076         /* api callbacks */
1077         ot->invoke = object_calculate_paths_invoke;
1078         ot->exec = object_calculate_paths_exec;
1079         ot->poll = ED_operator_object_active_editable;
1080         
1081         /* flags */
1082         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1083         
1084         /* properties */
1085         RNA_def_int(ot->srna, "start_frame", 1, MINAFRAME, MAXFRAME, "Start", 
1086                     "First frame to calculate object paths on", MINFRAME, MAXFRAME / 2.0);
1087         RNA_def_int(ot->srna, "end_frame", 250, MINAFRAME, MAXFRAME, "End", 
1088                     "Last frame to calculate object paths on", MINFRAME, MAXFRAME / 2.0);
1089 }
1090
1091 /* --------- */
1092
1093 static int object_update_paths_poll(bContext *C)
1094 {
1095         if (ED_operator_object_active_editable(C)) {
1096                 Object *ob = ED_object_active_context(C);
1097                 return (ob->avs.path_bakeflag & MOTIONPATH_BAKE_HAS_PATHS) != 0;
1098         }
1099         
1100         return false;
1101 }
1102
1103 static int object_update_paths_exec(bContext *C, wmOperator *UNUSED(op))
1104 {
1105         Scene *scene = CTX_data_scene(C);
1106         
1107         if (scene == NULL)
1108                 return OPERATOR_CANCELLED;
1109                 
1110         /* calculate the paths for objects that have them (and are tagged to get refreshed) */
1111         ED_objects_recalculate_paths(C, scene);
1112         
1113         /* notifiers for updates */
1114         WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL);
1115         
1116         return OPERATOR_FINISHED;
1117 }
1118
1119 void OBJECT_OT_paths_update(wmOperatorType *ot)
1120 {
1121         /* identifiers */
1122         ot->name = "Update Object Paths";
1123         ot->idname = "OBJECT_OT_paths_update";
1124         ot->description = "Recalculate paths for selected objects";
1125         
1126         /* api callbakcs */
1127         ot->exec = object_update_paths_exec;
1128         ot->poll = object_update_paths_poll;
1129         
1130         /* flags */
1131         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1132 }
1133
1134 /* --------- */
1135
1136 /* Helper for ED_objects_clear_paths() */
1137 static void object_clear_mpath(Object *ob)
1138 {
1139         if (ob->mpath) {
1140                 animviz_free_motionpath(ob->mpath);
1141                 ob->mpath = NULL;
1142                 ob->avs.path_bakeflag &= ~MOTIONPATH_BAKE_HAS_PATHS;
1143         }
1144 }
1145
1146 /* Clear motion paths for all objects */
1147 void ED_objects_clear_paths(bContext *C, bool only_selected)
1148 {
1149         if (only_selected) {
1150                 /* loop over all selected + sedtiable objects in scene */
1151                 CTX_DATA_BEGIN(C, Object *, ob, selected_editable_objects)
1152                 {
1153                         object_clear_mpath(ob);
1154                 }
1155                 CTX_DATA_END;
1156         }
1157         else {
1158                 /* loop over all edtiable objects in scene */
1159                 CTX_DATA_BEGIN(C, Object *, ob, editable_objects)
1160                 {
1161                         object_clear_mpath(ob);
1162                 }
1163                 CTX_DATA_END;
1164         }
1165 }
1166
1167 /* operator callback for this */
1168 static int object_clear_paths_exec(bContext *C, wmOperator *op)
1169 {
1170         bool only_selected = RNA_boolean_get(op->ptr, "only_selected");
1171         
1172         /* use the backend function for this */
1173         ED_objects_clear_paths(C, only_selected);
1174         
1175         /* notifiers for updates */
1176         WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL);
1177         
1178         return OPERATOR_FINISHED; 
1179 }
1180
1181 /* operator callback/wrapper */
1182 static int object_clear_paths_invoke(bContext *C, wmOperator *op, const wmEvent *evt)
1183 {
1184         if ((evt->shift) && !RNA_struct_property_is_set(op->ptr, "only_selected")) {
1185                 RNA_boolean_set(op->ptr, "only_selected", true);
1186         }
1187         return object_clear_paths_exec(C, op);
1188 }
1189
1190 void OBJECT_OT_paths_clear(wmOperatorType *ot)
1191 {
1192         /* identifiers */
1193         ot->name = "Clear Object Paths";
1194         ot->idname = "OBJECT_OT_paths_clear";
1195         ot->description = "Clear path caches for all objects, hold Shift key for selected objects only";
1196         
1197         /* api callbacks */
1198         ot->invoke = object_clear_paths_invoke;
1199         ot->exec = object_clear_paths_exec;
1200         ot->poll = ED_operator_object_active_editable;
1201         
1202         /* flags */
1203         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1204         
1205         /* properties */
1206         ot->prop = RNA_def_boolean(ot->srna, "only_selected", false, "Only Selected",
1207                                    "Only clear paths from selected objects");
1208         RNA_def_property_flag(ot->prop, PROP_SKIP_SAVE);
1209 }
1210
1211
1212 /********************** Smooth/Flat *********************/
1213
1214 static int shade_smooth_exec(bContext *C, wmOperator *op)
1215 {
1216         ID *data;
1217         Curve *cu;
1218         Nurb *nu;
1219         int clear = (STREQ(op->idname, "OBJECT_OT_shade_flat"));
1220         bool done = false, linked_data = false;
1221
1222         CTX_DATA_BEGIN(C, Object *, ob, selected_editable_objects)
1223         {
1224                 data = ob->data;
1225
1226                 if (data && ID_IS_LINKED(data)) {
1227                         linked_data = true;
1228                         continue;
1229                 }
1230
1231                 if (ob->type == OB_MESH) {
1232                         BKE_mesh_smooth_flag_set(ob, !clear);
1233
1234                         BKE_mesh_batch_cache_dirty(ob->data, BKE_MESH_BATCH_DIRTY_ALL);
1235                         DEG_id_tag_update(&ob->id, OB_RECALC_DATA);
1236                         WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, ob);
1237
1238                         done = true;
1239                 }
1240                 else if (ELEM(ob->type, OB_SURF, OB_CURVE)) {
1241                         cu = ob->data;
1242
1243                         for (nu = cu->nurb.first; nu; nu = nu->next) {
1244                                 if (!clear) nu->flag |= ME_SMOOTH;
1245                                 else nu->flag &= ~ME_SMOOTH;
1246                         }
1247
1248                         DEG_id_tag_update(&ob->id, OB_RECALC_DATA);
1249                         WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, ob);
1250
1251                         done = true;
1252                 }
1253         }
1254         CTX_DATA_END;
1255
1256         if (linked_data)
1257                 BKE_report(op->reports, RPT_WARNING, "Can't edit linked mesh or curve data");
1258
1259         return (done) ? OPERATOR_FINISHED : OPERATOR_CANCELLED;
1260 }
1261
1262 static int shade_poll(bContext *C)
1263 {
1264         return (CTX_data_edit_object(C) == NULL);
1265 }
1266
1267 void OBJECT_OT_shade_flat(wmOperatorType *ot)
1268 {
1269         /* identifiers */
1270         ot->name = "Shade Flat";
1271         ot->description = "Render and display faces uniform, using Face Normals";
1272         ot->idname = "OBJECT_OT_shade_flat";
1273         
1274         /* api callbacks */
1275         ot->poll = shade_poll;
1276         ot->exec = shade_smooth_exec;
1277
1278         /* flags */
1279         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1280 }
1281
1282 void OBJECT_OT_shade_smooth(wmOperatorType *ot)
1283 {
1284         /* identifiers */
1285         ot->name = "Shade Smooth";
1286         ot->description = "Render and display faces smooth, using interpolated Vertex Normals";
1287         ot->idname = "OBJECT_OT_shade_smooth";
1288         
1289         /* api callbacks */
1290         ot->poll = shade_poll;
1291         ot->exec = shade_smooth_exec;
1292         
1293         /* flags */
1294         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1295 }
1296
1297 /* ********************** */
1298
1299 static const EnumPropertyItem *object_mode_set_itemsf(
1300         bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free)
1301 {
1302         const EnumPropertyItem *input = rna_enum_object_mode_items;
1303         EnumPropertyItem *item = NULL;
1304         Object *ob;
1305         bGPdata *gpd;
1306         int totitem = 0;
1307
1308         if (!C) /* needed for docs */
1309                 return rna_enum_object_mode_items;
1310
1311         ob = CTX_data_active_object(C);
1312         if (ob) {
1313                 const bool use_mode_particle_edit = (BLI_listbase_is_empty(&ob->particlesystem) == false) ||
1314                                                     (ob->soft != NULL) ||
1315                                                     (modifiers_findByType(ob, eModifierType_Cloth) != NULL);
1316                 while (input->identifier) {
1317                         if ((input->value == OB_MODE_EDIT && OB_TYPE_SUPPORT_EDITMODE(ob->type)) ||
1318                             (input->value == OB_MODE_POSE && (ob->type == OB_ARMATURE)) ||
1319                             (input->value == OB_MODE_PARTICLE_EDIT && use_mode_particle_edit) ||
1320                             (ELEM(input->value, OB_MODE_SCULPT, OB_MODE_VERTEX_PAINT,
1321                                    OB_MODE_WEIGHT_PAINT, OB_MODE_TEXTURE_PAINT) && (ob->type == OB_MESH)) ||
1322                             (input->value == OB_MODE_OBJECT))
1323                         {
1324                                 RNA_enum_item_add(&item, &totitem, input);
1325                         }
1326                         input++;
1327                 }
1328         }
1329         else {
1330                 /* We need at least this one! */
1331                 RNA_enum_items_add_value(&item, &totitem, input, OB_MODE_OBJECT);
1332         }
1333         
1334         /* On top of all the rest, GPencil Stroke Edit Mode
1335          * is available if there's a valid gp datablock...
1336          */
1337         gpd = CTX_data_gpencil_data(C);
1338         if (gpd) {
1339                 RNA_enum_items_add_value(&item, &totitem, rna_enum_object_mode_items, OB_MODE_GPENCIL);
1340         }
1341
1342         RNA_enum_item_end(&item, &totitem);
1343
1344         *r_free = true;
1345
1346         return item;
1347 }
1348
1349 static int object_mode_set_poll(bContext *C)
1350 {
1351         /* Since Grease Pencil editmode is also handled here,
1352          * we have a special exception for allowing this operator
1353          * to still work in that case when there's no active object
1354          * so that users can exit editmode this way as per normal.
1355          */
1356         if (ED_operator_object_active_editable(C))
1357                 return true;
1358         else
1359                 return (CTX_data_gpencil_data(C) != NULL);
1360 }
1361
1362 static int object_mode_set_exec(bContext *C, wmOperator *op)
1363 {
1364         bool use_submode = STREQ(op->idname, "OBJECT_OT_mode_set_or_submode");
1365         Object *ob = CTX_data_active_object(C);
1366         bGPdata *gpd = CTX_data_gpencil_data(C);
1367         eObjectMode mode = RNA_enum_get(op->ptr, "mode");
1368         eObjectMode restore_mode = (ob) ? ob->mode : OB_MODE_OBJECT;
1369         const bool toggle = RNA_boolean_get(op->ptr, "toggle");
1370
1371         if (use_submode) {
1372                 /* Apply arbitrary fallback modes, see: T55162. */
1373                 if (ob) {
1374                         if (ob->type == OB_ARMATURE) {
1375                                 if (mode == OB_MODE_TEXTURE_PAINT) {
1376                                         mode = OB_MODE_POSE;
1377                                 }
1378                         }
1379                 }
1380
1381                 if (toggle == false) {
1382                         if (mode == restore_mode) {
1383                                 switch (mode) {
1384                                         case OB_MODE_EDIT:
1385                                                 WM_menu_name_call(C, "VIEW3D_MT_edit_mesh_select_mode", WM_OP_INVOKE_REGION_WIN);
1386                                                 return OPERATOR_INTERFACE;
1387                                         default:
1388                                                 break;
1389                                 }
1390                         }
1391                 }
1392         }
1393
1394         if (gpd) {
1395                 /* GP Mode is not bound to a specific object. Therefore,
1396                  * we don't want it to be actually saved on any objects,
1397                  * as weirdness can happen if you select other objects,
1398                  * or load old files.
1399                  *
1400                  * Instead, we use the following 2 rules to ensure that
1401                  * the mode selector works as expected:
1402                  *  1) If there's no object, we want to enter editmode.
1403                  *     (i.e. with no object, we're in object mode)
1404                  *  2) Otherwise, exit stroke editmode, so that we can
1405                  *     enter another mode...
1406                  */
1407                 if (!ob || (gpd->flag & GP_DATA_STROKE_EDITMODE)) {
1408                         WM_operator_name_call(C, "GPENCIL_OT_editmode_toggle", WM_OP_EXEC_REGION_WIN, NULL);
1409                 }
1410         }
1411         
1412         if (!ob || !ED_object_mode_compat_test(ob, mode))
1413                 return OPERATOR_PASS_THROUGH;
1414
1415         if (ob->mode != mode) {
1416                 /* we should be able to remove this call, each operator calls  */
1417                 ED_object_mode_compat_set(C, ob, mode, op->reports);
1418         }
1419
1420         /* Exit current mode if it's not the mode we're setting */
1421         if (mode != OB_MODE_OBJECT && (ob->mode != mode || toggle)) {
1422                 /* Enter new mode */
1423                 ED_object_mode_toggle(C, mode);
1424         }
1425
1426         if (toggle) {
1427                 /* Special case for Object mode! */
1428                 if (mode == OB_MODE_OBJECT && restore_mode == OB_MODE_OBJECT && ob->restore_mode != OB_MODE_OBJECT) {
1429                         ED_object_mode_toggle(C, ob->restore_mode);
1430                 }
1431                 else if (ob->mode == mode) {
1432                         /* For toggling, store old mode so we know what to go back to */
1433                         ob->restore_mode = restore_mode;
1434                 }
1435                 else if (ob->restore_mode != OB_MODE_OBJECT && ob->restore_mode != mode) {
1436                         ED_object_mode_toggle(C, ob->restore_mode);
1437                 }
1438         }
1439
1440         return OPERATOR_FINISHED;
1441 }
1442
1443 void OBJECT_OT_mode_set(wmOperatorType *ot)
1444 {
1445         PropertyRNA *prop;
1446         
1447         /* identifiers */
1448         ot->name = "Set Object Mode";
1449         ot->description = "Sets the object interaction mode";
1450         ot->idname = "OBJECT_OT_mode_set";
1451         
1452         /* api callbacks */
1453         ot->exec = object_mode_set_exec;
1454         
1455         ot->poll = object_mode_set_poll; //ED_operator_object_active_editable;
1456         
1457         /* flags */
1458         ot->flag = 0; /* no register/undo here, leave it to operators being called */
1459         
1460         ot->prop = RNA_def_enum(ot->srna, "mode", rna_enum_object_mode_items, OB_MODE_OBJECT, "Mode", "");
1461         RNA_def_enum_funcs(ot->prop, object_mode_set_itemsf);
1462         RNA_def_property_flag(ot->prop, PROP_SKIP_SAVE);
1463
1464         prop = RNA_def_boolean(ot->srna, "toggle", 0, "Toggle", "");
1465         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
1466 }
1467
1468 void OBJECT_OT_mode_set_or_submode(wmOperatorType *ot)
1469 {
1470         PropertyRNA *prop;
1471
1472         /* identifiers */
1473         ot->name = "Set Object Mode or Submode";
1474         ot->description = "Sets the object interaction mode";
1475         ot->idname = "OBJECT_OT_mode_set_or_submode";
1476
1477         /* api callbacks */
1478         ot->exec = object_mode_set_exec;
1479
1480         ot->poll = object_mode_set_poll; //ED_operator_object_active_editable;
1481
1482         /* flags */
1483         ot->flag = 0; /* no register/undo here, leave it to operators being called */
1484
1485         ot->prop = RNA_def_enum(ot->srna, "mode", rna_enum_object_mode_items, OB_MODE_OBJECT, "Mode", "");
1486         RNA_def_enum_funcs(ot->prop, object_mode_set_itemsf);
1487         RNA_def_property_flag(ot->prop, PROP_SKIP_SAVE);
1488
1489         prop = RNA_def_boolean(ot->srna, "toggle", 0, "Toggle", "");
1490         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
1491 }
1492
1493 bool ED_object_editmode_calc_active_center(Object *obedit, const bool select_only, float r_center[3])
1494 {
1495         switch (obedit->type) {
1496                 case OB_MESH:
1497                 {
1498                         BMEditMesh *em = BKE_editmesh_from_object(obedit);
1499                         BMEditSelection ese;
1500
1501                         if (BM_select_history_active_get(em->bm, &ese)) {
1502                                 BM_editselection_center(&ese, r_center);
1503                                 return true;
1504                         }
1505                         break;
1506                 }
1507                 case OB_ARMATURE:
1508                 {
1509                         bArmature *arm = obedit->data;
1510                         EditBone *ebo = arm->act_edbone;
1511
1512                         if (ebo && (!select_only || (ebo->flag & (BONE_SELECTED | BONE_ROOTSEL)))) {
1513                                 copy_v3_v3(r_center, ebo->head);
1514                                 return true;
1515                         }
1516
1517                         break;
1518                 }
1519                 case OB_CURVE:
1520                 case OB_SURF:
1521                 {
1522                         Curve *cu = obedit->data;
1523
1524                         if (ED_curve_active_center(cu, r_center)) {
1525                                 return true;
1526                         }
1527                         break;
1528                 }
1529                 case OB_MBALL:
1530                 {
1531                         MetaBall *mb = obedit->data;
1532                         MetaElem *ml_act = mb->lastelem;
1533
1534                         if (ml_act && (!select_only || (ml_act->flag & SELECT))) {
1535                                 copy_v3_v3(r_center, &ml_act->x);
1536                                 return true;
1537                         }
1538                         break;
1539                 }
1540                 case OB_LATTICE:
1541                 {
1542                         BPoint *actbp = BKE_lattice_active_point_get(obedit->data);
1543
1544                         if (actbp) {
1545                                 copy_v3_v3(r_center, actbp->vec);
1546                                 return true;
1547                         }
1548                         break;
1549                 }
1550         }
1551
1552         return false;
1553 }
1554
1555 #define COLLECTION_INVALID_INDEX -1
1556
1557 static int move_to_collection_exec(bContext *C, wmOperator *op)
1558 {
1559         Main *bmain = CTX_data_main(C);
1560         Scene *scene = CTX_data_scene(C);
1561         PropertyRNA *prop = RNA_struct_find_property(op->ptr, "collection_index");
1562         const bool is_link = STREQ(op->idname, "OBJECT_OT_link_to_collection");
1563         const bool is_new = RNA_boolean_get(op->ptr, "is_new");
1564         Collection *collection;
1565
1566         if (!RNA_property_is_set(op->ptr, prop)) {
1567                 BKE_report(op->reports, RPT_ERROR, "No collection selected");
1568                 return OPERATOR_CANCELLED;
1569         }
1570
1571         int collection_index = RNA_property_int_get(op->ptr, prop);
1572         collection = BKE_collection_from_index(CTX_data_scene(C), collection_index);
1573         if (collection == NULL) {
1574                 BKE_report(op->reports, RPT_ERROR, "Unexpected error, collection not found");
1575                 return OPERATOR_CANCELLED;
1576         }
1577
1578         Object *single_object = NULL;
1579         CTX_DATA_BEGIN (C, Object *, ob, selected_objects)
1580         {
1581                 if (single_object != NULL) {
1582                         single_object = NULL;
1583                         break;
1584                 }
1585                 else {
1586                         single_object = ob;
1587                 }
1588         }
1589         CTX_DATA_END;
1590
1591         if (is_new) {
1592                 char new_collection_name[MAX_NAME];
1593                 RNA_string_get(op->ptr, "new_collection_name", new_collection_name);
1594                 collection = BKE_collection_add(bmain, collection, new_collection_name);
1595         }
1596
1597         if ((single_object != NULL) &&
1598             is_link &&
1599             BLI_findptr(&collection->gobject, single_object, offsetof(CollectionObject, ob)))
1600         {
1601                 BKE_reportf(op->reports, RPT_ERROR, "%s already in %s", single_object->id.name + 2, collection->id.name + 2);
1602                 return OPERATOR_CANCELLED;
1603         }
1604
1605         CTX_DATA_BEGIN (C, Object *, ob, selected_objects)
1606         {
1607                 if (!is_link) {
1608                         BKE_collection_object_move(bmain, scene, collection, NULL, ob);
1609                 }
1610                 else {
1611                         BKE_collection_object_add(bmain, collection, ob);
1612                 }
1613         }
1614         CTX_DATA_END;
1615
1616         BKE_reportf(op->reports,
1617                     RPT_INFO,
1618                     "%s %s to %s",
1619                     (single_object != NULL) ? single_object->id.name + 2 : "Objects",
1620                     is_link ? "linked" : "moved",
1621                     collection->id.name + 2);
1622
1623         DEG_relations_tag_update(CTX_data_main(C));
1624         DEG_id_tag_update(&scene->id, 0);
1625
1626         WM_event_add_notifier(C, NC_SCENE | ND_LAYER, scene);
1627         WM_event_add_notifier(C, NC_SCENE | ND_OB_ACTIVE, scene);
1628         WM_event_add_notifier(C, NC_SCENE | ND_LAYER_CONTENT, scene);
1629
1630         return OPERATOR_FINISHED;
1631 }
1632
1633 struct MoveToCollectionData {
1634         struct MoveToCollectionData *next, *prev;
1635         int index;
1636         struct Collection *collection;
1637         struct ListBase submenus;
1638         PointerRNA ptr;
1639         struct wmOperatorType *ot;
1640 };
1641
1642 static int move_to_collection_menus_create(wmOperator *op, MoveToCollectionData *menu)
1643 {
1644         int index = menu->index;
1645         for (CollectionChild *child = menu->collection->children.first;
1646              child != NULL;
1647              child = child->next)
1648         {
1649                 Collection *collection = child->collection;
1650                 MoveToCollectionData *submenu = MEM_callocN(sizeof(MoveToCollectionData),
1651                                                             "MoveToCollectionData submenu - expected memleak");
1652                 BLI_addtail(&menu->submenus, submenu);
1653                 submenu->collection = collection;
1654                 submenu->index = ++index;
1655                 index = move_to_collection_menus_create(op, submenu);
1656                 submenu->ot = op->type;
1657         }
1658         return index;
1659 }
1660
1661 static void move_to_collection_menus_free_recursive(MoveToCollectionData *menu)
1662 {
1663         for (MoveToCollectionData *submenu = menu->submenus.first;
1664              submenu != NULL;
1665              submenu = submenu->next)
1666         {
1667                 move_to_collection_menus_free_recursive(submenu);
1668         }
1669         BLI_freelistN(&menu->submenus);
1670 }
1671
1672 static void move_to_collection_menus_free(MoveToCollectionData **menu)
1673 {
1674         if (*menu == NULL) {
1675                 return;
1676         }
1677
1678         move_to_collection_menus_free_recursive(*menu);
1679         MEM_freeN(*menu);
1680         *menu = NULL;
1681 }
1682
1683 static void move_to_collection_menu_create(bContext *UNUSED(C), uiLayout *layout, void *menu_v)
1684 {
1685         MoveToCollectionData *menu = menu_v;
1686         const char *name;
1687
1688         if (menu->collection->flag & COLLECTION_IS_MASTER) {
1689                 name = IFACE_("Scene Collection");
1690         }
1691         else {
1692                 name = menu->collection->id.name + 2;
1693         }
1694
1695         uiItemIntO(layout,
1696                    name,
1697                    ICON_NONE,
1698                    menu->ot->idname,
1699                    "collection_index",
1700                    menu->index);
1701         uiItemS(layout);
1702
1703         for (MoveToCollectionData *submenu = menu->submenus.first;
1704              submenu != NULL;
1705              submenu = submenu->next)
1706         {
1707                 move_to_collection_menus_items(layout, submenu);
1708         }
1709
1710         uiItemS(layout);
1711
1712         WM_operator_properties_create_ptr(&menu->ptr, menu->ot);
1713         RNA_int_set(&menu->ptr, "collection_index", menu->index);
1714         RNA_boolean_set(&menu->ptr, "is_new", true);
1715
1716         uiItemFullO_ptr(layout,
1717                         menu->ot,
1718                         "New Collection",
1719                         ICON_ZOOMIN,
1720                         menu->ptr.data,
1721                         WM_OP_INVOKE_DEFAULT,
1722                         0,
1723                         NULL);
1724 }
1725
1726 static void move_to_collection_menus_items(uiLayout *layout, MoveToCollectionData *menu)
1727 {
1728         if (BLI_listbase_is_empty(&menu->submenus)) {
1729                 uiItemIntO(layout,
1730                            menu->collection->id.name + 2,
1731                            ICON_NONE,
1732                            menu->ot->idname,
1733                            "collection_index",
1734                            menu->index);
1735         }
1736         else {
1737                 uiItemMenuF(layout,
1738                             menu->collection->id.name + 2,
1739                             ICON_NONE,
1740                             move_to_collection_menu_create,
1741                             menu);
1742         }
1743 }
1744
1745 /* This is allocated statically because we need this available for the menus creation callback. */
1746 static MoveToCollectionData *master_collection_menu = NULL;
1747
1748 static int move_to_collection_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1749 {
1750         Scene *scene = CTX_data_scene(C);
1751
1752         /* Reset the menus data for the current master collection, and free previously allocated data. */
1753         move_to_collection_menus_free(&master_collection_menu);
1754
1755         PropertyRNA *prop;
1756         prop = RNA_struct_find_property(op->ptr, "collection_index");
1757         if (RNA_property_is_set(op->ptr, prop)) {
1758                 int collection_index = RNA_property_int_get(op->ptr, prop);
1759
1760                 if (RNA_boolean_get(op->ptr, "is_new")) {
1761                         prop = RNA_struct_find_property(op->ptr, "new_collection_name");
1762                         if (!RNA_property_is_set(op->ptr, prop)) {
1763                                 char name[MAX_NAME];
1764                                 Collection *collection;
1765
1766                                 collection = BKE_collection_from_index(scene, collection_index);
1767                                 BKE_collection_new_name_get(collection, name);
1768
1769                                 RNA_property_string_set(op->ptr, prop, name);
1770                                 return WM_operator_props_dialog_popup(C, op, 10 * UI_UNIT_X, 5 * UI_UNIT_Y);
1771                         }
1772                 }
1773                 return move_to_collection_exec(C, op);
1774         }
1775
1776         Collection *master_collection = BKE_collection_master(scene);
1777
1778         /* We need the data to be allocated so it's available during menu drawing.
1779          * Technically we could use wmOperator->customdata. However there is no free callback
1780          * called to an operator that exit with OPERATOR_INTERFACE to launch a menu.
1781          *
1782          * So we are left with a memory that will necessarily leak. It's a small leak though.*/
1783         if (master_collection_menu == NULL) {
1784                 master_collection_menu = MEM_callocN(sizeof(MoveToCollectionData),
1785                                                      "MoveToCollectionData menu - expected eventual memleak");
1786         }
1787
1788         master_collection_menu->collection = master_collection;
1789         master_collection_menu->ot = op->type;
1790         move_to_collection_menus_create(op, master_collection_menu);
1791
1792         uiPopupMenu *pup;
1793         uiLayout *layout;
1794
1795         /* Build the menus. */
1796         const char *title = CTX_IFACE_(op->type->translation_context, op->type->name);
1797         pup = UI_popup_menu_begin(C, title, ICON_NONE);
1798         layout = UI_popup_menu_layout(pup);
1799
1800         uiLayoutSetOperatorContext(layout, WM_OP_INVOKE_DEFAULT);
1801
1802         move_to_collection_menu_create(C, layout, master_collection_menu);
1803
1804         UI_popup_menu_end(C, pup);
1805
1806         return OPERATOR_INTERFACE;
1807 }
1808
1809 void OBJECT_OT_move_to_collection(wmOperatorType *ot)
1810 {
1811         PropertyRNA *prop;
1812
1813         /* identifiers */
1814         ot->name = "Move to Collection";
1815         ot->description = "Move objects to a scene collection";
1816         ot->idname = "OBJECT_OT_move_to_collection";
1817
1818         /* api callbacks */
1819         ot->exec = move_to_collection_exec;
1820         ot->invoke = move_to_collection_invoke;
1821         ot->poll = ED_operator_object_active_editable;
1822
1823         /* flags */
1824         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1825
1826         prop = RNA_def_int(ot->srna, "collection_index", COLLECTION_INVALID_INDEX, COLLECTION_INVALID_INDEX, INT_MAX,
1827                            "Collection Index", "Index of the collection to move to", 0, INT_MAX);
1828         RNA_def_property_flag(prop, PROP_SKIP_SAVE | PROP_HIDDEN);
1829         prop = RNA_def_boolean(ot->srna, "is_new", false, "New", "Move objects to a new collection");
1830         RNA_def_property_flag(prop, PROP_SKIP_SAVE | PROP_HIDDEN);
1831         prop = RNA_def_string(ot->srna, "new_collection_name", NULL, MAX_NAME, "Name",
1832                               "Name of the newly added collection");
1833         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
1834 }
1835
1836 void OBJECT_OT_link_to_collection(wmOperatorType *ot)
1837 {
1838         PropertyRNA *prop;
1839
1840         /* identifiers */
1841         ot->name = "Link to Collection";
1842         ot->description = "Link objects to a collection";
1843         ot->idname = "OBJECT_OT_link_to_collection";
1844
1845         /* api callbacks */
1846         ot->exec = move_to_collection_exec;
1847         ot->invoke = move_to_collection_invoke;
1848         ot->poll = ED_operator_object_active_editable;
1849
1850         /* flags */
1851         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1852
1853         prop = RNA_def_int(ot->srna, "collection_index", COLLECTION_INVALID_INDEX, COLLECTION_INVALID_INDEX, INT_MAX,
1854                            "Collection Index", "Index of the collection to move to", 0, INT_MAX);
1855         RNA_def_property_flag(prop, PROP_SKIP_SAVE | PROP_HIDDEN);
1856         prop = RNA_def_boolean(ot->srna, "is_new", false, "New", "Move objects to a new collection");
1857         RNA_def_property_flag(prop, PROP_SKIP_SAVE | PROP_HIDDEN);
1858         prop = RNA_def_string(ot->srna, "new_collection_name", NULL, MAX_NAME, "Name",
1859                               "Name of the newly added collection");
1860         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
1861 }
1862
1863 #undef COLLECTION_INVALID_INDEX