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