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