Merge branch 'blender2.8' into blender2.8-workbench
[blender.git] / source / blender / editors / object / object_transform.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_transform.c
27  *  \ingroup edobj
28  */
29
30
31 #include <stdlib.h>
32 #include <string.h>
33
34 #include "DNA_anim_types.h"
35 #include "DNA_armature_types.h"
36 #include "DNA_mesh_types.h"
37 #include "DNA_meta_types.h"
38 #include "DNA_object_types.h"
39 #include "DNA_scene_types.h"
40 #include "DNA_group_types.h"
41 #include "DNA_lattice_types.h"
42 #include "DNA_lamp_types.h"
43
44 #include "BLI_math.h"
45 #include "BLI_listbase.h"
46 #include "BLI_utildefines.h"
47 #include "BLI_array.h"
48
49 #include "BKE_context.h"
50 #include "BKE_curve.h"
51 #include "BKE_main.h"
52 #include "BKE_idcode.h"
53 #include "BKE_mball.h"
54 #include "BKE_mesh.h"
55 #include "BKE_object.h"
56 #include "BKE_report.h"
57 #include "BKE_editmesh.h"
58 #include "BKE_multires.h"
59 #include "BKE_armature.h"
60 #include "BKE_lattice.h"
61 #include "BKE_tracking.h"
62
63 #include "DEG_depsgraph.h"
64
65 #include "RNA_define.h"
66 #include "RNA_access.h"
67
68 #include "WM_api.h"
69 #include "WM_types.h"
70
71 #include "ED_armature.h"
72 #include "ED_keyframing.h"
73 #include "ED_mesh.h"
74 #include "ED_screen.h"
75 #include "ED_view3d.h"
76
77 #include "MEM_guardedalloc.h"
78
79 #include "object_intern.h"
80
81 /*************************** Clear Transformation ****************************/
82
83 /* clear location of object */
84 static void object_clear_loc(Object *ob, const bool clear_delta)
85 {
86         /* clear location if not locked */
87         if ((ob->protectflag & OB_LOCK_LOCX) == 0) {
88                 ob->loc[0] = 0.0f;
89                 if (clear_delta) ob->dloc[0] = 0.0f;
90         }
91         if ((ob->protectflag & OB_LOCK_LOCY) == 0) {
92                 ob->loc[1] = 0.0f;
93                 if (clear_delta) ob->dloc[1] = 0.0f;
94         }
95         if ((ob->protectflag & OB_LOCK_LOCZ) == 0) {
96                 ob->loc[2] = 0.0f;
97                 if (clear_delta) ob->dloc[2] = 0.0f;
98         }
99 }
100
101 /* clear rotation of object */
102 static void object_clear_rot(Object *ob, const bool clear_delta)
103 {
104         /* clear rotations that aren't locked */
105         if (ob->protectflag & (OB_LOCK_ROTX | OB_LOCK_ROTY | OB_LOCK_ROTZ | OB_LOCK_ROTW)) {
106                 if (ob->protectflag & OB_LOCK_ROT4D) {
107                         /* perform clamping on a component by component basis */
108                         if (ob->rotmode == ROT_MODE_AXISANGLE) {
109                                 if ((ob->protectflag & OB_LOCK_ROTW) == 0) {
110                                         ob->rotAngle = 0.0f;
111                                         if (clear_delta) ob->drotAngle = 0.0f;
112                                 }
113                                 if ((ob->protectflag & OB_LOCK_ROTX) == 0) {
114                                         ob->rotAxis[0] = 0.0f;
115                                         if (clear_delta) ob->drotAxis[0] = 0.0f;
116                                 }
117                                 if ((ob->protectflag & OB_LOCK_ROTY) == 0) {
118                                         ob->rotAxis[1] = 0.0f;
119                                         if (clear_delta) ob->drotAxis[1] = 0.0f;
120                                 }
121                                 if ((ob->protectflag & OB_LOCK_ROTZ) == 0) {
122                                         ob->rotAxis[2] = 0.0f;
123                                         if (clear_delta) ob->drotAxis[2] = 0.0f;
124                                 }
125                                         
126                                 /* check validity of axis - axis should never be 0,0,0 (if so, then we make it rotate about y) */
127                                 if (IS_EQF(ob->rotAxis[0], ob->rotAxis[1]) && IS_EQF(ob->rotAxis[1], ob->rotAxis[2]))
128                                         ob->rotAxis[1] = 1.0f;
129                                 if (IS_EQF(ob->drotAxis[0], ob->drotAxis[1]) && IS_EQF(ob->drotAxis[1], ob->drotAxis[2]) && clear_delta)
130                                         ob->drotAxis[1] = 1.0f;
131                         }
132                         else if (ob->rotmode == ROT_MODE_QUAT) {
133                                 if ((ob->protectflag & OB_LOCK_ROTW) == 0) {
134                                         ob->quat[0] = 1.0f;
135                                         if (clear_delta) ob->dquat[0] = 1.0f;
136                                 }
137                                 if ((ob->protectflag & OB_LOCK_ROTX) == 0) {
138                                         ob->quat[1] = 0.0f;
139                                         if (clear_delta) ob->dquat[1] = 0.0f;
140                                 }
141                                 if ((ob->protectflag & OB_LOCK_ROTY) == 0) {
142                                         ob->quat[2] = 0.0f;
143                                         if (clear_delta) ob->dquat[2] = 0.0f;
144                                 }
145                                 if ((ob->protectflag & OB_LOCK_ROTZ) == 0) {
146                                         ob->quat[3] = 0.0f;
147                                         if (clear_delta) ob->dquat[3] = 0.0f;
148                                 }
149                                 /* TODO: does this quat need normalizing now? */
150                         }
151                         else {
152                                 /* the flag may have been set for the other modes, so just ignore the extra flag... */
153                                 if ((ob->protectflag & OB_LOCK_ROTX) == 0) {
154                                         ob->rot[0] = 0.0f;
155                                         if (clear_delta) ob->drot[0] = 0.0f;
156                                 }
157                                 if ((ob->protectflag & OB_LOCK_ROTY) == 0) {
158                                         ob->rot[1] = 0.0f;
159                                         if (clear_delta) ob->drot[1] = 0.0f;
160                                 }
161                                 if ((ob->protectflag & OB_LOCK_ROTZ) == 0) {
162                                         ob->rot[2] = 0.0f;
163                                         if (clear_delta) ob->drot[2] = 0.0f;
164                                 }
165                         }
166                 }
167                 else {
168                         /* perform clamping using euler form (3-components) */
169                         /* FIXME: deltas are not handled for these cases yet... */
170                         float eul[3], oldeul[3], quat1[4] = {0};
171                         
172                         if (ob->rotmode == ROT_MODE_QUAT) {
173                                 copy_qt_qt(quat1, ob->quat);
174                                 quat_to_eul(oldeul, ob->quat);
175                         }
176                         else if (ob->rotmode == ROT_MODE_AXISANGLE) {
177                                 axis_angle_to_eulO(oldeul, EULER_ORDER_DEFAULT, ob->rotAxis, ob->rotAngle);
178                         }
179                         else {
180                                 copy_v3_v3(oldeul, ob->rot);
181                         }
182                         
183                         eul[0] = eul[1] = eul[2] = 0.0f;
184                         
185                         if (ob->protectflag & OB_LOCK_ROTX)
186                                 eul[0] = oldeul[0];
187                         if (ob->protectflag & OB_LOCK_ROTY)
188                                 eul[1] = oldeul[1];
189                         if (ob->protectflag & OB_LOCK_ROTZ)
190                                 eul[2] = oldeul[2];
191                         
192                         if (ob->rotmode == ROT_MODE_QUAT) {
193                                 eul_to_quat(ob->quat, eul);
194                                 /* quaternions flip w sign to accumulate rotations correctly */
195                                 if ((quat1[0] < 0.0f && ob->quat[0] > 0.0f) || (quat1[0] > 0.0f && ob->quat[0] < 0.0f)) {
196                                         mul_qt_fl(ob->quat, -1.0f);
197                                 }
198                         }
199                         else if (ob->rotmode == ROT_MODE_AXISANGLE) {
200                                 eulO_to_axis_angle(ob->rotAxis, &ob->rotAngle, eul, EULER_ORDER_DEFAULT);
201                         }
202                         else {
203                                 copy_v3_v3(ob->rot, eul);
204                         }
205                 }
206         }                        // Duplicated in source/blender/editors/armature/editarmature.c
207         else {
208                 if (ob->rotmode == ROT_MODE_QUAT) {
209                         unit_qt(ob->quat);
210                         if (clear_delta) unit_qt(ob->dquat);
211                 }
212                 else if (ob->rotmode == ROT_MODE_AXISANGLE) {
213                         unit_axis_angle(ob->rotAxis, &ob->rotAngle);
214                         if (clear_delta) unit_axis_angle(ob->drotAxis, &ob->drotAngle);
215                 }
216                 else {
217                         zero_v3(ob->rot);
218                         if (clear_delta) zero_v3(ob->drot);
219                 }
220         }
221 }
222
223 /* clear scale of object */
224 static void object_clear_scale(Object *ob, const bool clear_delta)
225 {
226         /* clear scale factors which are not locked */
227         if ((ob->protectflag & OB_LOCK_SCALEX) == 0) {
228                 ob->size[0] = 1.0f;
229                 if (clear_delta) ob->dscale[0] = 1.0f;
230         }
231         if ((ob->protectflag & OB_LOCK_SCALEY) == 0) {
232                 ob->size[1] = 1.0f;
233                 if (clear_delta) ob->dscale[1] = 1.0f;
234         }
235         if ((ob->protectflag & OB_LOCK_SCALEZ) == 0) {
236                 ob->size[2] = 1.0f;
237                 if (clear_delta) ob->dscale[2] = 1.0f;
238         }
239 }
240
241 /* --------------- */
242
243 /* generic exec for clear-transform operators */
244 static int object_clear_transform_generic_exec(bContext *C, wmOperator *op, 
245                                                void (*clear_func)(Object *, const bool),
246                                                const char default_ksName[])
247 {
248         Scene *scene = CTX_data_scene(C);
249         KeyingSet *ks;
250         const bool clear_delta = RNA_boolean_get(op->ptr, "clear_delta");
251         
252         /* sanity checks */
253         if (ELEM(NULL, clear_func, default_ksName)) {
254                 BKE_report(op->reports, RPT_ERROR, "Programming error: missing clear transform function or keying set name");
255                 return OPERATOR_CANCELLED;
256         }
257         
258         /* get KeyingSet to use */
259         ks = ANIM_get_keyingset_for_autokeying(scene, default_ksName);
260         
261         /* operate on selected objects only if they aren't in weight-paint mode 
262          * (so that object-transform clearing won't be applied at same time as bone-clearing)
263          */
264         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
265         {
266                 if (!(ob->mode & OB_MODE_WEIGHT_PAINT)) {
267                         /* run provided clearing function */
268                         clear_func(ob, clear_delta);
269                         
270                         ED_autokeyframe_object(C, scene, ob, ks);
271                         
272                         /* tag for updates */
273                         DEG_id_tag_update(&ob->id, OB_RECALC_OB);
274                 }
275         }
276         CTX_DATA_END;
277         
278         /* this is needed so children are also updated */
279         WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL);
280
281         return OPERATOR_FINISHED;
282 }
283
284 /* --------------- */
285
286
287 static int object_location_clear_exec(bContext *C, wmOperator *op)
288 {
289         return object_clear_transform_generic_exec(C, op, object_clear_loc, ANIM_KS_LOCATION_ID);
290 }
291
292 void OBJECT_OT_location_clear(wmOperatorType *ot)
293 {
294         /* identifiers */
295         ot->name = "Clear Location";
296         ot->description = "Clear the object's location";
297         ot->idname = "OBJECT_OT_location_clear";
298         
299         /* api callbacks */
300         ot->exec = object_location_clear_exec;
301         ot->poll = ED_operator_scene_editable;
302         
303         /* flags */
304         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
305         
306         
307         /* properties */
308         ot->prop = RNA_def_boolean(ot->srna, "clear_delta", false, "Clear Delta",
309                                    "Clear delta location in addition to clearing the normal location transform");
310 }
311
312 static int object_rotation_clear_exec(bContext *C, wmOperator *op)
313 {
314         return object_clear_transform_generic_exec(C, op, object_clear_rot, ANIM_KS_ROTATION_ID);
315 }
316
317 void OBJECT_OT_rotation_clear(wmOperatorType *ot)
318 {
319         /* identifiers */
320         ot->name = "Clear Rotation";
321         ot->description = "Clear the object's rotation";
322         ot->idname = "OBJECT_OT_rotation_clear";
323         
324         /* api callbacks */
325         ot->exec = object_rotation_clear_exec;
326         ot->poll = ED_operator_scene_editable;
327         
328         /* flags */
329         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
330         
331         /* properties */
332         ot->prop = RNA_def_boolean(ot->srna, "clear_delta", false, "Clear Delta",
333                                    "Clear delta rotation in addition to clearing the normal rotation transform");
334 }
335
336 static int object_scale_clear_exec(bContext *C, wmOperator *op)
337 {
338         return object_clear_transform_generic_exec(C, op, object_clear_scale, ANIM_KS_SCALING_ID);
339 }
340
341 void OBJECT_OT_scale_clear(wmOperatorType *ot)
342 {
343         /* identifiers */
344         ot->name = "Clear Scale";
345         ot->description = "Clear the object's scale";
346         ot->idname = "OBJECT_OT_scale_clear";
347         
348         /* api callbacks */
349         ot->exec = object_scale_clear_exec;
350         ot->poll = ED_operator_scene_editable;
351         
352         /* flags */
353         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
354         
355         /* properties */
356         ot->prop = RNA_def_boolean(ot->srna, "clear_delta", false, "Clear Delta",
357                                    "Clear delta scale in addition to clearing the normal scale transform");
358 }
359
360 /* --------------- */
361
362 static int object_origin_clear_exec(bContext *C, wmOperator *UNUSED(op))
363 {
364         float *v1, *v3;
365         float mat[3][3];
366
367         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
368         {
369                 if (ob->parent) {
370                         /* vectors pointed to by v1 and v3 will get modified */
371                         v1 = ob->loc;
372                         v3 = ob->parentinv[3];
373                         
374                         copy_m3_m4(mat, ob->parentinv);
375                         negate_v3_v3(v3, v1);
376                         mul_m3_v3(mat, v3);
377                 }
378
379                 DEG_id_tag_update(&ob->id, OB_RECALC_OB);
380         }
381         CTX_DATA_END;
382
383         WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL);
384         
385         return OPERATOR_FINISHED;
386 }
387
388 void OBJECT_OT_origin_clear(wmOperatorType *ot)
389 {
390         /* identifiers */
391         ot->name = "Clear Origin";
392         ot->description = "Clear the object's origin";
393         ot->idname = "OBJECT_OT_origin_clear";
394         
395         /* api callbacks */
396         ot->exec = object_origin_clear_exec;
397         ot->poll = ED_operator_scene_editable;
398         
399         /* flags */
400         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
401 }
402
403 /*************************** Apply Transformation ****************************/
404
405 /* use this when the loc/size/rot of the parent has changed but the children
406  * should stay in the same place, e.g. for apply-size-rot or object center */
407 static void ignore_parent_tx(const bContext *C, Main *bmain, Scene *scene, Object *ob)
408 {
409         Object workob;
410         Object *ob_child;
411         EvaluationContext eval_ctx;
412
413         CTX_data_eval_ctx(C, &eval_ctx);
414         
415         /* a change was made, adjust the children to compensate */
416         for (ob_child = bmain->object.first; ob_child; ob_child = ob_child->id.next) {
417                 if (ob_child->parent == ob) {
418                         BKE_object_apply_mat4(ob_child, ob_child->obmat, true, false);
419                         BKE_object_workob_calc_parent(&eval_ctx, scene, ob_child, &workob);
420                         invert_m4_m4(ob_child->parentinv, workob.obmat);
421                 }
422         }
423 }
424
425 static int apply_objects_internal(
426         bContext *C, ReportList *reports,
427         bool apply_loc, bool apply_rot, bool apply_scale,
428         bool do_props)
429 {
430         Main *bmain = CTX_data_main(C);
431         Scene *scene = CTX_data_scene(C);
432         EvaluationContext eval_ctx;
433         float rsmat[3][3], obmat[3][3], iobmat[3][3], mat[4][4], scale;
434         bool changed = true;
435
436         CTX_data_eval_ctx(C, &eval_ctx);
437         
438         /* first check if we can execute */
439         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
440         {
441                 if (ELEM(ob->type, OB_MESH, OB_ARMATURE, OB_LATTICE, OB_MBALL, OB_CURVE, OB_SURF, OB_FONT)) {
442                         ID *obdata = ob->data;
443                         if (ID_REAL_USERS(obdata) > 1) {
444                                 BKE_reportf(reports, RPT_ERROR,
445                                             "Cannot apply to a multi user: Object \"%s\", %s \"%s\", aborting",
446                                             ob->id.name + 2, BKE_idcode_to_name(GS(obdata->name)), obdata->name + 2);
447                                 changed = false;
448                         }
449
450                         if (ID_IS_LINKED(obdata)) {
451                                 BKE_reportf(reports, RPT_ERROR,
452                                             "Cannot apply to library data: Object \"%s\", %s \"%s\", aborting",
453                                             ob->id.name + 2, BKE_idcode_to_name(GS(obdata->name)), obdata->name + 2);
454                                 changed = false;
455                         }
456                 }
457
458                 if (ELEM(ob->type, OB_CURVE, OB_SURF)) {
459                         ID *obdata = ob->data;
460                         Curve *cu;
461
462                         cu = ob->data;
463
464                         if (((ob->type == OB_CURVE) && !(cu->flag & CU_3D)) && (apply_rot || apply_loc)) {
465                                 BKE_reportf(reports, RPT_ERROR,
466                                             "Rotation/Location can't apply to a 2D curve: Object \"%s\", %s \"%s\", aborting",
467                                             ob->id.name + 2, BKE_idcode_to_name(GS(obdata->name)), obdata->name + 2);
468                                 changed = false;
469                         }
470                         if (cu->key) {
471                                 BKE_reportf(reports, RPT_ERROR,
472                                             "Can't apply to a curve with shape-keys: Object \"%s\", %s \"%s\", aborting",
473                                             ob->id.name + 2, BKE_idcode_to_name(GS(obdata->name)), obdata->name + 2);
474                                 changed = false;
475                         }
476                 }
477
478                 if (ob->type == OB_FONT) {
479                         if (apply_rot || apply_loc) {
480                                 BKE_reportf(reports, RPT_ERROR,
481                                             "Font's can only have scale applied: \"%s\"",
482                                             ob->id.name + 2);
483                                 changed = false;
484                         }
485                 }
486         }
487         CTX_DATA_END;
488         
489         if (!changed)
490                 return OPERATOR_CANCELLED;
491
492         changed = false;
493
494         /* now execute */
495         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
496         {
497
498                 /* calculate rotation/scale matrix */
499                 if (apply_scale && apply_rot)
500                         BKE_object_to_mat3(ob, rsmat);
501                 else if (apply_scale)
502                         BKE_object_scale_to_mat3(ob, rsmat);
503                 else if (apply_rot) {
504                         float tmat[3][3], timat[3][3];
505
506                         /* simple rotation matrix */
507                         BKE_object_rot_to_mat3(ob, rsmat, true);
508
509                         /* correct for scale, note mul_m3_m3m3 has swapped args! */
510                         BKE_object_scale_to_mat3(ob, tmat);
511                         invert_m3_m3(timat, tmat);
512                         mul_m3_m3m3(rsmat, timat, rsmat);
513                         mul_m3_m3m3(rsmat, rsmat, tmat);
514                 }
515                 else
516                         unit_m3(rsmat);
517
518                 copy_m4_m3(mat, rsmat);
519
520                 /* calculate translation */
521                 if (apply_loc) {
522                         copy_v3_v3(mat[3], ob->loc);
523
524                         if (!(apply_scale && apply_rot)) {
525                                 float tmat[3][3];
526                                 /* correct for scale and rotation that is still applied */
527                                 BKE_object_to_mat3(ob, obmat);
528                                 invert_m3_m3(iobmat, obmat);
529                                 mul_m3_m3m3(tmat, rsmat, iobmat);
530                                 mul_m3_v3(tmat, mat[3]);
531                         }
532                 }
533
534                 /* apply to object data */
535                 if (ob->type == OB_MESH) {
536                         Mesh *me = ob->data;
537
538                         if (apply_scale)
539                                 multiresModifier_scale_disp(&eval_ctx, scene, ob);
540                         
541                         /* adjust data */
542                         BKE_mesh_transform(me, mat, true);
543                         
544                         /* update normals */
545                         BKE_mesh_calc_normals(me);
546                 }
547                 else if (ob->type == OB_ARMATURE) {
548                         ED_armature_transform_apply(ob, mat, do_props);
549                 }
550                 else if (ob->type == OB_LATTICE) {
551                         Lattice *lt = ob->data;
552
553                         BKE_lattice_transform(lt, mat, true);
554                 }
555                 else if (ob->type == OB_MBALL) {
556                         MetaBall *mb = ob->data;
557                         BKE_mball_transform(mb, mat, do_props);
558                 }
559                 else if (ELEM(ob->type, OB_CURVE, OB_SURF)) {
560                         Curve *cu = ob->data;
561                         scale = mat3_to_scale(rsmat);
562                         BKE_curve_transform_ex(cu, mat, true, do_props, scale);
563                 }
564                 else if (ob->type == OB_FONT) {
565                         Curve *cu = ob->data;
566                         int i;
567
568                         scale = mat3_to_scale(rsmat);
569
570                         for (i = 0; i < cu->totbox; i++) {
571                                 TextBox *tb = &cu->tb[i];
572                                 tb->x *= scale;
573                                 tb->y *= scale;
574                                 tb->w *= scale;
575                                 tb->h *= scale;
576                         }
577
578                         if (do_props) {
579                                 cu->fsize *= scale;
580                         }
581                 }
582                 else if (ob->type == OB_CAMERA) {
583                         MovieClip *clip = BKE_object_movieclip_get(scene, ob, false);
584
585                         /* applying scale on camera actually scales clip's reconstruction.
586                          * of there's clip assigned to camera nothing to do actually.
587                          */
588                         if (!clip)
589                                 continue;
590
591                         if (apply_scale)
592                                 BKE_tracking_reconstruction_scale(&clip->tracking, ob->size);
593                 }
594                 else if (ob->type == OB_EMPTY) {
595                         /* It's possible for empties too, even though they don't 
596                          * really have obdata, since we can simply apply the maximum
597                          * scaling to the empty's drawsize.
598                          *
599                          * Core Assumptions:
600                          * 1) Most scaled empties have uniform scaling 
601                          *    (i.e. for visibility reasons), AND/OR
602                          * 2) Preserving non-uniform scaling is not that important,
603                          *    and is something that many users would be willing to
604                          *    sacrifice for having an easy way to do this.
605                          */
606
607                         if ((apply_loc == false) &&
608                             (apply_rot == false) &&
609                             (apply_scale == true))
610                         {
611                                 float max_scale = max_fff(fabsf(ob->size[0]), fabsf(ob->size[1]), fabsf(ob->size[2]));
612                                 ob->empty_drawsize *= max_scale;
613                         }
614                 }
615                 else {
616                         continue;
617                 }
618
619                 if (apply_loc)
620                         zero_v3(ob->loc);
621                 if (apply_scale)
622                         ob->size[0] = ob->size[1] = ob->size[2] = 1.0f;
623                 if (apply_rot) {
624                         zero_v3(ob->rot);
625                         unit_qt(ob->quat);
626                         unit_axis_angle(ob->rotAxis, &ob->rotAngle);
627                 }
628
629                 BKE_object_where_is_calc(&eval_ctx, scene, ob);
630                 if (ob->type == OB_ARMATURE) {
631                         BKE_pose_where_is(&eval_ctx, scene, ob); /* needed for bone parents */
632                 }
633
634                 ignore_parent_tx(C, bmain, scene, ob);
635
636                 DEG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA);
637
638                 changed = true;
639         }
640         CTX_DATA_END;
641
642         if (!changed) {
643                 BKE_report(reports, RPT_WARNING, "Objects have no data to transform");
644                 return OPERATOR_CANCELLED;
645         }
646
647         WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL);
648         return OPERATOR_FINISHED;
649 }
650
651 static int visual_transform_apply_exec(bContext *C, wmOperator *UNUSED(op))
652 {
653         Scene *scene = CTX_data_scene(C);
654         EvaluationContext eval_ctx;
655         bool changed = false;
656         
657         CTX_data_eval_ctx(C, &eval_ctx);
658
659         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
660         {
661                 BKE_object_where_is_calc(&eval_ctx, scene, ob);
662                 BKE_object_apply_mat4(ob, ob->obmat, true, true);
663                 BKE_object_where_is_calc(&eval_ctx, scene, ob);
664
665                 /* update for any children that may get moved */
666                 DEG_id_tag_update(&ob->id, OB_RECALC_OB);
667         
668                 changed = true;
669         }
670         CTX_DATA_END;
671
672         if (!changed)
673                 return OPERATOR_CANCELLED;
674
675         WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL);
676         return OPERATOR_FINISHED;
677 }
678
679 void OBJECT_OT_visual_transform_apply(wmOperatorType *ot)
680 {
681         /* identifiers */
682         ot->name = "Apply Visual Transform";
683         ot->description = "Apply the object's visual transformation to its data";
684         ot->idname = "OBJECT_OT_visual_transform_apply";
685         
686         /* api callbacks */
687         ot->exec = visual_transform_apply_exec;
688         ot->poll = ED_operator_scene_editable;
689         
690         /* flags */
691         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
692 }
693
694 static int object_transform_apply_exec(bContext *C, wmOperator *op)
695 {
696         const bool loc = RNA_boolean_get(op->ptr, "location");
697         const bool rot = RNA_boolean_get(op->ptr, "rotation");
698         const bool sca = RNA_boolean_get(op->ptr, "scale");
699         const bool do_props = RNA_boolean_get(op->ptr, "properties");
700
701         if (loc || rot || sca) {
702                 return apply_objects_internal(C, op->reports, loc, rot, sca, do_props);
703         }
704         else {
705                 /* allow for redo */
706                 return OPERATOR_FINISHED;
707         }
708 }
709
710 void OBJECT_OT_transform_apply(wmOperatorType *ot)
711 {
712         /* identifiers */
713         ot->name = "Apply Object Transform";
714         ot->description = "Apply the object's transformation to its data";
715         ot->idname = "OBJECT_OT_transform_apply";
716
717         /* api callbacks */
718         ot->exec = object_transform_apply_exec;
719         ot->poll = ED_operator_objectmode;
720
721         /* flags */
722         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
723
724         RNA_def_boolean(ot->srna, "location", 0, "Location", "");
725         RNA_def_boolean(ot->srna, "rotation", 0, "Rotation", "");
726         RNA_def_boolean(ot->srna, "scale", 0, "Scale", "");
727         RNA_def_boolean(ot->srna, "properties", true, "Apply Properties",
728                         "Modify properties such as curve vertex radius, font size and bone envelope");
729 }
730
731 /********************* Set Object Center ************************/
732
733 enum {
734         GEOMETRY_TO_ORIGIN = 0,
735         ORIGIN_TO_GEOMETRY,
736         ORIGIN_TO_CURSOR,
737         ORIGIN_TO_CENTER_OF_MASS_SURFACE,
738         ORIGIN_TO_CENTER_OF_MASS_VOLUME,
739 };
740
741 static int object_origin_set_exec(bContext *C, wmOperator *op)
742 {
743         Main *bmain = CTX_data_main(C);
744         Scene *scene = CTX_data_scene(C);
745         Object *obact = CTX_data_active_object(C);
746         Object *obedit = CTX_data_edit_object(C);
747         EvaluationContext eval_ctx;
748         Object *tob;
749         float cursor[3], cent[3], cent_neg[3], centn[3];
750         int centermode = RNA_enum_get(op->ptr, "type");
751         int around = RNA_enum_get(op->ptr, "center"); /* initialized from v3d->around */
752
753         ListBase ctx_data_list;
754         CollectionPointerLink *ctx_ob;
755         CollectionPointerLink *ctx_ob_act = NULL;
756
757         CTX_data_eval_ctx(C, &eval_ctx);
758
759         /* keep track of what is changed */
760         int tot_change = 0, tot_lib_error = 0, tot_multiuser_arm_error = 0;
761
762         if (obedit && centermode != GEOMETRY_TO_ORIGIN) {
763                 BKE_report(op->reports, RPT_ERROR, "Operation cannot be performed in edit mode");
764                 return OPERATOR_CANCELLED;
765         }
766         else {
767                 /* get the view settings if 'around' isn't set and the view is available */
768                 View3D *v3d = CTX_wm_view3d(C);
769                 copy_v3_v3(cursor, ED_view3d_cursor3d_get(scene, v3d));
770                 if (v3d && !RNA_struct_property_is_set(op->ptr, "center"))
771                         around = v3d->around;
772         }
773
774         zero_v3(cent);
775
776         if (obedit) {
777                 if (obedit->type == OB_MESH) {
778                         Mesh *me = obedit->data;
779                         BMEditMesh *em = me->edit_btmesh;
780                         BMVert *eve;
781                         BMIter iter;
782                         
783                         if (centermode == ORIGIN_TO_CURSOR) {
784                                 copy_v3_v3(cent, cursor);
785                                 invert_m4_m4(obedit->imat, obedit->obmat);
786                                 mul_m4_v3(obedit->imat, cent);
787                         }
788                         else {
789                                 if (around == V3D_AROUND_CENTER_MEAN) {
790                                         if (em->bm->totvert) {
791                                                 const float total_div = 1.0f / (float)em->bm->totvert;
792                                                 BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
793                                                         madd_v3_v3fl(cent, eve->co, total_div);
794                                                 }
795                                         }
796                                 }
797                                 else {
798                                         float min[3], max[3];
799                                         INIT_MINMAX(min, max);
800                                         BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
801                                                 minmax_v3v3_v3(min, max, eve->co);
802                                         }
803                                         mid_v3_v3v3(cent, min, max);
804                                 }
805                         }
806                         
807                         BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
808                                 sub_v3_v3(eve->co, cent);
809                         }
810
811                         EDBM_mesh_normals_update(em);
812                         tot_change++;
813                         DEG_id_tag_update(&obedit->id, OB_RECALC_DATA);
814                 }
815         }
816
817         CTX_data_selected_editable_objects(C, &ctx_data_list);
818
819         /* reset flags */
820         for (ctx_ob = ctx_data_list.first;
821              ctx_ob;
822              ctx_ob = ctx_ob->next)
823         {
824                 Object *ob = ctx_ob->ptr.data;
825                 ob->flag &= ~OB_DONE;
826
827                 /* move active first */
828                 if (ob == obact) {
829                         ctx_ob_act = ctx_ob;
830                 }
831         }
832
833         if (ctx_ob_act) {
834                 BLI_listbase_rotate_first(&ctx_data_list, (LinkData *)ctx_ob_act);
835         }
836
837         for (tob = bmain->object.first; tob; tob = tob->id.next) {
838                 if (tob->data)
839                         ((ID *)tob->data)->tag &= ~LIB_TAG_DOIT;
840                 if (tob->dup_group)
841                         ((ID *)tob->dup_group)->tag &= ~LIB_TAG_DOIT;
842         }
843
844         for (ctx_ob = ctx_data_list.first;
845              ctx_ob;
846              ctx_ob = ctx_ob->next)
847         {
848                 Object *ob = ctx_ob->ptr.data;
849
850                 if ((ob->flag & OB_DONE) == 0) {
851                         bool do_inverse_offset = false;
852                         ob->flag |= OB_DONE;
853
854                         if (centermode == ORIGIN_TO_CURSOR) {
855                                 copy_v3_v3(cent, cursor);
856                                 invert_m4_m4(ob->imat, ob->obmat);
857                                 mul_m4_v3(ob->imat, cent);
858                         }
859                         
860                         if (ob->data == NULL) {
861                                 /* special support for dupligroups */
862                                 if ((ob->transflag & OB_DUPLIGROUP) && ob->dup_group && (ob->dup_group->id.tag & LIB_TAG_DOIT) == 0) {
863                                         if (ID_IS_LINKED(ob->dup_group)) {
864                                                 tot_lib_error++;
865                                         }
866                                         else {
867                                                 if (centermode == ORIGIN_TO_CURSOR) {
868                                                         /* done */
869                                                 }
870                                                 else {
871                                                         float min[3], max[3];
872                                                         /* only bounds support */
873                                                         INIT_MINMAX(min, max);
874                                                         BKE_object_minmax_dupli(scene, ob, min, max, true);
875                                                         mid_v3_v3v3(cent, min, max);
876                                                         invert_m4_m4(ob->imat, ob->obmat);
877                                                         mul_m4_v3(ob->imat, cent);
878                                                 }
879                                                 
880                                                 add_v3_v3(ob->dup_group->dupli_ofs, cent);
881
882                                                 tot_change++;
883                                                 ob->dup_group->id.tag |= LIB_TAG_DOIT;
884                                                 do_inverse_offset = true;
885                                         }
886                                 }
887                         }
888                         else if (ID_IS_LINKED(ob->data)) {
889                                 tot_lib_error++;
890                         }
891
892                         if (obedit == NULL && ob->type == OB_MESH) {
893                                 Mesh *me = ob->data;
894
895                                 if (centermode == ORIGIN_TO_CURSOR) {
896                                         /* done */
897                                 }
898                                 else if (centermode == ORIGIN_TO_CENTER_OF_MASS_SURFACE) {
899                                         BKE_mesh_center_of_surface(me, cent);
900                                 }
901                                 else if (centermode == ORIGIN_TO_CENTER_OF_MASS_VOLUME) {
902                                         BKE_mesh_center_of_volume(me, cent);
903                                 }
904                                 else if (around == V3D_AROUND_CENTER_MEAN) {
905                                         BKE_mesh_center_median(me, cent);
906                                 }
907                                 else {
908                                         BKE_mesh_center_bounds(me, cent);
909                                 }
910
911                                 negate_v3_v3(cent_neg, cent);
912                                 BKE_mesh_translate(me, cent_neg, 1);
913
914                                 tot_change++;
915                                 me->id.tag |= LIB_TAG_DOIT;
916                                 do_inverse_offset = true;
917                         }
918                         else if (ELEM(ob->type, OB_CURVE, OB_SURF)) {
919                                 Curve *cu = ob->data;
920
921                                 if      (centermode == ORIGIN_TO_CURSOR)    { /* done */ }
922                                 else if (around == V3D_AROUND_CENTER_MEAN)  { BKE_curve_center_median(cu, cent); }
923                                 else                                        { BKE_curve_center_bounds(cu, cent); }
924
925                                 /* don't allow Z change if curve is 2D */
926                                 if ((ob->type == OB_CURVE) && !(cu->flag & CU_3D))
927                                         cent[2] = 0.0;
928
929                                 negate_v3_v3(cent_neg, cent);
930                                 BKE_curve_translate(cu, cent_neg, 1);
931
932                                 tot_change++;
933                                 cu->id.tag |= LIB_TAG_DOIT;
934                                 do_inverse_offset = true;
935
936                                 if (obedit) {
937                                         if (centermode == GEOMETRY_TO_ORIGIN) {
938                                                 DEG_id_tag_update(&obedit->id, OB_RECALC_DATA);
939                                         }
940                                         break;
941                                 }
942                         }
943                         else if (ob->type == OB_FONT) {
944                                 /* get from bb */
945
946                                 Curve *cu = ob->data;
947
948                                 if (ob->bb == NULL && (centermode != ORIGIN_TO_CURSOR)) {
949                                         /* do nothing*/
950                                 }
951                                 else {
952                                         if (centermode == ORIGIN_TO_CURSOR) {
953                                                 /* done */
954                                         }
955                                         else {
956                                                 /* extra 0.5 is the height o above line */
957                                                 cent[0] = 0.5f * (ob->bb->vec[4][0] + ob->bb->vec[0][0]);
958                                                 cent[1] = 0.5f * (ob->bb->vec[0][1] + ob->bb->vec[2][1]);
959                                         }
960
961                                         cent[2] = 0.0f;
962
963                                         cu->xof = cu->xof - cent[0];
964                                         cu->yof = cu->yof - cent[1];
965
966                                         tot_change++;
967                                         cu->id.tag |= LIB_TAG_DOIT;
968                                         do_inverse_offset = true;
969                                 }
970                         }
971                         else if (ob->type == OB_ARMATURE) {
972                                 bArmature *arm = ob->data;
973
974                                 if (ID_REAL_USERS(arm) > 1) {
975 #if 0
976                                         BKE_report(op->reports, RPT_ERROR, "Cannot apply to a multi user armature");
977                                         return;
978 #endif
979                                         tot_multiuser_arm_error++;
980                                 }
981                                 else {
982                                         /* Function to recenter armatures in editarmature.c
983                                          * Bone + object locations are handled there.
984                                          */
985                                         ED_armature_origin_set(ob, cursor, centermode, around);
986
987                                         tot_change++;
988                                         arm->id.tag |= LIB_TAG_DOIT;
989                                         /* do_inverse_offset = true; */ /* docenter_armature() handles this */
990
991                                         BKE_object_where_is_calc(&eval_ctx, scene, ob);
992                                         BKE_pose_where_is(&eval_ctx, scene, ob); /* needed for bone parents */
993
994                                         ignore_parent_tx(C, bmain, scene, ob);
995
996                                         if (obedit)
997                                                 break;
998                                 }
999                         }
1000                         else if (ob->type == OB_MBALL) {
1001                                 MetaBall *mb = ob->data;
1002
1003                                 if      (centermode == ORIGIN_TO_CURSOR)    { /* done */ }
1004                                 else if (around == V3D_AROUND_CENTER_MEAN)  { BKE_mball_center_median(mb, cent); }
1005                                 else                                        { BKE_mball_center_bounds(mb, cent); }
1006
1007                                 negate_v3_v3(cent_neg, cent);
1008                                 BKE_mball_translate(mb, cent_neg);
1009
1010                                 tot_change++;
1011                                 mb->id.tag |= LIB_TAG_DOIT;
1012                                 do_inverse_offset = true;
1013
1014                                 if (obedit) {
1015                                         if (centermode == GEOMETRY_TO_ORIGIN) {
1016                                                 DEG_id_tag_update(&obedit->id, OB_RECALC_DATA);
1017                                         }
1018                                         break;
1019                                 }
1020                         }
1021                         else if (ob->type == OB_LATTICE) {
1022                                 Lattice *lt = ob->data;
1023
1024                                 if      (centermode == ORIGIN_TO_CURSOR)    { /* done */ }
1025                                 else if (around == V3D_AROUND_CENTER_MEAN)  { BKE_lattice_center_median(lt, cent); }
1026                                 else                                        { BKE_lattice_center_bounds(lt, cent); }
1027
1028                                 negate_v3_v3(cent_neg, cent);
1029                                 BKE_lattice_translate(lt, cent_neg, 1);
1030
1031                                 tot_change++;
1032                                 lt->id.tag |= LIB_TAG_DOIT;
1033                                 do_inverse_offset = true;
1034                         }
1035
1036                         /* offset other selected objects */
1037                         if (do_inverse_offset && (centermode != GEOMETRY_TO_ORIGIN)) {
1038                                 CollectionPointerLink *ctx_link_other;
1039                                 float obmat[4][4];
1040
1041                                 /* was the object data modified
1042                                  * note: the functions above must set 'cent' */
1043
1044                                 /* convert the offset to parent space */
1045                                 BKE_object_to_mat4(ob, obmat);
1046                                 mul_v3_mat3_m4v3(centn, obmat, cent); /* omit translation part */
1047
1048                                 add_v3_v3(ob->loc, centn);
1049
1050                                 BKE_object_where_is_calc(&eval_ctx, scene, ob);
1051                                 if (ob->type == OB_ARMATURE) {
1052                                         BKE_pose_where_is(&eval_ctx, scene, ob); /* needed for bone parents */
1053                                 }
1054
1055                                 ignore_parent_tx(C, bmain, scene, ob);
1056                                 
1057                                 /* other users? */
1058                                 //CTX_DATA_BEGIN (C, Object *, ob_other, selected_editable_objects)
1059                                 //{
1060
1061                                 /* use existing context looper */
1062                                 for (ctx_link_other = ctx_data_list.first;
1063                                      ctx_link_other;
1064                                      ctx_link_other = ctx_link_other->next)
1065                                 {
1066                                         Object *ob_other = ctx_link_other->ptr.data;
1067
1068                                         if ((ob_other->flag & OB_DONE) == 0 &&
1069                                             ((ob->data && (ob->data == ob_other->data)) ||
1070                                              (ob->dup_group == ob_other->dup_group &&
1071                                               (ob->transflag | ob_other->transflag) & OB_DUPLIGROUP)))
1072                                         {
1073                                                 ob_other->flag |= OB_DONE;
1074                                                 DEG_id_tag_update(&ob_other->id, OB_RECALC_OB | OB_RECALC_DATA);
1075
1076                                                 mul_v3_mat3_m4v3(centn, ob_other->obmat, cent); /* omit translation part */
1077                                                 add_v3_v3(ob_other->loc, centn);
1078
1079                                                 BKE_object_where_is_calc(&eval_ctx, scene, ob_other);
1080                                                 if (ob_other->type == OB_ARMATURE) {
1081                                                         BKE_pose_where_is(&eval_ctx, scene, ob_other); /* needed for bone parents */
1082                                                 }
1083                                                 ignore_parent_tx(C, bmain, scene, ob_other);
1084                                         }
1085                                 }
1086                                 //CTX_DATA_END;
1087                         }
1088                 }
1089         }
1090         BLI_freelistN(&ctx_data_list);
1091
1092         for (tob = bmain->object.first; tob; tob = tob->id.next) {
1093                 if (tob->data && (((ID *)tob->data)->tag & LIB_TAG_DOIT)) {
1094                         BKE_mesh_batch_cache_dirty(tob->data, BKE_MESH_BATCH_DIRTY_ALL);
1095                         DEG_id_tag_update(&tob->id, OB_RECALC_OB | OB_RECALC_DATA);
1096                 }
1097         }
1098
1099         if (tot_change) {
1100                 WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL);
1101         }
1102
1103         /* Warn if any errors occurred */
1104         if (tot_lib_error + tot_multiuser_arm_error) {
1105                 BKE_reportf(op->reports, RPT_WARNING, "%i object(s) not centered, %i changed:", tot_lib_error + tot_multiuser_arm_error, tot_change);
1106                 if (tot_lib_error)
1107                         BKE_reportf(op->reports, RPT_WARNING, "|%i linked library object(s)", tot_lib_error);
1108                 if (tot_multiuser_arm_error)
1109                         BKE_reportf(op->reports, RPT_WARNING, "|%i multiuser armature object(s)", tot_multiuser_arm_error);
1110         }
1111
1112         return OPERATOR_FINISHED;
1113 }
1114
1115 void OBJECT_OT_origin_set(wmOperatorType *ot)
1116 {
1117         static const EnumPropertyItem prop_set_center_types[] = {
1118                 {GEOMETRY_TO_ORIGIN, "GEOMETRY_ORIGIN", 0, "Geometry to Origin", "Move object geometry to object origin"},
1119                 {ORIGIN_TO_GEOMETRY, "ORIGIN_GEOMETRY", 0, "Origin to Geometry",
1120                  "Calculate the center of geometry based on the current pivot point (median, otherwise bounding-box)"},
1121                 {ORIGIN_TO_CURSOR, "ORIGIN_CURSOR", 0, "Origin to 3D Cursor",
1122                  "Move object origin to position of the 3D cursor"},
1123                 /* Intentional naming mismatch since some scripts refer to this. */
1124                 {ORIGIN_TO_CENTER_OF_MASS_SURFACE, "ORIGIN_CENTER_OF_MASS", 0, "Origin to Center of Mass (Surface)",
1125                  "Calculate the center of mass from the surface area"},
1126                 {ORIGIN_TO_CENTER_OF_MASS_VOLUME, "ORIGIN_CENTER_OF_VOLUME", 0, "Origin to Center of Mass (Volume)",
1127                  "Calculate the center of mass from the volume (must be manifold geometry with consistent normals)"},
1128                 {0, NULL, 0, NULL, NULL}
1129         };
1130         
1131         static const EnumPropertyItem prop_set_bounds_types[] = {
1132                 {V3D_AROUND_CENTER_MEAN, "MEDIAN", 0, "Median Center", ""},
1133                 {V3D_AROUND_CENTER_BOUNDS, "BOUNDS", 0, "Bounds Center", ""},
1134                 {0, NULL, 0, NULL, NULL}
1135         };
1136         
1137         /* identifiers */
1138         ot->name = "Set Origin";
1139         ot->description = "Set the object's origin, by either moving the data, or set to center of data, or use 3D cursor";
1140         ot->idname = "OBJECT_OT_origin_set";
1141         
1142         /* api callbacks */
1143         ot->invoke = WM_menu_invoke;
1144         ot->exec = object_origin_set_exec;
1145         
1146         ot->poll = ED_operator_scene_editable;
1147         
1148         /* flags */
1149         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1150         
1151         ot->prop = RNA_def_enum(ot->srna, "type", prop_set_center_types, 0, "Type", "");
1152         RNA_def_enum(ot->srna, "center", prop_set_bounds_types, V3D_AROUND_CENTER_MEAN, "Center", "");
1153 }
1154
1155 /* -------------------------------------------------------------------- */
1156
1157 /** \name Transform Axis Target
1158  *
1159  * Note this is an experemental operator to point lamps/cameras at objects.
1160  * We may re-work how this behaves based on user feedback.
1161  * - campbell.
1162  * \{ */
1163
1164 /* When using multiple objects, apply their relative rotational offset to the active object. */
1165 #define USE_RELATIVE_ROTATION
1166
1167 struct XFormAxisItem {
1168         Object *ob;
1169         float rot_mat[3][3];
1170         void *obtfm;
1171         float xform_dist;
1172
1173 #ifdef USE_RELATIVE_ROTATION
1174         /* use when translating multiple */
1175         float xform_rot_offset[3][3];
1176 #endif
1177 };
1178
1179 struct XFormAxisData {
1180         ViewContext vc;
1181         struct {
1182                 float depth;
1183                 float normal[3];
1184                 bool is_depth_valid;
1185                 bool is_normal_valid;
1186         } prev;
1187
1188         struct XFormAxisItem *object_data;
1189         uint object_data_len;
1190         bool is_translate;
1191
1192         int init_event;
1193 };
1194
1195 static bool object_is_target_compat(const Object *ob)
1196 {
1197         if (ob->type == OB_LAMP) {
1198                 const Lamp *la = ob->data;
1199                 if (ELEM(la->type, LA_SUN, LA_SPOT, LA_HEMI, LA_AREA)) {
1200                         return true;
1201                 }
1202         }
1203         /* We might want to enable this later, for now just lamps */
1204 #if 0
1205         else if (ob->type == OB_CAMERA) {
1206                 return true;
1207         }
1208 #endif
1209         return false;
1210 }
1211
1212 static void object_transform_axis_target_free_data(wmOperator *op)
1213 {
1214         struct XFormAxisData *xfd = op->customdata;
1215         struct XFormAxisItem *item = xfd->object_data;
1216         for (int i = 0; i < xfd->object_data_len; i++, item++) {
1217                 MEM_freeN(item->obtfm);
1218         }
1219         MEM_freeN(xfd->object_data);
1220         MEM_freeN(xfd);
1221         op->customdata = NULL;
1222 }
1223
1224 /* We may want to expose as alternative to: BKE_object_apply_rotation */
1225 static void object_apply_rotation(Object *ob, const float rmat[3][3])
1226 {
1227         float size[3];
1228         float loc[3];
1229         float rmat4[4][4];
1230         copy_m4_m3(rmat4, rmat);
1231
1232         copy_v3_v3(size, ob->size);
1233         copy_v3_v3(loc, ob->loc);
1234         BKE_object_apply_mat4(ob, rmat4, true, true);
1235         copy_v3_v3(ob->size, size);
1236         copy_v3_v3(ob->loc, loc);
1237 }
1238 /* We may want to extract this to: BKE_object_apply_location */
1239 static void object_apply_location(Object *ob, const float loc[3])
1240 {
1241         /* quick but weak */
1242         Object ob_prev = *ob;
1243         float mat[4][4];
1244         copy_m4_m4(mat, ob->obmat);
1245         copy_v3_v3(mat[3], loc);
1246         BKE_object_apply_mat4(ob, mat, true, true);
1247         copy_v3_v3(mat[3], ob->loc);
1248         *ob = ob_prev;
1249         copy_v3_v3(ob->loc, mat[3]);
1250 }
1251
1252 static void object_orient_to_location(
1253         Object *ob, float rot_orig[3][3], const float axis[3], const float location[3])
1254 {
1255         float delta[3];
1256         sub_v3_v3v3(delta, ob->obmat[3], location);
1257         if (normalize_v3(delta) != 0.0f) {
1258                 if (len_squared_v3v3(delta, axis) > FLT_EPSILON) {
1259                         float delta_rot[3][3];
1260                         float final_rot[3][3];
1261                         rotation_between_vecs_to_mat3(delta_rot, axis, delta);
1262
1263                         mul_m3_m3m3(final_rot, delta_rot, rot_orig);
1264
1265                         object_apply_rotation(ob, final_rot);
1266
1267                         DEG_id_tag_update(&ob->id, OB_RECALC_OB);
1268                 }
1269         }
1270 }
1271
1272 static void object_transform_axis_target_cancel(bContext *C, wmOperator *op)
1273 {
1274         struct XFormAxisData *xfd = op->customdata;
1275         struct XFormAxisItem *item = xfd->object_data;
1276         for (int i = 0; i < xfd->object_data_len; i++, item++) {
1277                 BKE_object_tfm_restore(item->ob, item->obtfm);
1278                 DEG_id_tag_update(&item->ob->id, OB_RECALC_OB);
1279                 WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, item->ob);
1280         }
1281
1282         object_transform_axis_target_free_data(op);
1283 }
1284
1285 static int object_transform_axis_target_invoke(bContext *C, wmOperator *op, const wmEvent *event)
1286 {
1287         ViewContext vc;
1288         ED_view3d_viewcontext_init(C, &vc);
1289
1290         if (!object_is_target_compat(vc.obact)) {
1291                 /* Falls back to texture space transform. */
1292                 return OPERATOR_PASS_THROUGH;
1293         }
1294
1295         EvaluationContext eval_ctx;
1296
1297         CTX_data_eval_ctx(C, &eval_ctx);
1298
1299         ED_view3d_autodist_init(&eval_ctx, vc.depsgraph, vc.ar, vc.v3d, 0);
1300
1301         if (vc.rv3d->depths != NULL) {
1302                 vc.rv3d->depths->damaged = true;
1303         }
1304         ED_view3d_depth_update(vc.ar);
1305
1306         if (vc.rv3d->depths == NULL) {
1307                 BKE_report(op->reports, RPT_WARNING, "Unable to access depth buffer, using view plane");
1308                 return OPERATOR_CANCELLED;
1309         }
1310
1311         ED_region_tag_redraw(vc.ar);
1312
1313         struct XFormAxisData *xfd;
1314         xfd = op->customdata = MEM_callocN(sizeof(struct XFormAxisData), __func__);
1315
1316         /* Don't change this at runtime. */
1317         xfd->vc = vc;
1318         xfd->vc.mval[0] = event->mval[0];
1319         xfd->vc.mval[1] = event->mval[1];
1320
1321         xfd->prev.depth = 1.0f;
1322         xfd->prev.is_depth_valid = false;
1323         xfd->prev.is_normal_valid = false;
1324         xfd->is_translate = false;
1325
1326         xfd->init_event = WM_userdef_event_type_from_keymap_type(event->type);
1327
1328         {
1329                 struct XFormAxisItem *object_data = NULL;
1330                 BLI_array_declare(object_data);
1331
1332                 struct XFormAxisItem *item = BLI_array_append_ret(object_data);
1333                 item->ob = xfd->vc.obact;
1334
1335                 CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
1336                 {
1337                         if ((ob != xfd->vc.obact) && object_is_target_compat(ob)) {
1338                                 item = BLI_array_append_ret(object_data);
1339                                 item->ob = ob;
1340                         }
1341                 }
1342                 CTX_DATA_END;
1343
1344                 xfd->object_data = object_data;
1345                 xfd->object_data_len = BLI_array_len(object_data);
1346
1347                 if (xfd->object_data_len != BLI_array_len(object_data)) {
1348                         xfd->object_data = MEM_reallocN(xfd->object_data, xfd->object_data_len * sizeof(*xfd->object_data));
1349                 }
1350         }
1351
1352         {
1353                 struct XFormAxisItem *item = xfd->object_data;
1354                 for (int i = 0; i < xfd->object_data_len; i++, item++) {
1355                         item->obtfm = BKE_object_tfm_backup(item->ob);
1356                         BKE_object_rot_to_mat3(item->ob, item->rot_mat, true);
1357                 }
1358         }
1359
1360         WM_event_add_modal_handler(C, op);
1361
1362         return OPERATOR_RUNNING_MODAL;
1363 }
1364
1365 static int object_transform_axis_target_modal(bContext *C, wmOperator *op, const wmEvent *event)
1366 {
1367         struct XFormAxisData *xfd = op->customdata;
1368         ARegion *ar = xfd->vc.ar;
1369
1370         view3d_operator_needs_opengl(C);
1371
1372         const bool is_translate = (event->ctrl != 0);
1373         const bool is_translate_init = is_translate && (xfd->is_translate != is_translate);
1374
1375         if (event->type == MOUSEMOVE || is_translate_init) {
1376                 const ViewDepths *depths = xfd->vc.rv3d->depths;
1377                 if (depths &&
1378                     ((unsigned int)event->mval[0] < depths->w) &&
1379                     ((unsigned int)event->mval[1] < depths->h))
1380                 {
1381                         double depth = (double)ED_view3d_depth_read_cached(&xfd->vc, event->mval);
1382                         float location_world[3];
1383                         if (depth == 1.0f) {
1384                                 if (xfd->prev.is_depth_valid) {
1385                                         depth = (double)xfd->prev.depth;
1386                                 }
1387                         }
1388                         if ((depth > depths->depth_range[0]) && (depth < depths->depth_range[1])) {
1389                                 xfd->prev.depth = depth;
1390                                 xfd->prev.is_depth_valid = true;
1391                                 if (ED_view3d_depth_unproject(ar, event->mval, depth, location_world)) {
1392                                         if (is_translate) {
1393
1394                                                 float normal[3];
1395                                                 bool normal_found = false;
1396                                                 if (ED_view3d_depth_read_cached_normal(&xfd->vc, event->mval, normal)) {
1397                                                         normal_found = true;
1398
1399                                                         /* cheap attempt to smooth normals out a bit! */
1400                                                         const uint ofs = 2;
1401                                                         for (uint x = -ofs; x <= ofs; x += ofs / 2) {
1402                                                                 for (uint y = -ofs; y <= ofs; y += ofs / 2) {
1403                                                                         if (x != 0 && y != 0) {
1404                                                                                 int mval_ofs[2] = {event->mval[0] + x, event->mval[1] + y};
1405                                                                                 float n[3];
1406                                                                                 if (ED_view3d_depth_read_cached_normal(
1407                                                                                         &xfd->vc, mval_ofs, n))
1408                                                                                 {
1409                                                                                         add_v3_v3(normal, n);
1410                                                                                 }
1411                                                                         }
1412                                                                 }
1413                                                         }
1414                                                         normalize_v3(normal);
1415                                                 }
1416                                                 else if (xfd->prev.is_normal_valid) {
1417                                                         copy_v3_v3(normal, xfd->prev.normal);
1418                                                         normal_found = true;
1419                                                 }
1420
1421                                                 if (normal_found) {
1422 #ifdef USE_RELATIVE_ROTATION
1423                                                         if (is_translate_init && xfd->object_data_len > 1) {
1424                                                                 float xform_rot_offset_inv_first[3][3];
1425                                                                 struct XFormAxisItem *item = xfd->object_data;
1426                                                                 for (int i = 0; i < xfd->object_data_len; i++, item++) {
1427                                                                         copy_m3_m4(item->xform_rot_offset, item->ob->obmat);
1428                                                                         normalize_m3(item->xform_rot_offset);
1429
1430                                                                         if (i == 0) {
1431                                                                                 invert_m3_m3(xform_rot_offset_inv_first, xfd->object_data[0].xform_rot_offset);
1432                                                                         }
1433                                                                         else {
1434                                                                                 mul_m3_m3m3(item->xform_rot_offset,
1435                                                                                             item->xform_rot_offset,
1436                                                                                             xform_rot_offset_inv_first);
1437                                                                         }
1438                                                                 }
1439                                                         }
1440
1441 #endif
1442
1443                                                         struct XFormAxisItem *item = xfd->object_data;
1444                                                         for (int i = 0; i < xfd->object_data_len; i++, item++) {
1445                                                                 if (is_translate_init) {
1446                                                                         float ob_axis[3];
1447                                                                         item->xform_dist = len_v3v3(item->ob->obmat[3], location_world);
1448                                                                         normalize_v3_v3(ob_axis, item->ob->obmat[2]);
1449                                                                         /* Scale to avoid adding distance when moving between surfaces. */
1450                                                                         float scale = fabsf(dot_v3v3(ob_axis, normal));
1451                                                                         item->xform_dist *= scale;
1452                                                                 }
1453
1454                                                                 float target_normal[3];
1455                                                                 copy_v3_v3(target_normal, normal);
1456
1457 #ifdef USE_RELATIVE_ROTATION
1458                                                                 if (i != 0) {
1459                                                                         mul_m3_v3(item->xform_rot_offset, target_normal);
1460                                                                 }
1461 #endif
1462                                                                 {
1463                                                                         float loc[3];
1464
1465                                                                         copy_v3_v3(loc, location_world);
1466                                                                         madd_v3_v3fl(loc, target_normal, item->xform_dist);
1467                                                                         object_apply_location(item->ob, loc);
1468                                                                         copy_v3_v3(item->ob->obmat[3], loc);  /* so orient behaves as expected */
1469                                                                 }
1470
1471                                                                 object_orient_to_location(item->ob, item->rot_mat, item->rot_mat[2], location_world);
1472                                                                 WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, item->ob);
1473                                                         }
1474                                                         copy_v3_v3(xfd->prev.normal, normal);
1475                                                         xfd->prev.is_normal_valid = true;
1476                                                 }
1477                                         }
1478                                         else {
1479                                                 struct XFormAxisItem *item = xfd->object_data;
1480                                                 for (int i = 0; i < xfd->object_data_len; i++, item++) {
1481                                                         object_orient_to_location(item->ob, item->rot_mat, item->rot_mat[2], location_world);
1482                                                         WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, item->ob);
1483                                                 }
1484                                                 xfd->prev.is_normal_valid = false;
1485                                         }
1486                                 }
1487                         }
1488                 }
1489                 xfd->is_translate = is_translate;
1490
1491                 ED_region_tag_redraw(xfd->vc.ar);
1492         }
1493
1494         bool is_finished = false;
1495
1496         if (ISMOUSE(xfd->init_event)) {
1497                 if ((event->type == xfd->init_event) && (event->val == KM_RELEASE)) {
1498                         is_finished = true;
1499                 }
1500         }
1501         else {
1502                 if (ELEM(event->type, LEFTMOUSE, RETKEY, PADENTER)) {
1503                         is_finished = true;
1504                 }
1505         }
1506
1507         if (is_finished) {
1508                 object_transform_axis_target_free_data(op);
1509                 return OPERATOR_FINISHED;
1510         }
1511         else if (ELEM(event->type, ESCKEY, RIGHTMOUSE)) {
1512                 object_transform_axis_target_cancel(C, op);
1513                 return OPERATOR_CANCELLED;
1514         }
1515
1516
1517         return OPERATOR_RUNNING_MODAL;
1518 }
1519
1520 void OBJECT_OT_transform_axis_target(wmOperatorType *ot)
1521 {
1522         /* identifiers */
1523         ot->name = "Interactive Lamp Track to Cursor";
1524         ot->description = "Interactively point cameras and lamps to a location (Ctrl translates)";
1525         ot->idname = "OBJECT_OT_transform_axis_target";
1526
1527         /* api callbacks */
1528         ot->invoke = object_transform_axis_target_invoke;
1529         ot->cancel = object_transform_axis_target_cancel;
1530         ot->modal = object_transform_axis_target_modal;
1531         ot->poll = ED_operator_region_view3d_active;
1532
1533         /* flags */
1534         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_BLOCKING;
1535 }
1536
1537 #undef USE_RELATIVE_ROTATION
1538
1539 /** \} */