Merged changes in the trunk up to revision 55357.
[blender-staging.git] / source / blender / blenkernel / intern / object.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  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/blenkernel/intern/object.c
29  *  \ingroup bke
30  */
31
32
33 #include <string.h>
34 #include <math.h>
35 #include <stdio.h>                      
36
37 #include "MEM_guardedalloc.h"
38
39 #include "DNA_anim_types.h"
40 #include "DNA_armature_types.h"
41 #include "DNA_camera_types.h"
42 #include "DNA_constraint_types.h"
43 #include "DNA_group_types.h"
44 #include "DNA_key_types.h"
45 #include "DNA_lattice_types.h"
46 #include "DNA_material_types.h"
47 #include "DNA_meta_types.h"
48 #include "DNA_mesh_types.h"
49 #include "DNA_meshdata_types.h"
50 #include "DNA_movieclip_types.h"
51 #include "DNA_scene_types.h"
52 #include "DNA_screen_types.h"
53 #include "DNA_sequence_types.h"
54 #include "DNA_smoke_types.h"
55 #include "DNA_sound_types.h"
56 #include "DNA_space_types.h"
57 #include "DNA_view3d_types.h"
58 #include "DNA_world_types.h"
59 #include "DNA_object_types.h"
60 #include "DNA_property_types.h"
61 #include "DNA_rigidbody_types.h"
62
63 #include "BLI_blenlib.h"
64 #include "BLI_math.h"
65 #include "BLI_utildefines.h"
66 #include "BLI_linklist.h"
67
68 #include "BKE_pbvh.h"
69 #include "BKE_main.h"
70 #include "BKE_global.h"
71 #include "BKE_idprop.h"
72 #include "BKE_armature.h"
73 #include "BKE_action.h"
74 #include "BKE_bullet.h"
75 #include "BKE_colortools.h"
76 #include "BKE_deform.h"
77 #include "BKE_depsgraph.h"
78 #include "BKE_DerivedMesh.h"
79 #include "BKE_animsys.h"
80 #include "BKE_anim.h"
81 #include "BKE_constraint.h"
82 #include "BKE_curve.h"
83 #include "BKE_displist.h"
84 #include "BKE_effect.h"
85 #include "BKE_fcurve.h"
86 #include "BKE_group.h"
87 #include "BKE_icons.h"
88 #include "BKE_image.h"
89 #include "BKE_key.h"
90 #include "BKE_lamp.h"
91 #include "BKE_lattice.h"
92 #include "BKE_library.h"
93 #include "BKE_mesh.h"
94 #include "BKE_tessmesh.h"
95 #include "BKE_mball.h"
96 #include "BKE_modifier.h"
97 #include "BKE_node.h"
98 #include "BKE_object.h"
99 #include "BKE_paint.h"
100 #include "BKE_particle.h"
101 #include "BKE_pointcache.h"
102 #include "BKE_property.h"
103 #include "BKE_rigidbody.h"
104 #include "BKE_sca.h"
105 #include "BKE_scene.h"
106 #include "BKE_sequencer.h"
107 #include "BKE_speaker.h"
108 #include "BKE_softbody.h"
109 #include "BKE_material.h"
110 #include "BKE_camera.h"
111
112 #ifdef WITH_MOD_FLUID
113 #include "LBM_fluidsim.h"
114 #endif
115
116 #ifdef WITH_PYTHON
117 #include "BPY_extern.h"
118 #endif
119
120 #include "GPU_material.h"
121
122 #ifdef WITH_FREESTYLE
123 #  include "FRS_freestyle.h"
124 #endif
125
126 /* Local function protos */
127 float originmat[3][3];  /* after BKE_object_where_is_calc(), can be used in other functions (bad!) */
128
129 void BKE_object_workob_clear(Object *workob)
130 {
131         memset(workob, 0, sizeof(Object));
132         
133         workob->size[0] = workob->size[1] = workob->size[2] = 1.0f;
134         workob->dscale[0] = workob->dscale[1] = workob->dscale[2] = 1.0f;
135         workob->rotmode = ROT_MODE_EUL;
136 }
137
138 void BKE_object_update_base_layer(struct Scene *scene, Object *ob)
139 {
140         Base *base = scene->base.first;
141
142         while (base) {
143                 if (base->object == ob) base->lay = ob->lay;
144                 base = base->next;
145         }
146 }
147
148 void BKE_object_free_particlesystems(Object *ob)
149 {
150         while (ob->particlesystem.first) {
151                 ParticleSystem *psys = ob->particlesystem.first;
152                 
153                 BLI_remlink(&ob->particlesystem, psys);
154                 
155                 psys_free(ob, psys);
156         }
157 }
158
159 void BKE_object_free_softbody(Object *ob)
160 {
161         if (ob->soft) {
162                 sbFree(ob->soft);
163                 ob->soft = NULL;
164         }
165 }
166
167 void BKE_object_free_bulletsoftbody(Object *ob)
168 {
169         if (ob->bsoft) {
170                 bsbFree(ob->bsoft);
171                 ob->bsoft = NULL;
172         }
173 }
174
175 void BKE_object_free_modifiers(Object *ob)
176 {
177         while (ob->modifiers.first) {
178                 ModifierData *md = ob->modifiers.first;
179                 
180                 BLI_remlink(&ob->modifiers, md);
181                 
182                 modifier_free(md);
183         }
184
185         /* particle modifiers were freed, so free the particlesystems as well */
186         BKE_object_free_particlesystems(ob);
187
188         /* same for softbody */
189         BKE_object_free_softbody(ob);
190 }
191
192 bool BKE_object_support_modifier_type_check(Object *ob, int modifier_type)
193 {
194         ModifierTypeInfo *mti;
195
196         mti = modifierType_getInfo(modifier_type);
197
198         if (!((mti->flags & eModifierTypeFlag_AcceptsCVs) ||
199               (ob->type == OB_MESH && (mti->flags & eModifierTypeFlag_AcceptsMesh))))
200         {
201                 return false;
202         }
203
204         return true;
205 }
206
207 void BKE_object_link_modifiers(struct Object *ob_dst, struct Object *ob_src)
208 {
209         ModifierData *md;
210         BKE_object_free_modifiers(ob_dst);
211
212         if (!ELEM5(ob_dst->type, OB_MESH, OB_CURVE, OB_SURF, OB_FONT, OB_LATTICE)) {
213                 /* only objects listed above can have modifiers and linking them to objects
214                  * which doesn't have modifiers stack is quite silly */
215                 return;
216         }
217
218         for (md = ob_src->modifiers.first; md; md = md->next) {
219                 ModifierData *nmd = NULL;
220
221                 if (ELEM4(md->type,
222                           eModifierType_Hook,
223                           eModifierType_Softbody,
224                           eModifierType_ParticleInstance,
225                           eModifierType_Collision))
226                 {
227                         continue;
228                 }
229
230                 if (!BKE_object_support_modifier_type_check(ob_dst, md->type))
231                         continue;
232
233                 nmd = modifier_new(md->type);
234                 BLI_strncpy(nmd->name, md->name, sizeof(nmd->name));
235                 modifier_copyData(md, nmd);
236                 BLI_addtail(&ob_dst->modifiers, nmd);
237                 modifier_unique_name(&ob_dst->modifiers, nmd);
238         }
239
240         BKE_object_copy_particlesystems(ob_dst, ob_src);
241         BKE_object_copy_softbody(ob_dst, ob_src);
242
243         /* TODO: smoke?, cloth? */
244 }
245
246 /* here we will collect all local displist stuff */
247 /* also (ab)used in depsgraph */
248 void BKE_object_free_display(Object *ob)
249 {
250         if (ob->derivedDeform) {
251                 ob->derivedDeform->needsFree = 1;
252                 ob->derivedDeform->release(ob->derivedDeform);
253                 ob->derivedDeform = NULL;
254         }
255         if (ob->derivedFinal) {
256                 ob->derivedFinal->needsFree = 1;
257                 ob->derivedFinal->release(ob->derivedFinal);
258                 ob->derivedFinal = NULL;
259         }
260         
261         BKE_displist_free(&ob->disp);
262 }
263
264 void free_sculptsession_deformMats(SculptSession *ss)
265 {
266         if (ss->orig_cos) MEM_freeN(ss->orig_cos);
267         if (ss->deform_cos) MEM_freeN(ss->deform_cos);
268         if (ss->deform_imats) MEM_freeN(ss->deform_imats);
269
270         ss->orig_cos = NULL;
271         ss->deform_cos = NULL;
272         ss->deform_imats = NULL;
273 }
274
275 /* Write out the sculpt dynamic-topology BMesh to the Mesh */
276 void sculptsession_bm_to_me(struct Object *ob, int reorder)
277 {
278         if (ob && ob->sculpt) {
279                 SculptSession *ss = ob->sculpt;
280
281                 if (ss->bm) {
282                         if (ob->data) {
283                                 BMIter iter;
284                                 BMFace *efa;
285                                 BM_ITER_MESH (efa, &iter, ss->bm, BM_FACES_OF_MESH) {
286                                         BM_elem_flag_set(efa, BM_ELEM_SMOOTH,
287                                                          ss->bm_smooth_shading);
288                                 }
289                                 if (reorder)
290                                         BM_log_mesh_elems_reorder(ss->bm, ss->bm_log);
291                                 BM_mesh_bm_to_me(ss->bm, ob->data, FALSE);
292                         }
293                 }
294
295                 /* ensure the objects DerivedMesh mesh doesn't hold onto arrays now realloc'd in the mesh [#34473] */
296                 DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
297         }
298 }
299
300 void free_sculptsession(Object *ob)
301 {
302         if (ob && ob->sculpt) {
303                 SculptSession *ss = ob->sculpt;
304                 DerivedMesh *dm = ob->derivedFinal;
305
306                 if (ss->bm) {
307                         sculptsession_bm_to_me(ob, TRUE);
308                         BM_mesh_free(ss->bm);
309                 }
310
311                 if (ss->pbvh)
312                         BKE_pbvh_free(ss->pbvh);
313                 if (ss->bm_log)
314                         BM_log_free(ss->bm_log);
315
316                 if (dm && dm->getPBVH)
317                         dm->getPBVH(NULL, dm);  /* signal to clear */
318
319                 if (ss->texcache)
320                         MEM_freeN(ss->texcache);
321
322                 if (ss->tex_pool)
323                         BKE_image_pool_free(ss->tex_pool);
324
325                 if (ss->layer_co)
326                         MEM_freeN(ss->layer_co);
327
328                 if (ss->orig_cos)
329                         MEM_freeN(ss->orig_cos);
330                 if (ss->deform_cos)
331                         MEM_freeN(ss->deform_cos);
332                 if (ss->deform_imats)
333                         MEM_freeN(ss->deform_imats);
334
335                 MEM_freeN(ss);
336
337                 ob->sculpt = NULL;
338         }
339 }
340
341
342 /* do not free object itself */
343 void BKE_object_free(Object *ob)
344 {
345         int a;
346         
347         BKE_object_free_display(ob);
348         
349         /* disconnect specific data, but not for lib data (might be indirect data, can get relinked) */
350         if (ob->data) {
351                 ID *id = ob->data;
352                 id->us--;
353                 if (id->us == 0 && id->lib == NULL) {
354                         switch (ob->type) {
355                                 case OB_MESH:
356                                         BKE_mesh_unlink((Mesh *)id);
357                                         break;
358                                 case OB_CURVE:
359                                         BKE_curve_unlink((Curve *)id);
360                                         break;
361                                 case OB_MBALL:
362                                         BKE_mball_unlink((MetaBall *)id);
363                                         break;
364                         }
365                 }
366                 ob->data = NULL;
367         }
368
369         if (ob->mat) {
370                 for (a = 0; a < ob->totcol; a++) {
371                         if (ob->mat[a]) ob->mat[a]->id.us--;
372                 }
373                 MEM_freeN(ob->mat);
374         }
375         if (ob->matbits) MEM_freeN(ob->matbits);
376         ob->mat = NULL;
377         ob->matbits = NULL;
378         if (ob->bb) MEM_freeN(ob->bb); 
379         ob->bb = NULL;
380         if (ob->adt) BKE_free_animdata((ID *)ob);
381         if (ob->poselib) ob->poselib->id.us--;
382         if (ob->gpd) ((ID *)ob->gpd)->us--;
383         if (ob->defbase.first)
384                 BLI_freelistN(&ob->defbase);
385         if (ob->pose)
386                 BKE_pose_free(ob->pose);
387         if (ob->mpath)
388                 animviz_free_motionpath(ob->mpath);
389         BKE_bproperty_free_list(&ob->prop);
390         BKE_object_free_modifiers(ob);
391         
392         free_sensors(&ob->sensors);
393         free_controllers(&ob->controllers);
394         free_actuators(&ob->actuators);
395         
396         BKE_free_constraints(&ob->constraints);
397         
398         free_partdeflect(ob->pd);
399         BKE_rigidbody_free_object(ob);
400         BKE_rigidbody_free_constraint(ob);
401
402         if (ob->soft) sbFree(ob->soft);
403         if (ob->bsoft) bsbFree(ob->bsoft);
404         if (ob->gpulamp.first) GPU_lamp_free(ob);
405
406         free_sculptsession(ob);
407
408         if (ob->pc_ids.first) BLI_freelistN(&ob->pc_ids);
409 }
410
411 static void unlink_object__unlinkModifierLinks(void *userData, Object *ob, Object **obpoin)
412 {
413         Object *unlinkOb = userData;
414
415         if (*obpoin == unlinkOb) {
416                 *obpoin = NULL;
417                 // XXX: should this just be OB_RECALC_DATA?
418                 DAG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
419         }
420 }
421
422 void BKE_object_unlink(Object *ob)
423 {
424         Main *bmain = G.main;
425         Object *obt;
426         Material *mat;
427         World *wrld;
428         bScreen *sc;
429         Scene *sce;
430         Curve *cu;
431         Tex *tex;
432         Group *group;
433         Camera *camera;
434         bConstraint *con;
435         //bActionStrip *strip; // XXX animsys 
436         ModifierData *md;
437         ARegion *ar;
438         RegionView3D *rv3d;
439         int a, found;
440         
441         unlink_controllers(&ob->controllers);
442         unlink_actuators(&ob->actuators);
443         
444         /* check all objects: parents en bevels and fields, also from libraries */
445         /* FIXME: need to check all animation blocks (drivers) */
446         obt = bmain->object.first;
447         while (obt) {
448                 if (obt->proxy == ob)
449                         obt->proxy = NULL;
450                 if (obt->proxy_from == ob) {
451                         obt->proxy_from = NULL;
452                         DAG_id_tag_update(&obt->id, OB_RECALC_OB);
453                 }
454                 if (obt->proxy_group == ob)
455                         obt->proxy_group = NULL;
456                 
457                 if (obt->parent == ob) {
458                         obt->parent = NULL;
459                         DAG_id_tag_update(&obt->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
460                 }
461                 
462                 modifiers_foreachObjectLink(obt, unlink_object__unlinkModifierLinks, ob);
463                 
464                 if (ELEM(obt->type, OB_CURVE, OB_FONT)) {
465                         cu = obt->data;
466
467                         if (cu->bevobj == ob) {
468                                 cu->bevobj = NULL;
469                                 DAG_id_tag_update(&obt->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
470                         }
471                         if (cu->taperobj == ob) {
472                                 cu->taperobj = NULL;
473                                 DAG_id_tag_update(&obt->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
474                         }
475                         if (cu->textoncurve == ob) {
476                                 cu->textoncurve = NULL;
477                                 DAG_id_tag_update(&obt->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
478                         }
479                 }
480                 else if (obt->type == OB_ARMATURE && obt->pose) {
481                         bPoseChannel *pchan;
482                         for (pchan = obt->pose->chanbase.first; pchan; pchan = pchan->next) {
483                                 for (con = pchan->constraints.first; con; con = con->next) {
484                                         bConstraintTypeInfo *cti = BKE_constraint_get_typeinfo(con);
485                                         ListBase targets = {NULL, NULL};
486                                         bConstraintTarget *ct;
487                                         
488                                         if (cti && cti->get_constraint_targets) {
489                                                 cti->get_constraint_targets(con, &targets);
490                                                 
491                                                 for (ct = targets.first; ct; ct = ct->next) {
492                                                         if (ct->tar == ob) {
493                                                                 ct->tar = NULL;
494                                                                 ct->subtarget[0] = '\0';
495                                                                 DAG_id_tag_update(&obt->id, OB_RECALC_DATA);
496                                                         }
497                                                 }
498                                                 
499                                                 if (cti->flush_constraint_targets)
500                                                         cti->flush_constraint_targets(con, &targets, 0);
501                                         }
502                                 }
503                                 if (pchan->custom == ob)
504                                         pchan->custom = NULL;
505                         }
506                 }
507                 else if (ELEM(OB_MBALL, ob->type, obt->type)) {
508                         if (BKE_mball_is_basis_for(obt, ob))
509                                 DAG_id_tag_update(&obt->id, OB_RECALC_DATA);
510                 }
511                 
512                 sca_remove_ob_poin(obt, ob);
513                 
514                 for (con = obt->constraints.first; con; con = con->next) {
515                         bConstraintTypeInfo *cti = BKE_constraint_get_typeinfo(con);
516                         ListBase targets = {NULL, NULL};
517                         bConstraintTarget *ct;
518                         
519                         if (cti && cti->get_constraint_targets) {
520                                 cti->get_constraint_targets(con, &targets);
521                                 
522                                 for (ct = targets.first; ct; ct = ct->next) {
523                                         if (ct->tar == ob) {
524                                                 ct->tar = NULL;
525                                                 ct->subtarget[0] = '\0';
526                                                 DAG_id_tag_update(&obt->id, OB_RECALC_DATA);
527                                         }
528                                 }
529                                 
530                                 if (cti->flush_constraint_targets)
531                                         cti->flush_constraint_targets(con, &targets, 0);
532                         }
533                 }
534                 
535                 /* object is deflector or field */
536                 if (ob->pd) {
537                         if (obt->soft)
538                                 DAG_id_tag_update(&obt->id, OB_RECALC_DATA);
539
540                         /* cloth */
541                         for (md = obt->modifiers.first; md; md = md->next)
542                                 if (md->type == eModifierType_Cloth)
543                                         DAG_id_tag_update(&obt->id, OB_RECALC_DATA);
544                 }
545                 
546                 /* strips */
547 #if 0 // XXX old animation system
548                 for (strip = obt->nlastrips.first; strip; strip = strip->next) {
549                         if (strip->object == ob)
550                                 strip->object = NULL;
551                         
552                         if (strip->modifiers.first) {
553                                 bActionModifier *amod;
554                                 for (amod = strip->modifiers.first; amod; amod = amod->next)
555                                         if (amod->ob == ob)
556                                                 amod->ob = NULL;
557                         }
558                 }
559 #endif // XXX old animation system
560
561                 /* particle systems */
562                 if (obt->particlesystem.first) {
563                         ParticleSystem *tpsys = obt->particlesystem.first;
564                         for (; tpsys; tpsys = tpsys->next) {
565                                 BoidState *state = NULL;
566                                 BoidRule *rule = NULL;
567
568                                 ParticleTarget *pt = tpsys->targets.first;
569                                 for (; pt; pt = pt->next) {
570                                         if (pt->ob == ob) {
571                                                 pt->ob = NULL;
572                                                 DAG_id_tag_update(&obt->id, OB_RECALC_DATA);
573                                                 break;
574                                         }
575                                 }
576
577                                 if (tpsys->target_ob == ob) {
578                                         tpsys->target_ob = NULL;
579                                         DAG_id_tag_update(&obt->id, OB_RECALC_DATA);
580                                 }
581
582                                 if (tpsys->part->dup_ob == ob)
583                                         tpsys->part->dup_ob = NULL;
584
585                                 if (tpsys->part->phystype == PART_PHYS_BOIDS) {
586                                         ParticleData *pa;
587                                         BoidParticle *bpa;
588                                         int p;
589
590                                         for (p = 0, pa = tpsys->particles; p < tpsys->totpart; p++, pa++) {
591                                                 bpa = pa->boid;
592                                                 if (bpa->ground == ob)
593                                                         bpa->ground = NULL;
594                                         }
595                                 }
596                                 if (tpsys->part->boids) {
597                                         for (state = tpsys->part->boids->states.first; state; state = state->next) {
598                                                 for (rule = state->rules.first; rule; rule = rule->next) {
599                                                         if (rule->type == eBoidRuleType_Avoid) {
600                                                                 BoidRuleGoalAvoid *gabr = (BoidRuleGoalAvoid *)rule;
601                                                                 if (gabr->ob == ob)
602                                                                         gabr->ob = NULL;
603                                                         }
604                                                         else if (rule->type == eBoidRuleType_FollowLeader) {
605                                                                 BoidRuleFollowLeader *flbr = (BoidRuleFollowLeader *)rule;
606                                                                 if (flbr->ob == ob)
607                                                                         flbr->ob = NULL;
608                                                         }
609                                                 }
610                                         }
611                                 }
612                         }
613                         if (ob->pd)
614                                 DAG_id_tag_update(&obt->id, OB_RECALC_DATA);
615                 }
616
617                 obt = obt->id.next;
618         }
619         
620         /* materials */
621         mat = bmain->mat.first;
622         while (mat) {
623         
624                 for (a = 0; a < MAX_MTEX; a++) {
625                         if (mat->mtex[a] && ob == mat->mtex[a]->object) {
626                                 /* actually, test for lib here... to do */
627                                 mat->mtex[a]->object = NULL;
628                         }
629                 }
630
631                 mat = mat->id.next;
632         }
633         
634         /* textures */
635         for (tex = bmain->tex.first; tex; tex = tex->id.next) {
636                 if (tex->env && (ob == tex->env->object)) tex->env->object = NULL;
637                 if (tex->pd  && (ob == tex->pd->object)) tex->pd->object = NULL;
638                 if (tex->vd  && (ob == tex->vd->object)) tex->vd->object = NULL;
639         }
640
641         /* worlds */
642         wrld = bmain->world.first;
643         while (wrld) {
644                 if (wrld->id.lib == NULL) {
645                         for (a = 0; a < MAX_MTEX; a++) {
646                                 if (wrld->mtex[a] && ob == wrld->mtex[a]->object)
647                                         wrld->mtex[a]->object = NULL;
648                         }
649                 }
650                 
651                 wrld = wrld->id.next;
652         }
653                 
654         /* scenes */
655         sce = bmain->scene.first;
656         while (sce) {
657                 if (sce->id.lib == NULL) {
658                         if (sce->camera == ob) sce->camera = NULL;
659                         if (sce->toolsettings->skgen_template == ob) sce->toolsettings->skgen_template = NULL;
660                         if (sce->toolsettings->particle.object == ob) sce->toolsettings->particle.object = NULL;
661
662 #ifdef DURIAN_CAMERA_SWITCH
663                         {
664                                 TimeMarker *m;
665
666                                 for (m = sce->markers.first; m; m = m->next) {
667                                         if (m->camera == ob)
668                                                 m->camera = NULL;
669                                 }
670                         }
671 #endif
672                         if (sce->ed) {
673                                 Sequence *seq;
674                                 SEQ_BEGIN(sce->ed, seq)
675                                 {
676                                         if (seq->scene_camera == ob) {
677                                                 seq->scene_camera = NULL;
678                                         }
679                                 }
680                                 SEQ_END
681                         }
682
683 #ifdef WITH_FREESTYLE
684                         {
685                                 SceneRenderLayer *srl;
686
687                                 for (srl= sce->r.layers.first; srl; srl= srl->next) {
688                                         FRS_unlink_target_object(&srl->freestyleConfig, ob);
689                                 }
690                         }
691 #endif
692                 }
693
694                 sce = sce->id.next;
695         }
696         
697         /* screens */
698         sc = bmain->screen.first;
699         while (sc) {
700                 ScrArea *sa = sc->areabase.first;
701                 while (sa) {
702                         SpaceLink *sl;
703
704                         for (sl = sa->spacedata.first; sl; sl = sl->next) {
705                                 if (sl->spacetype == SPACE_VIEW3D) {
706                                         View3D *v3d = (View3D *) sl;
707
708                                         /* found doesn't need to be set here */
709                                         if (v3d->ob_centre == ob) {
710                                                 v3d->ob_centre = NULL;
711                                                 v3d->ob_centre_bone[0] = '\0';
712                                         }
713                                         if (v3d->localvd && v3d->localvd->ob_centre == ob) {
714                                                 v3d->localvd->ob_centre = NULL;
715                                                 v3d->localvd->ob_centre_bone[0] = '\0';
716                                         }
717
718                                         found = 0;
719                                         if (v3d->camera == ob) {
720                                                 v3d->camera = NULL;
721                                                 found = 1;
722                                         }
723                                         if (v3d->localvd && v3d->localvd->camera == ob) {
724                                                 v3d->localvd->camera = NULL;
725                                                 found += 2;
726                                         }
727
728                                         if (found) {
729                                                 if (sa->spacetype == SPACE_VIEW3D) {
730                                                         for (ar = sa->regionbase.first; ar; ar = ar->next) {
731                                                                 if (ar->regiontype == RGN_TYPE_WINDOW) {
732                                                                         rv3d = (RegionView3D *)ar->regiondata;
733                                                                         if (found == 1 || found == 3) {
734                                                                                 if (rv3d->persp == RV3D_CAMOB)
735                                                                                         rv3d->persp = RV3D_PERSP;
736                                                                         }
737                                                                         if (found == 2 || found == 3) {
738                                                                                 if (rv3d->localvd && rv3d->localvd->persp == RV3D_CAMOB)
739                                                                                         rv3d->localvd->persp = RV3D_PERSP;
740                                                                         }
741                                                                 }
742                                                         }
743                                                 }
744                                         }
745                                 }
746                                 else if (sl->spacetype == SPACE_OUTLINER) {
747                                         SpaceOops *so = (SpaceOops *)sl;
748
749                                         if (so->treestore) {
750                                                 TreeStoreElem *tselem = so->treestore->data;
751                                                 int i;
752                                                 for (i = 0; i < so->treestore->usedelem; i++, tselem++) {
753                                                         if (tselem->id == (ID *)ob) tselem->id = NULL;
754                                                 }
755                                         }
756                                 }
757                                 else if (sl->spacetype == SPACE_BUTS) {
758                                         SpaceButs *sbuts = (SpaceButs *)sl;
759
760                                         if (sbuts->pinid == (ID *)ob) {
761                                                 sbuts->flag &= ~SB_PIN_CONTEXT;
762                                                 sbuts->pinid = NULL;
763                                         }
764                                 }
765                         }
766
767                         sa = sa->next;
768                 }
769                 sc = sc->id.next;
770         }
771
772         /* groups */
773         group = bmain->group.first;
774         while (group) {
775                 rem_from_group(group, ob, NULL, NULL);
776                 group = group->id.next;
777         }
778         
779         /* cameras */
780         camera = bmain->camera.first;
781         while (camera) {
782                 if (camera->dof_ob == ob) {
783                         camera->dof_ob = NULL;
784                 }
785                 camera = camera->id.next;
786         }
787 }
788
789 /* actual check for internal data, not context or flags */
790 bool BKE_object_is_in_editmode(Object *ob)
791 {
792         if (ob->data == NULL)
793                 return false;
794         
795         if (ob->type == OB_MESH) {
796                 Mesh *me = ob->data;
797                 if (me->edit_btmesh)
798                         return true;
799         }
800         else if (ob->type == OB_ARMATURE) {
801                 bArmature *arm = ob->data;
802                 
803                 if (arm->edbo)
804                         return true;
805         }
806         else if (ob->type == OB_FONT) {
807                 Curve *cu = ob->data;
808                 
809                 if (cu->editfont)
810                         return true;
811         }
812         else if (ob->type == OB_MBALL) {
813                 MetaBall *mb = ob->data;
814                 
815                 if (mb->editelems)
816                         return true;
817         }
818         else if (ob->type == OB_LATTICE) {
819                 Lattice *lt = ob->data;
820                 
821                 if (lt->editlatt)
822                         return true;
823         }
824         else if (ob->type == OB_SURF || ob->type == OB_CURVE) {
825                 Curve *cu = ob->data;
826
827                 if (cu->editnurb)
828                         return true;
829         }
830         return false;
831 }
832
833 bool BKE_object_exists_check(Object *obtest)
834 {
835         Object *ob;
836         
837         if (obtest == NULL) return false;
838         
839         ob = G.main->object.first;
840         while (ob) {
841                 if (ob == obtest) return true;
842                 ob = ob->id.next;
843         }
844         return false;
845 }
846
847 /* *************************************************** */
848
849 void *BKE_object_obdata_add_from_type(int type)
850 {
851         switch (type) {
852                 case OB_MESH:      return BKE_mesh_add(G.main, "Mesh");
853                 case OB_CURVE:     return BKE_curve_add(G.main, "Curve", OB_CURVE);
854                 case OB_SURF:      return BKE_curve_add(G.main, "Surf", OB_SURF);
855                 case OB_FONT:      return BKE_curve_add(G.main, "Text", OB_FONT);
856                 case OB_MBALL:     return BKE_mball_add(G.main, "Meta");
857                 case OB_CAMERA:    return BKE_camera_add(G.main, "Camera");
858                 case OB_LAMP:      return BKE_lamp_add(G.main, "Lamp");
859                 case OB_LATTICE:   return BKE_lattice_add(G.main, "Lattice");
860                 case OB_ARMATURE:  return BKE_armature_add(G.main, "Armature");
861                 case OB_SPEAKER:   return BKE_speaker_add(G.main, "Speaker");
862                 case OB_EMPTY:     return NULL;
863                 default:
864                         printf("BKE_object_obdata_add_from_type: Internal error, bad type: %d\n", type);
865                         return NULL;
866         }
867 }
868
869 static const char *get_obdata_defname(int type)
870 {
871         switch (type) {
872                 case OB_MESH: return "Mesh";
873                 case OB_CURVE: return "Curve";
874                 case OB_SURF: return "Surf";
875                 case OB_FONT: return "Text";
876                 case OB_MBALL: return "Mball";
877                 case OB_CAMERA: return "Camera";
878                 case OB_LAMP: return "Lamp";
879                 case OB_LATTICE: return "Lattice";
880                 case OB_ARMATURE: return "Armature";
881                 case OB_SPEAKER: return "Speaker";
882                 case OB_EMPTY: return "Empty";
883                 default:
884                         printf("get_obdata_defname: Internal error, bad type: %d\n", type);
885                         return "Empty";
886         }
887 }
888
889 /* more general add: creates minimum required data, but without vertices etc. */
890 Object *BKE_object_add_only_object(Main *bmain, int type, const char *name)
891 {
892         Object *ob;
893
894         if (!name)
895                 name = get_obdata_defname(type);
896
897         ob = BKE_libblock_alloc(&bmain->object, ID_OB, name);
898
899         /* default object vars */
900         ob->type = type;
901         
902         ob->col[0] = ob->col[1] = ob->col[2] = 1.0;
903         ob->col[3] = 1.0;
904         
905         ob->size[0] = ob->size[1] = ob->size[2] = 1.0;
906         ob->dscale[0] = ob->dscale[1] = ob->dscale[2] = 1.0;
907         
908         /* objects should default to having Euler XYZ rotations, 
909          * but rotations default to quaternions 
910          */
911         ob->rotmode = ROT_MODE_EUL;
912
913         unit_axis_angle(ob->rotAxis, &ob->rotAngle);
914         unit_axis_angle(ob->drotAxis, &ob->drotAngle);
915
916         unit_qt(ob->quat);
917         unit_qt(ob->dquat);
918
919         /* rotation locks should be 4D for 4 component rotations by default... */
920         ob->protectflag = OB_LOCK_ROT4D;
921         
922         unit_m4(ob->constinv);
923         unit_m4(ob->parentinv);
924         unit_m4(ob->obmat);
925         ob->dt = OB_TEXTURE;
926         ob->empty_drawtype = OB_PLAINAXES;
927         ob->empty_drawsize = 1.0;
928
929         if (type == OB_CAMERA || type == OB_LAMP || type == OB_SPEAKER) {
930                 ob->trackflag = OB_NEGZ;
931                 ob->upflag = OB_POSY;
932         }
933         else {
934                 ob->trackflag = OB_POSY;
935                 ob->upflag = OB_POSZ;
936         }
937         
938         ob->dupon = 1; ob->dupoff = 0;
939         ob->dupsta = 1; ob->dupend = 100;
940         ob->dupfacesca = 1.0;
941
942         /* Game engine defaults*/
943         ob->mass = ob->inertia = 1.0f;
944         ob->formfactor = 0.4f;
945         ob->damping = 0.04f;
946         ob->rdamping = 0.1f;
947         ob->anisotropicFriction[0] = 1.0f;
948         ob->anisotropicFriction[1] = 1.0f;
949         ob->anisotropicFriction[2] = 1.0f;
950         ob->gameflag = OB_PROP | OB_COLLISION;
951         ob->margin = 0.0;
952         ob->init_state = 1;
953         ob->state = 1;
954         /* ob->pad3 == Contact Processing Threshold */
955         ob->m_contactProcessingThreshold = 1.0f;
956         ob->obstacleRad = 1.0f;
957         ob->step_height = 0.15f;
958         ob->jump_speed = 10.0f;
959         ob->fall_speed = 55.0f;
960         ob->col_group = 0x01;
961         ob->col_mask = 0xff;
962
963         /* NT fluid sim defaults */
964         ob->fluidsimSettings = NULL;
965
966         ob->pc_ids.first = ob->pc_ids.last = NULL;
967         
968         /* Animation Visualization defaults */
969         animviz_settings_init(&ob->avs);
970
971         return ob;
972 }
973
974 /* general add: to scene, with layer from area and default name */
975 /* creates minimum required data, but without vertices etc. */
976 Object *BKE_object_add(struct Scene *scene, int type)
977 {
978         Object *ob;
979         Base *base;
980         char name[MAX_ID_NAME];
981
982         BLI_strncpy(name, get_obdata_defname(type), sizeof(name));
983         ob = BKE_object_add_only_object(G.main, type, name);
984
985         ob->data = BKE_object_obdata_add_from_type(type);
986
987         ob->lay = scene->lay;
988         
989         base = BKE_scene_base_add(scene, ob);
990         BKE_scene_base_deselect_all(scene);
991         BKE_scene_base_select(scene, base);
992         DAG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
993
994         return ob;
995 }
996
997 SoftBody *copy_softbody(SoftBody *sb, int copy_caches)
998 {
999         SoftBody *sbn;
1000         
1001         if (sb == NULL) return(NULL);
1002         
1003         sbn = MEM_dupallocN(sb);
1004
1005         if (copy_caches == FALSE) {
1006                 sbn->totspring = sbn->totpoint = 0;
1007                 sbn->bpoint = NULL;
1008                 sbn->bspring = NULL;
1009         }
1010         else {
1011                 sbn->totspring = sb->totspring;
1012                 sbn->totpoint = sb->totpoint;
1013
1014                 if (sbn->bpoint) {
1015                         int i;
1016
1017                         sbn->bpoint = MEM_dupallocN(sbn->bpoint);
1018
1019                         for (i = 0; i < sbn->totpoint; i++) {
1020                                 if (sbn->bpoint[i].springs)
1021                                         sbn->bpoint[i].springs = MEM_dupallocN(sbn->bpoint[i].springs);
1022                         }
1023                 }
1024
1025                 if (sb->bspring)
1026                         sbn->bspring = MEM_dupallocN(sb->bspring);
1027         }
1028         
1029         sbn->keys = NULL;
1030         sbn->totkey = sbn->totpointkey = 0;
1031         
1032         sbn->scratch = NULL;
1033
1034         sbn->pointcache = BKE_ptcache_copy_list(&sbn->ptcaches, &sb->ptcaches, copy_caches);
1035
1036         if (sb->effector_weights)
1037                 sbn->effector_weights = MEM_dupallocN(sb->effector_weights);
1038
1039         return sbn;
1040 }
1041
1042 BulletSoftBody *copy_bulletsoftbody(BulletSoftBody *bsb)
1043 {
1044         BulletSoftBody *bsbn;
1045
1046         if (bsb == NULL)
1047                 return NULL;
1048         bsbn = MEM_dupallocN(bsb);
1049         /* no pointer in this structure yet */
1050         return bsbn;
1051 }
1052
1053 static ParticleSystem *copy_particlesystem(ParticleSystem *psys)
1054 {
1055         ParticleSystem *psysn;
1056         ParticleData *pa;
1057         int p;
1058
1059         psysn = MEM_dupallocN(psys);
1060         psysn->particles = MEM_dupallocN(psys->particles);
1061         psysn->child = MEM_dupallocN(psys->child);
1062
1063         if (psys->part->type == PART_HAIR) {
1064                 for (p = 0, pa = psysn->particles; p < psysn->totpart; p++, pa++)
1065                         pa->hair = MEM_dupallocN(pa->hair);
1066         }
1067
1068         if (psysn->particles && (psysn->particles->keys || psysn->particles->boid)) {
1069                 ParticleKey *key = psysn->particles->keys;
1070                 BoidParticle *boid = psysn->particles->boid;
1071
1072                 if (key)
1073                         key = MEM_dupallocN(key);
1074                 
1075                 if (boid)
1076                         boid = MEM_dupallocN(boid);
1077                 
1078                 for (p = 0, pa = psysn->particles; p < psysn->totpart; p++, pa++) {
1079                         if (boid)
1080                                 pa->boid = boid++;
1081                         if (key) {
1082                                 pa->keys = key;
1083                                 key += pa->totkey;
1084                         }
1085                 }
1086         }
1087
1088         if (psys->clmd) {
1089                 psysn->clmd = (ClothModifierData *)modifier_new(eModifierType_Cloth);
1090                 modifier_copyData((ModifierData *)psys->clmd, (ModifierData *)psysn->clmd);
1091                 psys->hair_in_dm = psys->hair_out_dm = NULL;
1092         }
1093
1094         BLI_duplicatelist(&psysn->targets, &psys->targets);
1095
1096         psysn->pathcache = NULL;
1097         psysn->childcache = NULL;
1098         psysn->edit = NULL;
1099         psysn->frand = NULL;
1100         psysn->pdd = NULL;
1101         psysn->effectors = NULL;
1102         
1103         psysn->pathcachebufs.first = psysn->pathcachebufs.last = NULL;
1104         psysn->childcachebufs.first = psysn->childcachebufs.last = NULL;
1105         psysn->renderdata = NULL;
1106         
1107         psysn->pointcache = BKE_ptcache_copy_list(&psysn->ptcaches, &psys->ptcaches, FALSE);
1108
1109         /* XXX - from reading existing code this seems correct but intended usage of
1110          * pointcache should /w cloth should be added in 'ParticleSystem' - campbell */
1111         if (psysn->clmd) {
1112                 psysn->clmd->point_cache = psysn->pointcache;
1113         }
1114
1115         id_us_plus((ID *)psysn->part);
1116
1117         return psysn;
1118 }
1119
1120 void BKE_object_copy_particlesystems(Object *obn, Object *ob)
1121 {
1122         ParticleSystem *psys, *npsys;
1123         ModifierData *md;
1124
1125         if (obn->type != OB_MESH) {
1126                 /* currently only mesh objects can have soft body */
1127                 return;
1128         }
1129
1130         obn->particlesystem.first = obn->particlesystem.last = NULL;
1131         for (psys = ob->particlesystem.first; psys; psys = psys->next) {
1132                 npsys = copy_particlesystem(psys);
1133
1134                 BLI_addtail(&obn->particlesystem, npsys);
1135
1136                 /* need to update particle modifiers too */
1137                 for (md = obn->modifiers.first; md; md = md->next) {
1138                         if (md->type == eModifierType_ParticleSystem) {
1139                                 ParticleSystemModifierData *psmd = (ParticleSystemModifierData *)md;
1140                                 if (psmd->psys == psys)
1141                                         psmd->psys = npsys;
1142                         }
1143                         else if (md->type == eModifierType_DynamicPaint) {
1144                                 DynamicPaintModifierData *pmd = (DynamicPaintModifierData *)md;
1145                                 if (pmd->brush) {
1146                                         if (pmd->brush->psys == psys) {
1147                                                 pmd->brush->psys = npsys;
1148                                         }
1149                                 }
1150                         }
1151                         else if (md->type == eModifierType_Smoke) {
1152                                 SmokeModifierData *smd = (SmokeModifierData *) md;
1153                                 
1154                                 if (smd->type == MOD_SMOKE_TYPE_FLOW) {
1155                                         if (smd->flow) {
1156                                                 if (smd->flow->psys == psys)
1157                                                         smd->flow->psys = npsys;
1158                                         }
1159                                 }
1160                         }
1161                 }
1162         }
1163 }
1164
1165 void BKE_object_copy_softbody(Object *obn, Object *ob)
1166 {
1167         if (ob->soft)
1168                 obn->soft = copy_softbody(ob->soft, FALSE);
1169 }
1170
1171 static void copy_object_pose(Object *obn, Object *ob)
1172 {
1173         bPoseChannel *chan;
1174         
1175         /* note: need to clear obn->pose pointer first, so that BKE_pose_copy_data works (otherwise there's a crash) */
1176         obn->pose = NULL;
1177         BKE_pose_copy_data(&obn->pose, ob->pose, 1);    /* 1 = copy constraints */
1178
1179         for (chan = obn->pose->chanbase.first; chan; chan = chan->next) {
1180                 bConstraint *con;
1181                 
1182                 chan->flag &= ~(POSE_LOC | POSE_ROT | POSE_SIZE);
1183                 
1184                 if (chan->custom) {
1185                         id_us_plus(&chan->custom->id);
1186                 }
1187                 
1188                 for (con = chan->constraints.first; con; con = con->next) {
1189                         bConstraintTypeInfo *cti = BKE_constraint_get_typeinfo(con);
1190                         ListBase targets = {NULL, NULL};
1191                         bConstraintTarget *ct;
1192                         
1193                         if (cti && cti->get_constraint_targets) {
1194                                 cti->get_constraint_targets(con, &targets);
1195                                 
1196                                 for (ct = targets.first; ct; ct = ct->next) {
1197                                         if (ct->tar == ob)
1198                                                 ct->tar = obn;
1199                                 }
1200                                 
1201                                 if (cti->flush_constraint_targets)
1202                                         cti->flush_constraint_targets(con, &targets, 0);
1203                         }
1204                 }
1205         }
1206 }
1207
1208 int BKE_object_pose_context_check(Object *ob)
1209 {
1210         if ((ob) &&
1211             (ob->type == OB_ARMATURE) &&
1212             (ob->pose) &&
1213             (ob->mode & OB_MODE_POSE))
1214         {
1215                 return 1;
1216         }
1217         else {
1218                 return 0;
1219         }
1220 }
1221
1222 Object *BKE_object_pose_armature_get(Object *ob)
1223 {
1224         if (ob == NULL)
1225                 return NULL;
1226
1227         if (BKE_object_pose_context_check(ob))
1228                 return ob;
1229
1230         ob = modifiers_isDeformedByArmature(ob);
1231
1232         if (BKE_object_pose_context_check(ob))
1233                 return ob;
1234
1235         return NULL;
1236 }
1237
1238 void BKE_object_transform_copy(Object *ob_tar, const Object *ob_src)
1239 {
1240         copy_v3_v3(ob_tar->loc, ob_src->loc);
1241         copy_v3_v3(ob_tar->rot, ob_src->rot);
1242         copy_v3_v3(ob_tar->quat, ob_src->quat);
1243         copy_v3_v3(ob_tar->rotAxis, ob_src->rotAxis);
1244         ob_tar->rotAngle = ob_src->rotAngle;
1245         ob_tar->rotmode = ob_src->rotmode;
1246         copy_v3_v3(ob_tar->size, ob_src->size);
1247 }
1248
1249 Object *BKE_object_copy_ex(Main *bmain, Object *ob, int copy_caches)
1250 {
1251         Object *obn;
1252         ModifierData *md;
1253         int a;
1254
1255         obn = BKE_libblock_copy_ex(bmain, &ob->id);
1256         
1257         if (ob->totcol) {
1258                 obn->mat = MEM_dupallocN(ob->mat);
1259                 obn->matbits = MEM_dupallocN(ob->matbits);
1260                 obn->totcol = ob->totcol;
1261         }
1262         
1263         if (ob->bb) obn->bb = MEM_dupallocN(ob->bb);
1264         obn->flag &= ~OB_FROMGROUP;
1265         
1266         obn->modifiers.first = obn->modifiers.last = NULL;
1267         
1268         for (md = ob->modifiers.first; md; md = md->next) {
1269                 ModifierData *nmd = modifier_new(md->type);
1270                 BLI_strncpy(nmd->name, md->name, sizeof(nmd->name));
1271                 modifier_copyData(md, nmd);
1272                 BLI_addtail(&obn->modifiers, nmd);
1273         }
1274
1275         obn->prop.first = obn->prop.last = NULL;
1276         BKE_bproperty_copy_list(&obn->prop, &ob->prop);
1277         
1278         copy_sensors(&obn->sensors, &ob->sensors);
1279         copy_controllers(&obn->controllers, &ob->controllers);
1280         copy_actuators(&obn->actuators, &ob->actuators);
1281         
1282         if (ob->pose) {
1283                 copy_object_pose(obn, ob);
1284                 /* backwards compat... non-armatures can get poses in older files? */
1285                 if (ob->type == OB_ARMATURE)
1286                         BKE_pose_rebuild(obn, obn->data);
1287         }
1288         defgroup_copy_list(&obn->defbase, &ob->defbase);
1289         BKE_copy_constraints(&obn->constraints, &ob->constraints, TRUE);
1290
1291         obn->mode = 0;
1292         obn->sculpt = NULL;
1293
1294         /* increase user numbers */
1295         id_us_plus((ID *)obn->data);
1296         id_us_plus((ID *)obn->gpd);
1297         id_lib_extern((ID *)obn->dup_group);
1298
1299         for (a = 0; a < obn->totcol; a++) id_us_plus((ID *)obn->mat[a]);
1300         
1301         obn->disp.first = obn->disp.last = NULL;
1302         
1303         if (ob->pd) {
1304                 obn->pd = MEM_dupallocN(ob->pd);
1305                 if (obn->pd->tex)
1306                         id_us_plus(&(obn->pd->tex->id));
1307                 if (obn->pd->rng)
1308                         obn->pd->rng = MEM_dupallocN(ob->pd->rng);
1309         }
1310         obn->soft = copy_softbody(ob->soft, copy_caches);
1311         obn->bsoft = copy_bulletsoftbody(ob->bsoft);
1312         obn->rigidbody_object = BKE_rigidbody_copy_object(ob);
1313         obn->rigidbody_constraint = BKE_rigidbody_copy_constraint(ob);
1314
1315         BKE_object_copy_particlesystems(obn, ob);
1316         
1317         obn->derivedDeform = NULL;
1318         obn->derivedFinal = NULL;
1319
1320         obn->gpulamp.first = obn->gpulamp.last = NULL;
1321         obn->pc_ids.first = obn->pc_ids.last = NULL;
1322
1323         obn->mpath = NULL;
1324         
1325         return obn;
1326 }
1327
1328 /* copy objects, will re-initialize cached simulation data */
1329 Object *BKE_object_copy(Object *ob)
1330 {
1331         return BKE_object_copy_ex(G.main, ob, FALSE);
1332 }
1333
1334 static void extern_local_object(Object *ob)
1335 {
1336         ParticleSystem *psys;
1337
1338         id_lib_extern((ID *)ob->data);
1339         id_lib_extern((ID *)ob->dup_group);
1340         id_lib_extern((ID *)ob->poselib);
1341         id_lib_extern((ID *)ob->gpd);
1342
1343         extern_local_matarar(ob->mat, ob->totcol);
1344
1345         for (psys = ob->particlesystem.first; psys; psys = psys->next)
1346                 id_lib_extern((ID *)psys->part);
1347 }
1348
1349 void BKE_object_make_local(Object *ob)
1350 {
1351         Main *bmain = G.main;
1352         Scene *sce;
1353         Base *base;
1354         int is_local = FALSE, is_lib = FALSE;
1355
1356         /* - only lib users: do nothing
1357          * - only local users: set flag
1358          * - mixed: make copy
1359          */
1360
1361         if (ob->id.lib == NULL) return;
1362         
1363         ob->proxy = ob->proxy_from = NULL;
1364         
1365         if (ob->id.us == 1) {
1366                 id_clear_lib_data(bmain, &ob->id);
1367                 extern_local_object(ob);
1368         }
1369         else {
1370                 for (sce = bmain->scene.first; sce && ELEM(0, is_lib, is_local); sce = sce->id.next) {
1371                         if (BKE_scene_base_find(sce, ob)) {
1372                                 if (sce->id.lib) is_lib = TRUE;
1373                                 else is_local = TRUE;
1374                         }
1375                 }
1376
1377                 if (is_local && is_lib == FALSE) {
1378                         id_clear_lib_data(bmain, &ob->id);
1379                         extern_local_object(ob);
1380                 }
1381                 else if (is_local && is_lib) {
1382                         Object *ob_new = BKE_object_copy(ob);
1383
1384                         ob_new->id.us = 0;
1385                         
1386                         /* Remap paths of new ID using old library as base. */
1387                         BKE_id_lib_local_paths(bmain, ob->id.lib, &ob_new->id);
1388
1389                         sce = bmain->scene.first;
1390                         while (sce) {
1391                                 if (sce->id.lib == NULL) {
1392                                         base = sce->base.first;
1393                                         while (base) {
1394                                                 if (base->object == ob) {
1395                                                         base->object = ob_new;
1396                                                         ob_new->id.us++;
1397                                                         ob->id.us--;
1398                                                 }
1399                                                 base = base->next;
1400                                         }
1401                                 }
1402                                 sce = sce->id.next;
1403                         }
1404                 }
1405         }
1406 }
1407
1408 /*
1409  * Returns true if the Object is a from an external blend file (libdata)
1410  */
1411 bool BKE_object_is_libdata(Object *ob)
1412 {
1413         if (!ob) return false;
1414         if (ob->proxy) return false;
1415         if (ob->id.lib) return true;
1416         return false;
1417 }
1418
1419 /* Returns true if the Object data is a from an external blend file (libdata) */
1420 bool BKE_object_obdata_is_libdata(Object *ob)
1421 {
1422         if (!ob) return false;
1423         if (ob->proxy && (ob->data == NULL || ((ID *)ob->data)->lib == NULL)) return false;
1424         if (ob->id.lib) return true;
1425         if (ob->data == NULL) return false;
1426         if (((ID *)ob->data)->lib) return true;
1427
1428         return false;
1429 }
1430
1431 /* *************** PROXY **************** */
1432
1433 /* when you make proxy, ensure the exposed layers are extern */
1434 static void armature_set_id_extern(Object *ob)
1435 {
1436         bArmature *arm = ob->data;
1437         bPoseChannel *pchan;
1438         unsigned int lay = arm->layer_protected;
1439         
1440         for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
1441                 if (!(pchan->bone->layer & lay))
1442                         id_lib_extern((ID *)pchan->custom);
1443         }
1444                         
1445 }
1446
1447 void BKE_object_copy_proxy_drivers(Object *ob, Object *target)
1448 {
1449         if ((target->adt) && (target->adt->drivers.first)) {
1450                 FCurve *fcu;
1451                 
1452                 /* add new animdata block */
1453                 if (!ob->adt)
1454                         ob->adt = BKE_id_add_animdata(&ob->id);
1455                 
1456                 /* make a copy of all the drivers (for now), then correct any links that need fixing */
1457                 free_fcurves(&ob->adt->drivers);
1458                 copy_fcurves(&ob->adt->drivers, &target->adt->drivers);
1459                 
1460                 for (fcu = ob->adt->drivers.first; fcu; fcu = fcu->next) {
1461                         ChannelDriver *driver = fcu->driver;
1462                         DriverVar *dvar;
1463                         
1464                         for (dvar = driver->variables.first; dvar; dvar = dvar->next) {
1465                                 /* all drivers */
1466                                 DRIVER_TARGETS_LOOPER(dvar) 
1467                                 {
1468                                         if (dtar->id) {
1469                                                 if ((Object *)dtar->id == target)
1470                                                         dtar->id = (ID *)ob;
1471                                                 else {
1472                                                         /* only on local objects because this causes indirect links
1473                                                          * 'a -> b -> c', blend to point directly to a.blend
1474                                                          * when a.blend has a proxy thats linked into c.blend  */
1475                                                         if (ob->id.lib == NULL)
1476                                                                 id_lib_extern((ID *)dtar->id);
1477                                                 }
1478                                         }
1479                                 }
1480                                 DRIVER_TARGETS_LOOPER_END
1481                         }
1482                 }
1483         }
1484 }
1485
1486 /* proxy rule: lib_object->proxy_from == the one we borrow from, set temporally while object_update */
1487 /*             local_object->proxy == pointer to library object, saved in files and read */
1488 /*             local_object->proxy_group == pointer to group dupli-object, saved in files and read */
1489
1490 void BKE_object_make_proxy(Object *ob, Object *target, Object *gob)
1491 {
1492         /* paranoia checks */
1493         if (ob->id.lib || target->id.lib == NULL) {
1494                 printf("cannot make proxy\n");
1495                 return;
1496         }
1497         
1498         ob->proxy = target;
1499         ob->proxy_group = gob;
1500         id_lib_extern(&target->id);
1501         
1502         DAG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
1503         DAG_id_tag_update(&target->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
1504         
1505         /* copy transform
1506          * - gob means this proxy comes from a group, just apply the matrix
1507          *   so the object wont move from its dupli-transform.
1508          *
1509          * - no gob means this is being made from a linked object,
1510          *   this is closer to making a copy of the object - in-place. */
1511         if (gob) {
1512                 ob->rotmode = target->rotmode;
1513                 mult_m4_m4m4(ob->obmat, gob->obmat, target->obmat);
1514                 if (gob->dup_group) { /* should always be true */
1515                         float tvec[3];
1516                         copy_v3_v3(tvec, gob->dup_group->dupli_ofs);
1517                         mul_mat3_m4_v3(ob->obmat, tvec);
1518                         sub_v3_v3(ob->obmat[3], tvec);
1519                 }
1520                 BKE_object_apply_mat4(ob, ob->obmat, FALSE, TRUE);
1521         }
1522         else {
1523                 BKE_object_transform_copy(ob, target);
1524                 ob->parent = target->parent; /* libdata */
1525                 copy_m4_m4(ob->parentinv, target->parentinv);
1526         }
1527         
1528         /* copy animdata stuff - drivers only for now... */
1529         BKE_object_copy_proxy_drivers(ob, target);
1530
1531         /* skip constraints? */
1532         /* FIXME: this is considered by many as a bug */
1533         
1534         /* set object type and link to data */
1535         ob->type = target->type;
1536         ob->data = target->data;
1537         id_us_plus((ID *)ob->data);     /* ensures lib data becomes LIB_EXTERN */
1538         
1539         /* copy material and index information */
1540         ob->actcol = ob->totcol = 0;
1541         if (ob->mat) MEM_freeN(ob->mat);
1542         if (ob->matbits) MEM_freeN(ob->matbits);
1543         ob->mat = NULL;
1544         ob->matbits = NULL;
1545         if ((target->totcol) && (target->mat) && OB_TYPE_SUPPORT_MATERIAL(ob->type)) {
1546                 int i;
1547                 
1548                 ob->actcol = target->actcol;
1549                 ob->totcol = target->totcol;
1550                 
1551                 ob->mat = MEM_dupallocN(target->mat);
1552                 ob->matbits = MEM_dupallocN(target->matbits);
1553                 for (i = 0; i < target->totcol; i++) {
1554                         /* don't need to run test_object_materials since we know this object is new and not used elsewhere */
1555                         id_us_plus((ID *)ob->mat[i]); 
1556                 }
1557         }
1558         
1559         /* type conversions */
1560         if (target->type == OB_ARMATURE) {
1561                 copy_object_pose(ob, target);   /* data copy, object pointers in constraints */
1562                 BKE_pose_rest(ob->pose);            /* clear all transforms in channels */
1563                 BKE_pose_rebuild(ob, ob->data); /* set all internal links */
1564                 
1565                 armature_set_id_extern(ob);
1566         }
1567         else if (target->type == OB_EMPTY) {
1568                 ob->empty_drawtype = target->empty_drawtype;
1569                 ob->empty_drawsize = target->empty_drawsize;
1570         }
1571
1572         /* copy IDProperties */
1573         if (ob->id.properties) {
1574                 IDP_FreeProperty(ob->id.properties);
1575                 MEM_freeN(ob->id.properties);
1576                 ob->id.properties = NULL;
1577         }
1578         if (target->id.properties) {
1579                 ob->id.properties = IDP_CopyProperty(target->id.properties);
1580         }
1581
1582         /* copy drawtype info */
1583         ob->dt = target->dt;
1584 }
1585
1586
1587 /* *************** CALC ****************** */
1588
1589 void BKE_object_scale_to_mat3(Object *ob, float mat[3][3])
1590 {
1591         float vec[3];
1592         mul_v3_v3v3(vec, ob->size, ob->dscale);
1593         size_to_mat3(mat, vec);
1594 }
1595
1596 void BKE_object_rot_to_mat3(Object *ob, float mat[3][3], short use_drot)
1597 {
1598         float rmat[3][3], dmat[3][3];
1599         
1600         /* 'dmat' is the delta-rotation matrix, which will get (pre)multiplied
1601          * with the rotation matrix to yield the appropriate rotation
1602          */
1603
1604         /* rotations may either be quats, eulers (with various rotation orders), or axis-angle */
1605         if (ob->rotmode > 0) {
1606                 /* euler rotations (will cause gimble lock, but this can be alleviated a bit with rotation orders) */
1607                 eulO_to_mat3(rmat, ob->rot, ob->rotmode);
1608                 eulO_to_mat3(dmat, ob->drot, ob->rotmode);
1609         }
1610         else if (ob->rotmode == ROT_MODE_AXISANGLE) {
1611                 /* axis-angle - not really that great for 3D-changing orientations */
1612                 axis_angle_to_mat3(rmat, ob->rotAxis, ob->rotAngle);
1613                 axis_angle_to_mat3(dmat, ob->drotAxis, ob->drotAngle);
1614         }
1615         else {
1616                 /* quats are normalized before use to eliminate scaling issues */
1617                 float tquat[4];
1618                 
1619                 normalize_qt_qt(tquat, ob->quat);
1620                 quat_to_mat3(rmat, tquat);
1621                 
1622                 normalize_qt_qt(tquat, ob->dquat);
1623                 quat_to_mat3(dmat, tquat);
1624         }
1625         
1626         /* combine these rotations */
1627         if (use_drot)
1628                 mul_m3_m3m3(mat, dmat, rmat);
1629         else
1630                 copy_m3_m3(mat, rmat);
1631 }
1632
1633 void BKE_object_mat3_to_rot(Object *ob, float mat[3][3], short use_compat)
1634 {
1635         switch (ob->rotmode) {
1636                 case ROT_MODE_QUAT:
1637                 {
1638                         float dquat[4];
1639                         mat3_to_quat(ob->quat, mat);
1640                         normalize_qt_qt(dquat, ob->dquat);
1641                         invert_qt(dquat);
1642                         mul_qt_qtqt(ob->quat, dquat, ob->quat);
1643                 }
1644                 break;
1645                 case ROT_MODE_AXISANGLE:
1646                         mat3_to_axis_angle(ob->rotAxis, &ob->rotAngle, mat);
1647                         sub_v3_v3(ob->rotAxis, ob->drotAxis);
1648                         ob->rotAngle -= ob->drotAngle;
1649                         break;
1650                 default: /* euler */
1651                 {
1652                         float quat[4];
1653                         float dquat[4];
1654                         float tmat[3][3];
1655
1656                         /* without drot we could apply 'mat' directly */
1657                         mat3_to_quat(quat, mat);
1658                         eulO_to_quat(dquat, ob->drot, ob->rotmode);
1659                         invert_qt(dquat);
1660                         mul_qt_qtqt(quat, dquat, quat);
1661                         quat_to_mat3(tmat, quat);
1662                         /* end drot correction */
1663
1664                         if (use_compat) mat3_to_compatible_eulO(ob->rot, ob->rot, ob->rotmode, tmat);
1665                         else            mat3_to_eulO(ob->rot, ob->rotmode, tmat);
1666                 }
1667         }
1668 }
1669
1670 void BKE_object_tfm_protected_backup(const Object *ob,
1671                                      ObjectTfmProtectedChannels *obtfm)
1672 {
1673
1674 #define TFMCPY(_v) (obtfm->_v = ob->_v)
1675 #define TFMCPY3D(_v) copy_v3_v3(obtfm->_v, ob->_v)
1676 #define TFMCPY4D(_v) copy_v4_v4(obtfm->_v, ob->_v)
1677
1678         TFMCPY3D(loc);
1679         TFMCPY3D(dloc);
1680         TFMCPY3D(size);
1681         TFMCPY3D(dscale);
1682         TFMCPY3D(rot);
1683         TFMCPY3D(drot);
1684         TFMCPY4D(quat);
1685         TFMCPY4D(dquat);
1686         TFMCPY3D(rotAxis);
1687         TFMCPY3D(drotAxis);
1688         TFMCPY(rotAngle);
1689         TFMCPY(drotAngle);
1690
1691 #undef TFMCPY
1692 #undef TFMCPY3D
1693 #undef TFMCPY4D
1694
1695 }
1696
1697 void BKE_object_tfm_protected_restore(Object *ob,
1698                                       const ObjectTfmProtectedChannels *obtfm,
1699                                       const short protectflag)
1700 {
1701         unsigned int i;
1702
1703         for (i = 0; i < 3; i++) {
1704                 if (protectflag & (OB_LOCK_LOCX << i)) {
1705                         ob->loc[i] =  obtfm->loc[i];
1706                         ob->dloc[i] = obtfm->dloc[i];
1707                 }
1708
1709                 if (protectflag & (OB_LOCK_SCALEX << i)) {
1710                         ob->size[i] =  obtfm->size[i];
1711                         ob->dscale[i] = obtfm->dscale[i];
1712                 }
1713
1714                 if (protectflag & (OB_LOCK_ROTX << i)) {
1715                         ob->rot[i] =  obtfm->rot[i];
1716                         ob->drot[i] = obtfm->drot[i];
1717
1718                         ob->quat[i + 1] =  obtfm->quat[i + 1];
1719                         ob->dquat[i + 1] = obtfm->dquat[i + 1];
1720
1721                         ob->rotAxis[i] =  obtfm->rotAxis[i];
1722                         ob->drotAxis[i] = obtfm->drotAxis[i];
1723                 }
1724         }
1725
1726         if ((protectflag & OB_LOCK_ROT4D) && (protectflag & OB_LOCK_ROTW)) {
1727                 ob->quat[0] =  obtfm->quat[0];
1728                 ob->dquat[0] = obtfm->dquat[0];
1729
1730                 ob->rotAngle =  obtfm->rotAngle;
1731                 ob->drotAngle = obtfm->drotAngle;
1732         }
1733 }
1734
1735 /* see BKE_pchan_apply_mat4() for the equivalent 'pchan' function */
1736 void BKE_object_apply_mat4(Object *ob, float mat[4][4], const short use_compat, const short use_parent)
1737 {
1738         float rot[3][3];
1739
1740         if (use_parent && ob->parent) {
1741                 float rmat[4][4], diff_mat[4][4], imat[4][4];
1742                 mult_m4_m4m4(diff_mat, ob->parent->obmat, ob->parentinv);
1743                 invert_m4_m4(imat, diff_mat);
1744                 mult_m4_m4m4(rmat, imat, mat); /* get the parent relative matrix */
1745                 BKE_object_apply_mat4(ob, rmat, use_compat, FALSE);
1746                 
1747                 /* same as below, use rmat rather than mat */
1748                 mat4_to_loc_rot_size(ob->loc, rot, ob->size, rmat);
1749                 BKE_object_mat3_to_rot(ob, rot, use_compat);
1750         }
1751         else {
1752                 mat4_to_loc_rot_size(ob->loc, rot, ob->size, mat);
1753                 BKE_object_mat3_to_rot(ob, rot, use_compat);
1754         }
1755         
1756         sub_v3_v3(ob->loc, ob->dloc);
1757
1758         if (ob->dscale[0] != 0.0f) ob->size[0] /= ob->dscale[0];
1759         if (ob->dscale[1] != 0.0f) ob->size[1] /= ob->dscale[1];
1760         if (ob->dscale[2] != 0.0f) ob->size[2] /= ob->dscale[2];
1761
1762         /* BKE_object_mat3_to_rot handles delta rotations */
1763 }
1764
1765 void BKE_object_to_mat3(Object *ob, float mat[3][3]) /* no parent */
1766 {
1767         float smat[3][3];
1768         float rmat[3][3];
1769         /*float q1[4];*/
1770         
1771         /* size */
1772         BKE_object_scale_to_mat3(ob, smat);
1773
1774         /* rot */
1775         BKE_object_rot_to_mat3(ob, rmat, TRUE);
1776         mul_m3_m3m3(mat, rmat, smat);
1777 }
1778
1779 void BKE_object_to_mat4(Object *ob, float mat[4][4])
1780 {
1781         float tmat[3][3];
1782         
1783         BKE_object_to_mat3(ob, tmat);
1784         
1785         copy_m4_m3(mat, tmat);
1786
1787         add_v3_v3v3(mat[3], ob->loc, ob->dloc);
1788 }
1789
1790 /* extern */
1791 int enable_cu_speed = 1;
1792
1793 static void ob_parcurve(Scene *scene, Object *ob, Object *par, float mat[4][4])
1794 {
1795         Curve *cu;
1796         float vec[4], dir[3], quat[4], radius, ctime;
1797         float timeoffs = 0.0, sf_orig = 0.0;
1798         
1799         unit_m4(mat);
1800         
1801         cu = par->data;
1802         if (cu->path == NULL || cu->path->data == NULL) /* only happens on reload file, but violates depsgraph still... fix! */
1803                 BKE_displist_make_curveTypes(scene, par, 0);
1804         if (cu->path == NULL) return;
1805         
1806         /* catch exceptions: feature for nla stride editing */
1807         if (ob->ipoflag & OB_DISABLE_PATH) {
1808                 ctime = 0.0f;
1809         }
1810         /* catch exceptions: curve paths used as a duplicator */
1811         else if (enable_cu_speed) {
1812                 /* ctime is now a proper var setting of Curve which gets set by Animato like any other var that's animated,
1813                  * but this will only work if it actually is animated... 
1814                  *
1815                  * we divide the curvetime calculated in the previous step by the length of the path, to get a time
1816                  * factor, which then gets clamped to lie within 0.0 - 1.0 range
1817                  */
1818                 if (IS_EQF(cu->pathlen, 0.0f) == 0)
1819                         ctime = cu->ctime / cu->pathlen;
1820                 else
1821                         ctime = cu->ctime;
1822
1823                 CLAMP(ctime, 0.0f, 1.0f);
1824         }
1825         else {
1826                 ctime = BKE_scene_frame_get(scene);
1827                 if (IS_EQF(cu->pathlen, 0.0f) == 0)
1828                         ctime /= cu->pathlen;
1829                 
1830                 CLAMP(ctime, 0.0f, 1.0f);
1831         }
1832         
1833         /* time calculus is correct, now apply distance offset */
1834         if (cu->flag & CU_OFFS_PATHDIST) {
1835                 ctime += timeoffs / cu->path->totdist;
1836
1837                 /* restore */
1838                 SWAP(float, sf_orig, ob->sf);
1839         }
1840         
1841         
1842         /* vec: 4 items! */
1843         if (where_on_path(par, ctime, vec, dir, cu->flag & CU_FOLLOW ? quat : NULL, &radius, NULL)) {
1844
1845                 if (cu->flag & CU_FOLLOW) {
1846 #if 0
1847                         float si, q[4];
1848                         vec_to_quat(quat, dir, ob->trackflag, ob->upflag);
1849                         
1850                         /* the tilt */
1851                         normalize_v3(dir);
1852                         q[0] = (float)cos(0.5 * vec[3]);
1853                         si = (float)sin(0.5 * vec[3]);
1854                         q[1] = -si * dir[0];
1855                         q[2] = -si * dir[1];
1856                         q[3] = -si * dir[2];
1857                         mul_qt_qtqt(quat, q, quat);
1858 #else
1859                         quat_apply_track(quat, ob->trackflag, ob->upflag);
1860 #endif
1861                         normalize_qt(quat);
1862                         quat_to_mat4(mat, quat);
1863                 }
1864                 
1865                 if (cu->flag & CU_PATH_RADIUS) {
1866                         float tmat[4][4], rmat[4][4];
1867                         scale_m4_fl(tmat, radius);
1868                         mult_m4_m4m4(rmat, tmat, mat);
1869                         copy_m4_m4(mat, rmat);
1870                 }
1871
1872                 copy_v3_v3(mat[3], vec);
1873                 
1874         }
1875 }
1876
1877 static void ob_parbone(Object *ob, Object *par, float mat[4][4])
1878 {       
1879         bPoseChannel *pchan;
1880         float vec[3];
1881         
1882         if (par->type != OB_ARMATURE) {
1883                 unit_m4(mat);
1884                 return;
1885         }
1886         
1887         /* Make sure the bone is still valid */
1888         pchan = BKE_pose_channel_find_name(par->pose, ob->parsubstr);
1889         if (!pchan || !pchan->bone) {
1890                 printf("Object %s with Bone parent: bone %s doesn't exist\n", ob->id.name + 2, ob->parsubstr);
1891                 unit_m4(mat);
1892                 return;
1893         }
1894
1895         /* get bone transform */
1896         if (pchan->bone->flag & BONE_RELATIVE_PARENTING) {
1897                 /* the new option uses the root - expected bahaviour, but differs from old... */
1898                 /* XXX check on version patching? */
1899                 copy_m4_m4(mat, pchan->chan_mat);
1900         }
1901         else {
1902                 copy_m4_m4(mat, pchan->pose_mat);
1903
1904                 /* but for backwards compatibility, the child has to move to the tail */
1905                 copy_v3_v3(vec, mat[1]);
1906                 mul_v3_fl(vec, pchan->bone->length);
1907                 add_v3_v3(mat[3], vec);
1908         }
1909 }
1910
1911 static void give_parvert(Object *par, int nr, float vec[3])
1912 {
1913         BMEditMesh *em;
1914
1915         zero_v3(vec);
1916         
1917         if (par->type == OB_MESH) {
1918                 Mesh *me = par->data;
1919                 DerivedMesh *dm;
1920
1921                 em = me->edit_btmesh;
1922
1923 #if 0   /* this was bmesh only, better, evaluate why this was needed - campbell*/
1924                 if (em) {
1925                         BMVert *eve;
1926                         BMIter iter;
1927
1928                         BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
1929                                 int *keyindex = CustomData_bmesh_get(&em->bm->vdata, eve->head.data, CD_SHAPE_KEYINDEX);
1930                                 
1931                                 if (keyindex && *keyindex == nr) {
1932                                         copy_v3_v3(vec, eve->co);
1933                                         break;
1934                                 }
1935                         }
1936                 }
1937 #endif
1938
1939                 dm = (em) ? em->derivedFinal : par->derivedFinal;
1940                         
1941                 if (dm) {
1942                         int count = 0;
1943                         int numVerts = dm->getNumVerts(dm);
1944
1945                         if (nr < numVerts) {
1946                                 MVert *mvert = dm->getVertArray(dm);
1947                                 int   *index = (int *)dm->getVertDataArray(dm, CD_ORIGINDEX);
1948                                 int i;
1949
1950                                 /* get the average of all verts with (original index == nr) */
1951                                 if (index) {
1952                                         for (i = 0; i < numVerts; i++) {
1953                                                 if (index[i] == nr) {
1954                                                         add_v3_v3(vec, mvert[i].co);
1955                                                         count++;
1956                                                 }
1957                                         }
1958                                 }
1959                                 else {
1960                                         if (nr < numVerts) {
1961                                                 add_v3_v3(vec, mvert[nr].co);
1962                                                 count++;
1963                                         }
1964                                 }
1965                         }
1966
1967                         if (count == 0) {
1968                                 /* keep as 0, 0, 0 */
1969                         }
1970                         else if (count > 0) {
1971                                 mul_v3_fl(vec, 1.0f / count);
1972                         }
1973                         else {
1974                                 /* use first index if its out of range */
1975                                 dm->getVertCo(dm, 0, vec);
1976                         }
1977                 }
1978                 else {
1979                         fprintf(stderr,
1980                                 "%s: DerivedMesh is needed to solve parenting, "
1981                                 "object position can be wrong now\n", __func__);
1982                 }
1983         }
1984         else if (ELEM(par->type, OB_CURVE, OB_SURF)) {
1985                 Curve *cu       = par->data;
1986                 ListBase *nurb  = BKE_curve_nurbs_get(cu);
1987
1988                 BKE_nurbList_index_get_co(nurb, nr, vec);
1989         }
1990         else if (par->type == OB_LATTICE) {
1991                 Lattice *latt  = par->data;
1992                 DispList *dl   = BKE_displist_find(&par->disp, DL_VERTS);
1993                 float (*co)[3] = dl ? (float (*)[3])dl->verts : NULL;
1994                 int tot;
1995
1996                 if (latt->editlatt) latt = latt->editlatt->latt;
1997
1998                 tot = latt->pntsu * latt->pntsv * latt->pntsw;
1999
2000                 /* ensure dl is correct size */
2001                 BLI_assert(dl == NULL || dl->nr == tot);
2002
2003                 if (nr < tot) {
2004                         if (co) {
2005                                 copy_v3_v3(vec, co[nr]);
2006                         }
2007                         else {
2008                                 copy_v3_v3(vec, latt->def[nr].vec);
2009                         }
2010                 }
2011         }
2012 }
2013
2014 static void ob_parvert3(Object *ob, Object *par, float mat[4][4])
2015 {
2016         float cmat[3][3], v1[3], v2[3], v3[3], q[4];
2017
2018         /* in local ob space */
2019         unit_m4(mat);
2020         
2021         if (ELEM4(par->type, OB_MESH, OB_SURF, OB_CURVE, OB_LATTICE)) {
2022                 
2023                 give_parvert(par, ob->par1, v1);
2024                 give_parvert(par, ob->par2, v2);
2025                 give_parvert(par, ob->par3, v3);
2026                                 
2027                 tri_to_quat(q, v1, v2, v3);
2028                 quat_to_mat3(cmat, q);
2029                 copy_m4_m3(mat, cmat);
2030                 
2031                 if (ob->type == OB_CURVE) {
2032                         copy_v3_v3(mat[3], v1);
2033                 }
2034                 else {
2035                         add_v3_v3v3(mat[3], v1, v2);
2036                         add_v3_v3(mat[3], v3);
2037                         mul_v3_fl(mat[3], 1.0f / 3.0f);
2038                 }
2039         }
2040 }
2041
2042 static void solve_parenting(Scene *scene, Object *ob, Object *par, float obmat[4][4], float slowmat[4][4], int simul)
2043 {
2044         float totmat[4][4];
2045         float tmat[4][4];
2046         float locmat[4][4];
2047         float vec[3];
2048         int ok;
2049         
2050         BKE_object_to_mat4(ob, locmat);
2051         
2052         if (ob->partype & PARSLOW) copy_m4_m4(slowmat, obmat);
2053
2054         switch (ob->partype & PARTYPE) {
2055                 case PAROBJECT:
2056                         ok = 0;
2057                         if (par->type == OB_CURVE) {
2058                                 if (((Curve *)par->data)->flag & CU_PATH) {
2059                                         ob_parcurve(scene, ob, par, tmat);
2060                                         ok = 1;
2061                                 }
2062                         }
2063                         
2064                         if (ok) mul_serie_m4(totmat, par->obmat, tmat,
2065                                                  NULL, NULL, NULL, NULL, NULL, NULL);
2066                         else copy_m4_m4(totmat, par->obmat);
2067                         
2068                         break;
2069                 case PARBONE:
2070                         ob_parbone(ob, par, tmat);
2071                         mul_serie_m4(totmat, par->obmat, tmat,
2072                                      NULL, NULL, NULL, NULL, NULL, NULL);
2073                         break;
2074                 
2075                 case PARVERT1:
2076                         unit_m4(totmat);
2077                         if (simul) {
2078                                 copy_v3_v3(totmat[3], par->obmat[3]);
2079                         }
2080                         else {
2081                                 give_parvert(par, ob->par1, vec);
2082                                 mul_v3_m4v3(totmat[3], par->obmat, vec);
2083                         }
2084                         break;
2085                 case PARVERT3:
2086                         ob_parvert3(ob, par, tmat);
2087                         
2088                         mul_serie_m4(totmat, par->obmat, tmat,
2089                                      NULL, NULL, NULL, NULL, NULL, NULL);
2090                         break;
2091                 
2092                 case PARSKEL:
2093                         copy_m4_m4(totmat, par->obmat);
2094                         break;
2095         }
2096         
2097         /* total */
2098         mul_serie_m4(tmat, totmat, ob->parentinv,
2099                      NULL, NULL, NULL, NULL, NULL, NULL);
2100         mul_serie_m4(obmat, tmat, locmat,         
2101                      NULL, NULL, NULL, NULL, NULL, NULL);
2102         
2103         if (simul) {
2104
2105         }
2106         else {
2107                 /* external usable originmat */
2108                 copy_m3_m4(originmat, tmat);
2109                 
2110                 /* origin, for help line */
2111                 if ((ob->partype & PARTYPE) == PARSKEL) {
2112                         copy_v3_v3(ob->orig, par->obmat[3]);
2113                 }
2114                 else {
2115                         copy_v3_v3(ob->orig, totmat[3]);
2116                 }
2117         }
2118 }
2119
2120 static int where_is_object_parslow(Object *ob, float obmat[4][4], float slowmat[4][4])
2121 {
2122         float *fp1, *fp2;
2123         float fac1, fac2;
2124         int a;
2125
2126         /* include framerate */
2127         fac1 = (1.0f / (1.0f + fabsf(ob->sf)) );
2128         if (fac1 >= 1.0f) return 0;
2129         fac2 = 1.0f - fac1;
2130
2131         fp1 = obmat[0];
2132         fp2 = slowmat[0];
2133         for (a = 0; a < 16; a++, fp1++, fp2++) {
2134                 fp1[0] = fac1 * fp1[0] + fac2 * fp2[0];
2135         }
2136
2137         return 1;
2138 }
2139
2140 /* note, scene is the active scene while actual_scene is the scene the object resides in */
2141 void BKE_object_where_is_calc_time_ex(Scene *scene, Object *ob, float ctime,
2142                                       RigidBodyWorld *rbw)
2143 {
2144         if (ob == NULL) return;
2145         
2146         /* execute drivers only, as animation has already been done */
2147         BKE_animsys_evaluate_animdata(scene, &ob->id, ob->adt, ctime, ADT_RECALC_DRIVERS);
2148         
2149         if (ob->parent) {
2150                 Object *par = ob->parent;
2151                 float slowmat[4][4] = MAT4_UNITY;
2152                 
2153                 /* calculate parent matrix */
2154                 solve_parenting(scene, ob, par, ob->obmat, slowmat, 0);
2155                 
2156                 /* "slow parent" is definitely not threadsafe, and may also give bad results jumping around 
2157                  * An old-fashioned hack which probably doesn't really cut it anymore
2158                  */
2159                 if (ob->partype & PARSLOW) {
2160                         if (!where_is_object_parslow(ob, ob->obmat, slowmat))
2161                                 return;
2162                 }
2163         }
2164         else {
2165                 BKE_object_to_mat4(ob, ob->obmat);
2166         }
2167
2168         /* try to fall back to the scene rigid body world if none given */
2169         rbw = rbw ? rbw : scene->rigidbody_world;
2170         /* read values pushed into RBO from sim/cache... */
2171         BKE_rigidbody_sync_transforms(rbw, ob, ctime);
2172         
2173         /* solve constraints */
2174         if (ob->constraints.first && !(ob->transflag & OB_NO_CONSTRAINTS)) {
2175                 bConstraintOb *cob;
2176                 
2177                 cob = BKE_constraints_make_evalob(scene, ob, NULL, CONSTRAINT_OBTYPE_OBJECT);
2178                 BKE_solve_constraints(&ob->constraints, cob, ctime);
2179                 BKE_constraints_clear_evalob(cob);
2180         }
2181         
2182         /* set negative scale flag in object */
2183         if (is_negative_m4(ob->obmat)) ob->transflag |= OB_NEG_SCALE;
2184         else ob->transflag &= ~OB_NEG_SCALE;
2185 }
2186
2187 void BKE_object_where_is_calc_time(Scene *scene, Object *ob, float ctime)
2188 {
2189         BKE_object_where_is_calc_time_ex(scene, ob, ctime, NULL);
2190 }
2191
2192 /* get object transformation matrix without recalculating dependencies and
2193  * constraints -- assume dependencies are already solved by depsgraph.
2194  * no changes to object and it's parent would be done.
2195  * used for bundles orientation in 3d space relative to parented blender camera */
2196 void BKE_object_where_is_calc_mat4(Scene *scene, Object *ob, float obmat[4][4])
2197 {
2198         float slowmat[4][4] = MAT4_UNITY;
2199
2200         if (ob->parent) {
2201                 Object *par = ob->parent;
2202                 
2203                 solve_parenting(scene, ob, par, obmat, slowmat, 1);
2204                 
2205                 if (ob->partype & PARSLOW)
2206                         where_is_object_parslow(ob, obmat, slowmat);
2207         }
2208         else {
2209                 BKE_object_to_mat4(ob, obmat);
2210         }
2211 }
2212
2213 void BKE_object_where_is_calc_ex(Scene *scene, RigidBodyWorld *rbw, Object *ob)
2214 {
2215         BKE_object_where_is_calc_time_ex(scene, ob, BKE_scene_frame_get(scene), rbw);
2216 }
2217 void BKE_object_where_is_calc(Scene *scene, Object *ob)
2218 {
2219         BKE_object_where_is_calc_time_ex(scene, ob, BKE_scene_frame_get(scene), NULL);
2220 }
2221
2222 /* was written for the old game engine (until 2.04) */
2223 /* It seems that this function is only called
2224  * for a lamp that is the child of another object */
2225 void BKE_object_where_is_calc_simul(Scene *scene, Object *ob)
2226 {
2227         Object *par;
2228         float *fp1, *fp2;
2229         float slowmat[4][4];
2230         float fac1, fac2;
2231         int a;
2232         
2233         /* NO TIMEOFFS */
2234         if (ob->parent) {
2235                 par = ob->parent;
2236                 
2237                 solve_parenting(scene, ob, par, ob->obmat, slowmat, 1);
2238                 
2239                 if (ob->partype & PARSLOW) {
2240                         fac1 = (float)(1.0 / (1.0 + fabs(ob->sf)));
2241                         fac2 = 1.0f - fac1;
2242                         fp1 = ob->obmat[0];
2243                         fp2 = slowmat[0];
2244                         for (a = 0; a < 16; a++, fp1++, fp2++) {
2245                                 fp1[0] = fac1 * fp1[0] + fac2 * fp2[0];
2246                         }
2247                 }
2248         }
2249         else {
2250                 BKE_object_to_mat4(ob, ob->obmat);
2251         }
2252         
2253         /* solve constraints */
2254         if (ob->constraints.first) {
2255                 bConstraintOb *cob;
2256                 
2257                 cob = BKE_constraints_make_evalob(scene, ob, NULL, CONSTRAINT_OBTYPE_OBJECT);
2258                 BKE_solve_constraints(&ob->constraints, cob, BKE_scene_frame_get(scene));
2259                 BKE_constraints_clear_evalob(cob);
2260         }
2261 }
2262
2263 /* for calculation of the inverse parent transform, only used for editor */
2264 void BKE_object_workob_calc_parent(Scene *scene, Object *ob, Object *workob)
2265 {
2266         BKE_object_workob_clear(workob);
2267         
2268         unit_m4(workob->obmat);
2269         unit_m4(workob->parentinv);
2270         unit_m4(workob->constinv);
2271         workob->parent = ob->parent;
2272
2273         workob->trackflag = ob->trackflag;
2274         workob->upflag = ob->upflag;
2275         
2276         workob->partype = ob->partype;
2277         workob->par1 = ob->par1;
2278         workob->par2 = ob->par2;
2279         workob->par3 = ob->par3;
2280
2281         workob->constraints.first = ob->constraints.first;
2282         workob->constraints.last = ob->constraints.last;
2283
2284         BLI_strncpy(workob->parsubstr, ob->parsubstr, sizeof(workob->parsubstr));
2285
2286         BKE_object_where_is_calc(scene, workob);
2287 }
2288
2289 BoundBox *BKE_boundbox_alloc_unit(void)
2290 {
2291         BoundBox *bb;
2292         float min[3] = {-1.0f, -1.0f, -1.0f}, max[3] = {-1.0f, -1.0f, -1.0f};
2293
2294         bb = MEM_callocN(sizeof(BoundBox), "OB-BoundBox");
2295         BKE_boundbox_init_from_minmax(bb, min, max);
2296         
2297         return bb;
2298 }
2299
2300 void BKE_boundbox_init_from_minmax(BoundBox *bb, float min[3], float max[3])
2301 {
2302         bb->vec[0][0] = bb->vec[1][0] = bb->vec[2][0] = bb->vec[3][0] = min[0];
2303         bb->vec[4][0] = bb->vec[5][0] = bb->vec[6][0] = bb->vec[7][0] = max[0];
2304         
2305         bb->vec[0][1] = bb->vec[1][1] = bb->vec[4][1] = bb->vec[5][1] = min[1];
2306         bb->vec[2][1] = bb->vec[3][1] = bb->vec[6][1] = bb->vec[7][1] = max[1];
2307
2308         bb->vec[0][2] = bb->vec[3][2] = bb->vec[4][2] = bb->vec[7][2] = min[2];
2309         bb->vec[1][2] = bb->vec[2][2] = bb->vec[5][2] = bb->vec[6][2] = max[2];
2310 }
2311
2312 BoundBox *BKE_object_boundbox_get(Object *ob)
2313 {
2314         BoundBox *bb = NULL;
2315         
2316         if (ob->type == OB_MESH) {
2317                 bb = BKE_mesh_boundbox_get(ob);
2318         }
2319         else if (ELEM3(ob->type, OB_CURVE, OB_SURF, OB_FONT)) {
2320                 bb = ob->bb ? ob->bb : ((Curve *)ob->data)->bb;
2321         }
2322         else if (ob->type == OB_MBALL) {
2323                 bb = ob->bb;
2324         }
2325         return bb;
2326 }
2327
2328 /* used to temporally disable/enable boundbox */
2329 void BKE_object_boundbox_flag(Object *ob, int flag, int set)
2330 {
2331         BoundBox *bb = BKE_object_boundbox_get(ob);
2332         if (bb) {
2333                 if (set) bb->flag |= flag;
2334                 else bb->flag &= ~flag;
2335         }
2336 }
2337
2338 void BKE_object_dimensions_get(Object *ob, float vec[3])
2339 {
2340         BoundBox *bb = NULL;
2341         
2342         bb = BKE_object_boundbox_get(ob);
2343         if (bb) {
2344                 float scale[3];
2345                 
2346                 mat4_to_size(scale, ob->obmat);
2347                 
2348                 vec[0] = fabsf(scale[0]) * (bb->vec[4][0] - bb->vec[0][0]);
2349                 vec[1] = fabsf(scale[1]) * (bb->vec[2][1] - bb->vec[0][1]);
2350                 vec[2] = fabsf(scale[2]) * (bb->vec[1][2] - bb->vec[0][2]);
2351         }
2352         else {
2353                 zero_v3(vec);
2354         }
2355 }
2356
2357 void BKE_object_dimensions_set(Object *ob, const float *value)
2358 {
2359         BoundBox *bb = NULL;
2360         
2361         bb = BKE_object_boundbox_get(ob);
2362         if (bb) {
2363                 float scale[3], len[3];
2364                 
2365                 mat4_to_size(scale, ob->obmat);
2366                 
2367                 len[0] = bb->vec[4][0] - bb->vec[0][0];
2368                 len[1] = bb->vec[2][1] - bb->vec[0][1];
2369                 len[2] = bb->vec[1][2] - bb->vec[0][2];
2370                 
2371                 if (len[0] > 0.f) ob->size[0] = value[0] / len[0];
2372                 if (len[1] > 0.f) ob->size[1] = value[1] / len[1];
2373                 if (len[2] > 0.f) ob->size[2] = value[2] / len[2];
2374         }
2375 }
2376
2377 void BKE_object_minmax(Object *ob, float min_r[3], float max_r[3], const short use_hidden)
2378 {
2379         BoundBox bb;
2380         float vec[3];
2381         int a;
2382         short change = FALSE;
2383         
2384         switch (ob->type) {
2385                 case OB_CURVE:
2386                 case OB_FONT:
2387                 case OB_SURF:
2388                 {
2389                         Curve *cu = ob->data;
2390
2391                         /* Use the object bounding box so that modifier output
2392                          * gets taken into account */
2393                         if (ob->bb)
2394                                 bb = *(ob->bb);
2395                         else {
2396                                 if (cu->bb == NULL)
2397                                         BKE_curve_texspace_calc(cu);
2398                                 bb = *(cu->bb);
2399                         }
2400
2401                         for (a = 0; a < 8; a++) {
2402                                 mul_m4_v3(ob->obmat, bb.vec[a]);
2403                                 minmax_v3v3_v3(min_r, max_r, bb.vec[a]);
2404                         }
2405                         change = TRUE;
2406                 }
2407                 break;
2408                 case OB_LATTICE:
2409                 {
2410                         Lattice *lt = ob->data;
2411                         BPoint *bp = lt->def;
2412                         int u, v, w;
2413
2414                         for (w = 0; w < lt->pntsw; w++) {
2415                                 for (v = 0; v < lt->pntsv; v++) {
2416                                         for (u = 0; u < lt->pntsu; u++, bp++) {
2417                                                 mul_v3_m4v3(vec, ob->obmat, bp->vec);
2418                                                 minmax_v3v3_v3(min_r, max_r, vec);
2419                                         }
2420                                 }
2421                         }
2422                         change = TRUE;
2423                 }
2424                 break;
2425                 case OB_ARMATURE:
2426                         if (ob->pose) {
2427                                 bArmature *arm = ob->data;
2428                                 bPoseChannel *pchan;
2429
2430                                 for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
2431                                         /* XXX pchan->bone may be NULL for duplicated bones, see duplicateEditBoneObjects() comment
2432                                          *     (editarmature.c:2592)... Skip in this case too! */
2433                                         if (pchan->bone && !((use_hidden == FALSE) && (PBONE_VISIBLE(arm, pchan->bone) == FALSE))) {
2434                                                 mul_v3_m4v3(vec, ob->obmat, pchan->pose_head);
2435                                                 minmax_v3v3_v3(min_r, max_r, vec);
2436                                                 mul_v3_m4v3(vec, ob->obmat, pchan->pose_tail);
2437                                                 minmax_v3v3_v3(min_r, max_r, vec);
2438
2439                                                 change = TRUE;
2440                                         }
2441                                 }
2442                         }
2443                         break;
2444                 case OB_MESH:
2445                 {
2446                         Mesh *me = BKE_mesh_from_object(ob);
2447
2448                         if (me) {
2449                                 bb = *BKE_mesh_boundbox_get(ob);
2450
2451                                 for (a = 0; a < 8; a++) {
2452                                         mul_m4_v3(ob->obmat, bb.vec[a]);
2453                                         minmax_v3v3_v3(min_r, max_r, bb.vec[a]);
2454                                 }
2455                                 change = TRUE;
2456                         }
2457                 }
2458                 break;
2459         }
2460
2461         if (change == FALSE) {
2462                 float size[3];
2463
2464                 copy_v3_v3(size, ob->size);
2465                 if (ob->type == OB_EMPTY) {
2466                         mul_v3_fl(size, ob->empty_drawsize);
2467                 }
2468
2469                 minmax_v3v3_v3(min_r, max_r, ob->obmat[3]);
2470
2471                 copy_v3_v3(vec, ob->obmat[3]);
2472                 add_v3_v3(vec, size);
2473                 minmax_v3v3_v3(min_r, max_r, vec);
2474
2475                 copy_v3_v3(vec, ob->obmat[3]);
2476                 sub_v3_v3(vec, size);
2477                 minmax_v3v3_v3(min_r, max_r, vec);
2478         }
2479 }
2480
2481 int BKE_object_minmax_dupli(Scene *scene, Object *ob, float r_min[3], float r_max[3], const short use_hidden)
2482 {
2483         int ok = FALSE;
2484         if ((ob->transflag & OB_DUPLI) == 0) {
2485                 return ok;
2486         }
2487         else {
2488                 ListBase *lb;
2489                 DupliObject *dob;
2490                 
2491                 lb = object_duplilist(scene, ob, FALSE);
2492                 for (dob = lb->first; dob; dob = dob->next) {
2493                         if ((use_hidden == FALSE) && (dob->no_draw != 0)) {
2494                                 /* pass */
2495                         }
2496                         else {
2497                                 BoundBox *bb = BKE_object_boundbox_get(dob->ob);
2498
2499                                 if (bb) {
2500                                         int i;
2501                                         for (i = 0; i < 8; i++) {
2502                                                 float vec[3];
2503                                                 mul_v3_m4v3(vec, dob->mat, bb->vec[i]);
2504                                                 minmax_v3v3_v3(r_min, r_max, vec);
2505                                         }
2506
2507                                         ok = TRUE;
2508                                 }
2509                         }
2510                 }
2511                 free_object_duplilist(lb);  /* does restore */
2512         }
2513
2514         return ok;
2515 }
2516
2517 void BKE_object_foreach_display_point(
2518         Object *ob, float obmat[4][4],
2519         void (*func_cb)(const float[3], void *), void *user_data)
2520 {
2521         float co[3];
2522
2523         if (ob->derivedFinal) {
2524                 DerivedMesh *dm = ob->derivedFinal;
2525                 MVert *mv = dm->getVertArray(dm);
2526                 int totvert = dm->getNumVerts(dm);
2527                 int i;
2528
2529                 for (i = 0; i < totvert; i++, mv++) {
2530                         mul_v3_m4v3(co, obmat, mv->co);
2531                         func_cb(co, user_data);
2532                 }
2533         }
2534         else if (ob->disp.first) {
2535                 DispList *dl;
2536
2537                 for (dl = ob->disp.first; dl; dl = dl->next) {
2538                         float *v3 = dl->verts;
2539                         int totvert = dl->nr;
2540                         int i;
2541
2542                         for (i = 0; i < totvert; i++, v3 += 3) {
2543                                 mul_v3_m4v3(co, obmat, v3);
2544                                 func_cb(co, user_data);
2545                         }
2546                 }
2547         }
2548 }
2549
2550 void BKE_scene_foreach_display_point(
2551         Scene *scene, View3D *v3d, const short flag,
2552         void (*func_cb)(const float[3], void *), void *user_data)
2553 {
2554         Base *base;
2555         Object *ob;
2556
2557         for (base = FIRSTBASE; base; base = base->next) {
2558                 if (BASE_VISIBLE(v3d, base) && (base->flag & flag) == flag) {
2559                         ob = base->object;
2560
2561                         if ((ob->transflag & OB_DUPLI) == 0) {
2562                                 BKE_object_foreach_display_point(ob, ob->obmat, func_cb, user_data);
2563                         }
2564                         else {
2565                                 ListBase *lb;
2566                                 DupliObject *dob;
2567
2568                                 lb = object_duplilist(scene, ob, FALSE);
2569                                 for (dob = lb->first; dob; dob = dob->next) {
2570                                         if (dob->no_draw == 0) {
2571                                                 BKE_object_foreach_display_point(dob->ob, dob->mat, func_cb, user_data);
2572                                         }
2573                                 }
2574                                 free_object_duplilist(lb);  /* does restore */
2575                         }
2576                 }
2577         }
2578 }
2579
2580 /* copied from DNA_object_types.h */
2581 typedef struct ObTfmBack {
2582         float loc[3], dloc[3], orig[3];
2583         float size[3], dscale[3];   /* scale and delta scale */
2584         float rot[3], drot[3];      /* euler rotation */
2585         float quat[4], dquat[4];    /* quaternion rotation */
2586         float rotAxis[3], drotAxis[3];  /* axis angle rotation - axis part */
2587         float rotAngle, drotAngle;  /* axis angle rotation - angle part */
2588         float obmat[4][4];      /* final worldspace matrix with constraints & animsys applied */
2589         float parentinv[4][4]; /* inverse result of parent, so that object doesn't 'stick' to parent */
2590         float constinv[4][4]; /* inverse result of constraints. doesn't include effect of parent or object local transform */
2591         float imat[4][4];   /* inverse matrix of 'obmat' for during render, old game engine, temporally: ipokeys of transform  */
2592 } ObTfmBack;
2593
2594 void *BKE_object_tfm_backup(Object *ob)
2595 {
2596         ObTfmBack *obtfm = MEM_mallocN(sizeof(ObTfmBack), "ObTfmBack");
2597         copy_v3_v3(obtfm->loc, ob->loc);
2598         copy_v3_v3(obtfm->dloc, ob->dloc);
2599         copy_v3_v3(obtfm->orig, ob->orig);
2600         copy_v3_v3(obtfm->size, ob->size);
2601         copy_v3_v3(obtfm->dscale, ob->dscale);
2602         copy_v3_v3(obtfm->rot, ob->rot);
2603         copy_v3_v3(obtfm->drot, ob->drot);
2604         copy_qt_qt(obtfm->quat, ob->quat);
2605         copy_qt_qt(obtfm->dquat, ob->dquat);
2606         copy_v3_v3(obtfm->rotAxis, ob->rotAxis);
2607         copy_v3_v3(obtfm->drotAxis, ob->drotAxis);
2608         obtfm->rotAngle = ob->rotAngle;
2609         obtfm->drotAngle = ob->drotAngle;
2610         copy_m4_m4(obtfm->obmat, ob->obmat);
2611         copy_m4_m4(obtfm->parentinv, ob->parentinv);
2612         copy_m4_m4(obtfm->constinv, ob->constinv);
2613         copy_m4_m4(obtfm->imat, ob->imat);
2614
2615         return (void *)obtfm;
2616 }
2617
2618 void BKE_object_tfm_restore(Object *ob, void *obtfm_pt)
2619 {
2620         ObTfmBack *obtfm = (ObTfmBack *)obtfm_pt;
2621         copy_v3_v3(ob->loc, obtfm->loc);
2622         copy_v3_v3(ob->dloc, obtfm->dloc);
2623         copy_v3_v3(ob->orig, obtfm->orig);
2624         copy_v3_v3(ob->size, obtfm->size);
2625         copy_v3_v3(ob->dscale, obtfm->dscale);
2626         copy_v3_v3(ob->rot, obtfm->rot);
2627         copy_v3_v3(ob->drot, obtfm->drot);
2628         copy_qt_qt(ob->quat, obtfm->quat);
2629         copy_qt_qt(ob->dquat, obtfm->dquat);
2630         copy_v3_v3(ob->rotAxis, obtfm->rotAxis);
2631         copy_v3_v3(ob->drotAxis, obtfm->drotAxis);
2632         ob->rotAngle = obtfm->rotAngle;
2633         ob->drotAngle = obtfm->drotAngle;
2634         copy_m4_m4(ob->obmat, obtfm->obmat);
2635         copy_m4_m4(ob->parentinv, obtfm->parentinv);
2636         copy_m4_m4(ob->constinv, obtfm->constinv);
2637         copy_m4_m4(ob->imat, obtfm->imat);
2638 }
2639
2640 bool BKE_object_parent_loop_check(const Object *par, const Object *ob)
2641 {
2642         /* test if 'ob' is a parent somewhere in par's parents */
2643         if (par == NULL) return false;
2644         if (ob == par) return true;
2645         return BKE_object_parent_loop_check(par->parent, ob);
2646 }
2647
2648 /* proxy rule: lib_object->proxy_from == the one we borrow from, only set temporal and cleared here */
2649 /*           local_object->proxy      == pointer to library object, saved in files and read */
2650
2651 /* function below is polluted with proxy exceptions, cleanup will follow! */
2652
2653 /* the main object update call, for object matrix, constraints, keys and displist (modifiers) */
2654 /* requires flags to be set! */
2655 /* Ideally we shouldn't have to pass the rigid body world, but need bigger restructuring to avoid id */
2656 void BKE_object_handle_update_ex(Scene *scene, Object *ob,
2657                                  RigidBodyWorld *rbw)
2658 {
2659         if (ob->recalc & OB_RECALC_ALL) {
2660                 /* speed optimization for animation lookups */
2661                 if (ob->pose)
2662                         BKE_pose_channels_hash_make(ob->pose);
2663
2664                 if (ob->recalc & OB_RECALC_DATA) {
2665                         if (ob->type == OB_ARMATURE) {
2666                                 /* this happens for reading old files and to match library armatures
2667                                  * with poses we do it ahead of BKE_object_where_is_calc to ensure animation
2668                                  * is evaluated on the rebuilt pose, otherwise we get incorrect poses
2669                                  * on file load */
2670                                 if (ob->pose == NULL || (ob->pose->flag & POSE_RECALC))
2671                                         BKE_pose_rebuild(ob, ob->data);
2672                         }
2673                 }
2674
2675                 /* XXX new animsys warning: depsgraph tag OB_RECALC_DATA should not skip drivers, 
2676                  * which is only in BKE_object_where_is_calc now */
2677                 /* XXX: should this case be OB_RECALC_OB instead? */
2678                 if (ob->recalc & OB_RECALC_ALL) {
2679                         
2680                         if (G.debug & G_DEBUG)
2681                                 printf("recalcob %s\n", ob->id.name + 2);
2682                         
2683                         /* handle proxy copy for target */
2684                         if (ob->id.lib && ob->proxy_from) {
2685                                 // printf("ob proxy copy, lib ob %s proxy %s\n", ob->id.name, ob->proxy_from->id.name);
2686                                 if (ob->proxy_from->proxy_group) { /* transform proxy into group space */
2687                                         Object *obg = ob->proxy_from->proxy_group;
2688                                         invert_m4_m4(obg->imat, obg->obmat);
2689                                         mult_m4_m4m4(ob->obmat, obg->imat, ob->proxy_from->obmat);
2690                                         if (obg->dup_group) { /* should always be true */
2691                                                 add_v3_v3(ob->obmat[3], obg->dup_group->dupli_ofs);
2692                                         }
2693                                 }
2694                                 else
2695                                         copy_m4_m4(ob->obmat, ob->proxy_from->obmat);
2696                         }
2697                         else
2698                                 BKE_object_where_is_calc_ex(scene, rbw, ob);
2699                 }
2700                 
2701                 if (ob->recalc & OB_RECALC_DATA) {
2702                         ID *data_id = (ID *)ob->data;
2703                         AnimData *adt = BKE_animdata_from_id(data_id);
2704                         float ctime = BKE_scene_frame_get(scene);
2705                         
2706                         if (G.debug & G_DEBUG)
2707                                 printf("recalcdata %s\n", ob->id.name + 2);
2708
2709                         if (adt) {
2710                                 /* evaluate drivers - datalevel */
2711                                 /* XXX: for mesh types, should we push this to derivedmesh instead? */
2712                                 BKE_animsys_evaluate_animdata(scene, data_id, adt, ctime, ADT_RECALC_DRIVERS);
2713                         }
2714
2715                         /* includes all keys and modifiers */
2716                         switch (ob->type) {
2717                                 case OB_MESH:
2718                                 {
2719 #if 0               // XXX, comment for 2.56a release, background wont set 'scene->customdata_mask'
2720                                         BMEditMesh *em = (ob == scene->obedit) ? BMEdit_FromObject(ob) : NULL;
2721                                         BLI_assert((scene->customdata_mask & CD_MASK_BAREMESH) == CD_MASK_BAREMESH);
2722                                         if (em) {
2723                                                 makeDerivedMesh(scene, ob, em,  scene->customdata_mask, 0); /* was CD_MASK_BAREMESH */
2724                                         }
2725                                         else {
2726                                                 makeDerivedMesh(scene, ob, NULL, scene->customdata_mask, 0);
2727                                         }
2728
2729 #else               /* ensure CD_MASK_BAREMESH for now */
2730                                         BMEditMesh *em = (ob == scene->obedit) ? BMEdit_FromObject(ob) : NULL;
2731                                         uint64_t data_mask = scene->customdata_mask | ob->customdata_mask | CD_MASK_BAREMESH;
2732                                         if (em) {
2733                                                 makeDerivedMesh(scene, ob, em,  data_mask, 0); /* was CD_MASK_BAREMESH */
2734                                         }
2735                                         else {
2736                                                 makeDerivedMesh(scene, ob, NULL, data_mask, 0);
2737                                         }
2738 #endif
2739
2740                                 }
2741                                 break;
2742
2743                                 case OB_ARMATURE:
2744                                         if (ob->id.lib && ob->proxy_from) {
2745                                                 if (BKE_pose_copy_result(ob->pose, ob->proxy_from->pose) == false) {
2746                                                         printf("Proxy copy error, lib Object: %s proxy Object: %s\n",
2747                                                                ob->id.name + 2, ob->proxy_from->id.name + 2);
2748                                                 }
2749                                         }
2750                                         else {
2751                                                 BKE_pose_where_is(scene, ob);
2752                                         }
2753                                         break;
2754
2755                                 case OB_MBALL:
2756                                         BKE_displist_make_mball(scene, ob);
2757                                         break;
2758
2759                                 case OB_CURVE:
2760                                 case OB_SURF:
2761                                 case OB_FONT:
2762                                         BKE_displist_make_curveTypes(scene, ob, 0);
2763                                         break;
2764                                 
2765                                 case OB_LATTICE:
2766                                         BKE_lattice_modifiers_calc(scene, ob);
2767                                         break;
2768                         }
2769                         
2770                         /* related materials */
2771                         /* XXX: without depsgraph tagging, this will always need to be run, which will be slow! 
2772                          * However, not doing anything (or trying to hack around this lack) is not an option 
2773                          * anymore, especially due to Cycles [#31834] 
2774                          */
2775                         if (ob->totcol) {
2776                                 int a;
2777                                 
2778                                 for (a = 1; a <= ob->totcol; a++) {
2779                                         Material *ma = give_current_material(ob, a);
2780                                         
2781                                         if (ma) {
2782                                                 /* recursively update drivers for this material */
2783                                                 material_drivers_update(scene, ma, ctime);
2784                                         }
2785                                 }
2786                         }
2787                         else if (ob->type == OB_LAMP)
2788                                 lamp_drivers_update(scene, ob->data, ctime);
2789                         
2790                         /* particles */
2791                         if (ob->particlesystem.first) {
2792                                 ParticleSystem *tpsys, *psys;
2793                                 DerivedMesh *dm;
2794                                 ob->transflag &= ~OB_DUPLIPARTS;
2795                                 
2796                                 psys = ob->particlesystem.first;
2797                                 while (psys) {
2798                                         if (psys_check_enabled(ob, psys)) {
2799                                                 /* check use of dupli objects here */
2800                                                 if (psys->part && (psys->part->draw_as == PART_DRAW_REND || G.is_rendering) &&
2801                                                     ((psys->part->ren_as == PART_DRAW_OB && psys->part->dup_ob) ||
2802                                                      (psys->part->ren_as == PART_DRAW_GR && psys->part->dup_group)))
2803                                                 {
2804                                                         ob->transflag |= OB_DUPLIPARTS;
2805                                                 }
2806
2807                                                 particle_system_update(scene, ob, psys);
2808                                                 psys = psys->next;
2809                                         }
2810                                         else if (psys->flag & PSYS_DELETE) {
2811                                                 tpsys = psys->next;
2812                                                 BLI_remlink(&ob->particlesystem, psys);
2813                                                 psys_free(ob, psys);
2814                                                 psys = tpsys;
2815                                         }
2816                                         else
2817                                                 psys = psys->next;
2818                                 }
2819
2820                                 if (G.is_rendering && ob->transflag & OB_DUPLIPARTS) {
2821                                         /* this is to make sure we get render level duplis in groups:
2822                                          * the derivedmesh must be created before init_render_mesh,
2823                                          * since object_duplilist does dupliparticles before that */
2824                                         dm = mesh_create_derived_render(scene, ob, CD_MASK_BAREMESH | CD_MASK_MTFACE | CD_MASK_MCOL);
2825                                         dm->release(dm);
2826
2827                                         for (psys = ob->particlesystem.first; psys; psys = psys->next)
2828                                                 psys_get_modifier(ob, psys)->flag &= ~eParticleSystemFlag_psys_updated;
2829                                 }
2830                         }
2831                         
2832                         /* quick cache removed */
2833                 }
2834
2835                 /* the no-group proxy case, we call update */
2836                 if (ob->proxy && ob->proxy_group == NULL) {
2837                         /* set pointer in library proxy target, for copying, but restore it */
2838                         ob->proxy->proxy_from = ob;
2839                         // printf("call update, lib ob %s proxy %s\n", ob->proxy->id.name, ob->id.name);
2840                         BKE_object_handle_update(scene, ob->proxy);
2841                 }
2842         
2843                 ob->recalc &= ~OB_RECALC_ALL;
2844         }
2845
2846         /* the case when this is a group proxy, object_update is called in group.c */
2847         if (ob->proxy) {
2848                 ob->proxy->proxy_from = ob;
2849                 // printf("set proxy pointer for later group stuff %s\n", ob->id.name);
2850         }
2851 }
2852 /* WARNING: "scene" here may not be the scene object actually resides in. 
2853  * When dealing with background-sets, "scene" is actually the active scene.
2854  * e.g. "scene" <-- set 1 <-- set 2 ("ob" lives here) <-- set 3 <-- ... <-- set n
2855  * rigid bodies depend on their world so use BKE_object_handle_update_ex() to also pass along the corrent rigid body world
2856  */
2857 void BKE_object_handle_update(Scene *scene, Object *ob)
2858 {
2859         BKE_object_handle_update_ex(scene, ob, NULL);
2860 }
2861
2862 void BKE_object_sculpt_modifiers_changed(Object *ob)
2863 {
2864         SculptSession *ss = ob->sculpt;
2865
2866         if (!ss->cache) {
2867                 /* we free pbvh on changes, except during sculpt since it can't deal with
2868                  * changing PVBH node organization, we hope topology does not change in
2869                  * the meantime .. weak */
2870                 if (ss->pbvh) {
2871                         BKE_pbvh_free(ss->pbvh);
2872                         ss->pbvh = NULL;
2873                 }
2874
2875                 free_sculptsession_deformMats(ob->sculpt);
2876         }
2877         else {
2878                 PBVHNode **nodes;
2879                 int n, totnode;
2880
2881                 BKE_pbvh_search_gather(ss->pbvh, NULL, NULL, &nodes, &totnode);
2882
2883                 for (n = 0; n < totnode; n++)
2884                         BKE_pbvh_node_mark_update(nodes[n]);
2885
2886                 MEM_freeN(nodes);
2887         }
2888 }
2889
2890 int BKE_object_obdata_texspace_get(Object *ob, short **r_texflag, float **r_loc, float **r_size, float **r_rot)
2891 {
2892         
2893         if (ob->data == NULL)
2894                 return 0;
2895         
2896         switch (GS(((ID *)ob->data)->name)) {
2897                 case ID_ME:
2898                 {
2899                         Mesh *me = ob->data;
2900                         if (r_texflag) *r_texflag = &me->texflag;
2901                         if (r_loc) *r_loc = me->loc;
2902                         if (r_size) *r_size = me->size;
2903                         if (r_rot) *r_rot = me->rot;
2904                         break;
2905                 }
2906                 case ID_CU:
2907                 {
2908                         Curve *cu = ob->data;
2909                         if (r_texflag) *r_texflag = &cu->texflag;
2910                         if (r_loc) *r_loc = cu->loc;
2911                         if (r_size) *r_size = cu->size;
2912                         if (r_rot) *r_rot = cu->rot;
2913                         break;
2914                 }
2915                 case ID_MB:
2916                 {
2917                         MetaBall *mb = ob->data;
2918                         if (r_texflag) *r_texflag = &mb->texflag;
2919                         if (r_loc) *r_loc = mb->loc;
2920                         if (r_size) *r_size = mb->size;
2921                         if (r_rot) *r_rot = mb->rot;
2922                         break;
2923                 }
2924                 default:
2925                         return 0;
2926         }
2927         return 1;
2928 }
2929
2930 /*
2931  * Test a bounding box for ray intersection
2932  * assumes the ray is already local to the boundbox space
2933  */
2934 int BKE_boundbox_ray_hit_check(struct BoundBox *bb, float ray_start[3], float ray_normal[3])
2935 {
2936         static int triangle_indexes[12][3] = {{0, 1, 2}, {0, 2, 3},
2937                                               {3, 2, 6}, {3, 6, 7},
2938                                               {1, 2, 6}, {1, 6, 5},
2939                                               {5, 6, 7}, {4, 5, 7},
2940                                               {0, 3, 7}, {0, 4, 7},
2941                                               {0, 1, 5}, {0, 4, 5}};
2942         int result = 0;
2943         int i;
2944         
2945         for (i = 0; i < 12 && result == 0; i++) {
2946                 float lambda;
2947                 int v1, v2, v3;
2948                 v1 = triangle_indexes[i][0];
2949                 v2 = triangle_indexes[i][1];
2950                 v3 = triangle_indexes[i][2];
2951                 result = isect_ray_tri_v3(ray_start, ray_normal, bb->vec[v1], bb->vec[v2], bb->vec[v3], &lambda, NULL);
2952         }
2953         
2954         return result;
2955 }
2956
2957 static int pc_cmp(void *a, void *b)
2958 {
2959         LinkData *ad = a, *bd = b;
2960         if (GET_INT_FROM_POINTER(ad->data) > GET_INT_FROM_POINTER(bd->data))
2961                 return 1;
2962         else return 0;
2963 }
2964
2965 int BKE_object_insert_ptcache(Object *ob) 
2966 {
2967         LinkData *link = NULL;
2968         int i = 0;
2969
2970         BLI_sortlist(&ob->pc_ids, pc_cmp);
2971
2972         for (link = ob->pc_ids.first, i = 0; link; link = link->next, i++) {
2973                 int index = GET_INT_FROM_POINTER(link->data);
2974
2975                 if (i < index)
2976                         break;
2977         }
2978
2979         link = MEM_callocN(sizeof(LinkData), "PCLink");
2980         link->data = SET_INT_IN_POINTER(i);
2981         BLI_addtail(&ob->pc_ids, link);
2982
2983         return i;
2984 }
2985
2986 #if 0
2987 static int pc_findindex(ListBase *listbase, int index)
2988 {
2989         LinkData *link = NULL;
2990         int number = 0;
2991         
2992         if (listbase == NULL) return -1;
2993         
2994         link = listbase->first;
2995         while (link) {
2996