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