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