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