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