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