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