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