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