- remove unused includes IMB_*, BIF_* & MEM_*
[blender.git] / source / blender / blenkernel / intern / anim.c
1 /** anim.c
2  *
3  *
4  * $Id$
5  *
6  * ***** BEGIN GPL LICENSE BLOCK *****
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License
10  * as published by the Free Software Foundation; either version 2
11  * of the License, or (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software Foundation,
20  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21  *
22  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
23  * All rights reserved.
24  *
25  * The Original Code is: all of this file.
26  *
27  * Contributor(s): none yet.
28  *
29  * ***** END GPL LICENSE BLOCK *****
30  */
31
32 #include <stdio.h>
33 #include <math.h>
34 #include <string.h>
35
36 #include "MEM_guardedalloc.h"
37
38 #include "BLI_blenlib.h"
39 #include "BLI_editVert.h"
40 #include "BLI_math.h"
41 #include "BLI_rand.h"
42
43 #include "DNA_anim_types.h"
44 #include "DNA_armature_types.h"
45 #include "DNA_group_types.h"
46 #include "DNA_key_types.h"
47 #include "DNA_meshdata_types.h"
48 #include "DNA_scene_types.h"
49 #include "DNA_vfont_types.h"
50
51 #include "BKE_curve.h"
52 #include "BKE_DerivedMesh.h"
53 #include "BKE_depsgraph.h"
54 #include "BKE_font.h"
55 #include "BKE_group.h"
56 #include "BKE_global.h"
57 #include "BKE_key.h"
58 #include "BKE_lattice.h"
59 #include "BKE_main.h"
60 #include "BKE_mesh.h"
61 #include "BKE_object.h"
62 #include "BKE_particle.h"
63 #include "BKE_scene.h"
64 #include "BKE_utildefines.h"
65 #include "BKE_depsgraph.h"
66
67
68 // XXX bad level call...
69
70 /* --------------------- */
71 /* forward declarations */
72
73 static void object_duplilist_recursive(ID *id, Scene *scene, Object *ob, ListBase *duplilist, float par_space_mat[][4], int level, int animated);
74
75 /* ******************************************************************** */
76 /* Animation Visualisation */
77
78 /* Initialise the default settings for animation visualisation */
79 void animviz_settings_init(bAnimVizSettings *avs)
80 {
81         /* sanity check */
82         if (avs == NULL)
83                 return;
84                 
85         /* ghosting settings */
86         avs->ghost_bc= avs->ghost_ac= 10;
87         
88         avs->ghost_sf= 1; // xxx - take from scene instead?
89         avs->ghost_ef= 250; // xxx - take from scene instead?
90         
91         avs->ghost_step= 1;
92         
93         
94         /* path settings */
95         avs->path_bc= avs->path_ac= 10;
96         
97         avs->path_sf= 1; // xxx - take from scene instead?
98         avs->path_ef= 250; // xxx - take from scene instead?
99         
100         avs->path_viewflag= (MOTIONPATH_VIEW_KFRAS|MOTIONPATH_VIEW_KFNOS);
101         
102         avs->path_step= 1;
103 }
104
105 /* ------------------- */
106
107 /* Free the given motion path's cache */
108 void animviz_free_motionpath_cache(bMotionPath *mpath) 
109 {
110         /* sanity check */
111         if (mpath == NULL) 
112                 return;
113                 
114         /* free the path if necessary */
115         if (mpath->points)
116                 MEM_freeN(mpath->points);
117         
118         /* reset the relevant parameters */
119         mpath->points= NULL;
120         mpath->length= 0;
121 }
122
123 /* Free the given motion path instance and its data 
124  * NOTE: this frees the motion path given!
125  */
126 void animviz_free_motionpath(bMotionPath *mpath)
127 {
128         /* sanity check */
129         if (mpath == NULL)
130                 return;
131         
132         /* free the cache first */
133         animviz_free_motionpath_cache(mpath);
134         
135         /* now the instance itself */
136         MEM_freeN(mpath);
137 }
138
139 /* ------------------- */
140
141 /* Setup motion paths for the given data
142  *      - scene: current scene (for frame ranges, etc.)
143  *      - ob: object to add paths for (must be provided)
144  *      - pchan: posechannel to add paths for (optional; if not provided, object-paths are assumed)
145  */
146 bMotionPath *animviz_verify_motionpaths(Scene *scene, Object *ob, bPoseChannel *pchan)
147 {
148         bAnimVizSettings *avs;
149         bMotionPath *mpath, **dst;
150         
151         /* sanity checks */
152         if (ELEM(NULL, scene, ob))
153                 return NULL;
154                 
155         /* get destination data */
156         if (pchan) {
157                 /* paths for posechannel - assume that posechannel belongs to the object */
158                 avs= &ob->pose->avs;
159                 dst= &pchan->mpath;
160         }
161         else {
162                 /* paths for object */
163                 avs= &ob->avs;
164                 dst= &ob->mpath;
165         }
166         
167         /* if there is already a motionpath, just return that,
168          * but provided it's settings are ok 
169          */
170         if (*dst != NULL) {
171                 mpath= *dst;
172                 
173                 /* if range is not invalid, and/or length is set ok, just return */
174                 if ((mpath->start_frame != mpath->end_frame) && (mpath->length > 0))
175                         return mpath;
176         }
177         else {
178                 /* create a new motionpath, and assign it */
179                 mpath= MEM_callocN(sizeof(bMotionPath), "bMotionPath");
180                 *dst= mpath;
181         }
182         
183         /* set settings from the viz settings */
184         mpath->start_frame= avs->path_sf;
185         mpath->end_frame= avs->path_ef;
186         
187         mpath->length= mpath->end_frame - mpath->start_frame;
188         
189         if (avs->path_bakeflag & MOTIONPATH_BAKE_HEADS)
190                 mpath->flag |= MOTIONPATH_FLAG_BHEAD;
191         else
192                 mpath->flag &= ~MOTIONPATH_FLAG_BHEAD;
193         
194         /* allocate a cache */
195         mpath->points= MEM_callocN(sizeof(bMotionPathVert)*mpath->length, "bMotionPathVerts");
196         
197         /* tag viz settings as currently having some path(s) which use it */
198         avs->path_bakeflag |= MOTIONPATH_BAKE_HAS_PATHS;
199         
200         /* return it */
201         return mpath;
202 }
203
204 /* ------------------- */
205
206 /* Motion path needing to be baked (mpt) */
207 typedef struct MPathTarget {
208         struct MPathTarget *next, *prev;
209         
210         bMotionPath *mpath;                     /* motion path in question */
211         
212         Object *ob;                                     /* source object */
213         bPoseChannel *pchan;            /* source posechannel (if applicable) */
214 } MPathTarget;
215
216 /* ........ */
217
218 /* get list of motion paths to be baked for the given object
219  *      - assumes the given list is ready to be used
220  */
221 void animviz_get_object_motionpaths(Object *ob, ListBase *targets)
222 {
223         MPathTarget *mpt;
224         
225         /* object itself first */
226         if ((ob->avs.recalc & ANIMVIZ_RECALC_PATHS) && (ob->mpath)) {
227                 /* new target for object */
228                 mpt= MEM_callocN(sizeof(MPathTarget), "MPathTarget Ob");
229                 BLI_addtail(targets, mpt);
230                 
231                 mpt->mpath= ob->mpath;
232                 mpt->ob= ob;
233         }
234         
235         /* bones */
236         if ((ob->pose) && (ob->pose->avs.recalc & ANIMVIZ_RECALC_PATHS)) {
237                 bArmature *arm= ob->data;
238                 bPoseChannel *pchan;
239                 
240                 for (pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
241                         if ((pchan->bone) && (arm->layer & pchan->bone->layer) && (pchan->mpath)) {
242                                 /* new target for bone */
243                                 mpt= MEM_callocN(sizeof(MPathTarget), "MPathTarget PoseBone");
244                                 BLI_addtail(targets, mpt);
245                                 
246                                 mpt->mpath= pchan->mpath;
247                                 mpt->ob= ob;
248                                 mpt->pchan= pchan;
249                         }
250                 }
251         }
252 }
253
254 /* ........ */
255
256 /* Note on evaluation optimisations:
257  * Optimisations currently used here play tricks with the depsgraph in order to try and 
258  * evaluate as few objects as strictly necessary to get nicer performance under standard
259  * production conditions. For those people who really need the accurate version, 
260  * disable the ifdef (i.e. 1 -> 0) and comment out the call to motionpaths_calc_optimise_depsgraph()
261  */
262
263 /* tweak the object ordering to trick depsgraph into making MotionPath calculations run faster */
264 static void motionpaths_calc_optimise_depsgraph(Scene *scene, ListBase *targets)
265 {
266         Base *base, *baseNext;
267         MPathTarget *mpt;
268         
269         /* make sure our temp-tag isn't already in use */
270         for (base= scene->base.first; base; base= base->next)
271                 base->object->flag &= ~BA_TEMP_TAG;
272         
273         /* for each target, dump its object to the start of the list if it wasn't moved already */
274         for (mpt= targets->first; mpt; mpt= mpt->next) {
275                 for (base=scene->base.first; base; base=baseNext) {
276                         baseNext = base->next;
277                         
278                         if ((base->object == mpt->ob) && !(mpt->ob->flag & BA_TEMP_TAG)) {
279                                 BLI_remlink(&scene->base, base);
280                                 BLI_addhead(&scene->base, base);
281                                 
282                                 mpt->ob->flag |= BA_TEMP_TAG;
283                                 break; // we really don't need to continue anymore once this happens, but this line might really 'break'
284                         }
285                 }
286         }
287         
288         /* "brew me a list that's sorted a bit faster now depsy" */
289         DAG_scene_sort(G.main, scene);
290 }
291
292 /* update scene for current frame */
293 static void motionpaths_calc_update_scene(Scene *scene)
294 {
295 #if 1 // 'production' optimisations always on
296         Base *base, *last=NULL;
297         
298         /* only stuff that moves or needs display still */
299         DAG_scene_update_flags(G.main, scene, scene->lay);
300         
301         /* find the last object with the tag 
302          *      - all those afterwards are assumed to not be relevant for our calculations
303          */
304         // optimise further by moving out...
305         for (base=scene->base.first; base; base=base->next) {
306                 if (base->object->flag & BA_TEMP_TAG)
307                         last = base;
308         }
309         
310         /* perform updates for tagged objects */
311         // XXX: this will break if rigs depend on scene or other data that 
312         // is animated but not attached to/updatable from objects
313         for (base=scene->base.first; base; base=base->next) {
314                 /* update this object */
315                 object_handle_update(scene, base->object);
316                 
317                 /* if this is the last one we need to update, let's stop to save some time */
318                 if (base == last)
319                         break;
320         }
321 #else // original, 'always correct' version
322         /* do all updates 
323          *      - if this is too slow, resort to using a more efficient way 
324          *        that doesn't force complete update, but for now, this is the
325          *        most accurate way!
326          */
327         scene_update_for_newframe(G.main, scene, scene->lay); // XXX this is the best way we can get anything moving
328 #endif
329 }
330
331 /* ........ */
332
333 /* perform baking for the targets on the current frame */
334 static void motionpaths_calc_bake_targets(Scene *scene, ListBase *targets)
335 {
336         MPathTarget *mpt;
337         
338         /* for each target, check if it can be baked on the current frame */
339         for (mpt= targets->first; mpt; mpt= mpt->next) {        
340                 bMotionPath *mpath= mpt->mpath;
341                 bMotionPathVert *mpv;
342                 
343                 /* current frame must be within the range the cache works for 
344                  *      - is inclusive of the first frame, but not the last otherwise we get buffer overruns
345                  */
346                 if ((CFRA < mpath->start_frame) || (CFRA >= mpath->end_frame))
347                         continue;
348                 
349                 /* get the relevant cache vert to write to */
350                 mpv= mpath->points + (CFRA - mpath->start_frame);
351                 
352                 /* pose-channel or object path baking? */
353                 if (mpt->pchan) {
354                         /* heads or tails */
355                         if (mpath->flag & MOTIONPATH_FLAG_BHEAD) {
356                                 VECCOPY(mpv->co, mpt->pchan->pose_head);
357                         }
358                         else {
359                                 VECCOPY(mpv->co, mpt->pchan->pose_tail);
360                         }
361                         
362                         /* result must be in worldspace */
363                         mul_m4_v3(mpt->ob->obmat, mpv->co);
364                 }
365                 else {
366                         /* worldspace object location */
367                         VECCOPY(mpv->co, mpt->ob->obmat[3]);
368                 }
369         }
370 }
371
372 /* Perform baking of the given object's and/or its bones' transforms to motion paths 
373  *      - scene: current scene
374  *      - ob: object whose flagged motionpaths should get calculated
375  *      - recalc: whether we need to 
376  */
377 // TODO: include reports pointer?
378 void animviz_calc_motionpaths(Scene *scene, ListBase *targets)
379 {
380         MPathTarget *mpt;
381         int sfra, efra;
382         int cfra;
383         
384         /* sanity check */
385         if (ELEM(NULL, targets, targets->first))
386                 return;
387         
388         /* set frame values */
389         cfra = CFRA;
390         sfra = efra = cfra;
391         
392         // TODO: this method could be improved...
393         //      1) max range for standard baking
394         //      2) minimum range for recalc baking (i.e. between keyframes, but how?)
395         for (mpt= targets->first; mpt; mpt= mpt->next) {
396                 /* try to increase area to do (only as much as needed) */
397                 sfra= MIN2(sfra, mpt->mpath->start_frame);
398                 efra= MAX2(efra, mpt->mpath->end_frame);
399         }
400         if (efra <= sfra) return;
401         
402         /* optimise the depsgraph for faster updates */
403         // TODO: whether this is used should depend on some setting for the level of optimisations used
404         motionpaths_calc_optimise_depsgraph(scene, targets);
405         
406         /* calculate path over requested range */
407         for (CFRA=sfra; CFRA<=efra; CFRA++) {
408                 /* update relevant data for new frame */
409                 motionpaths_calc_update_scene(scene);
410                 
411                 /* perform baking for targets */
412                 motionpaths_calc_bake_targets(scene, targets);
413         }
414         
415         /* reset original environment */
416         CFRA= cfra;
417         motionpaths_calc_update_scene(scene);
418         
419         /* clear recalc flags from targets */
420         for (mpt= targets->first; mpt; mpt= mpt->next) {
421                 bAnimVizSettings *avs;
422                 
423                 /* get pointer to animviz settings for each target */
424                 if (mpt->pchan)
425                         avs= &mpt->ob->pose->avs;
426                 else    
427                         avs= &mpt->ob->avs;
428                 
429                 /* clear the flag requesting recalculation of targets */
430                 avs->recalc &= ~ANIMVIZ_RECALC_PATHS;
431         }
432 }
433
434 /* ******************************************************************** */
435 /* Curve Paths - for curve deforms and/or curve following */
436
437 /* free curve path data 
438  * NOTE: frees the path itself!
439  */
440 void free_path(Path *path)
441 {
442         if(path->data) MEM_freeN(path->data);
443         MEM_freeN(path);
444 }
445
446 /* calculate a curve-deform path for a curve 
447  *      - only called from displist.c -> makeDispListCurveTypes
448  */
449 void calc_curvepath(Object *ob)
450 {
451         BevList *bl;
452         BevPoint *bevp, *bevpn, *bevpfirst, *bevplast;
453         PathPoint *pp;
454         Curve *cu;
455         Nurb *nu;
456         Path *path;
457         float *fp, *dist, *maxdist, xyz[3];
458         float fac, d=0, fac1, fac2;
459         int a, tot, cycl=0;
460         ListBase *nurbs;
461         
462         /* in a path vertices are with equal differences: path->len = number of verts */
463         /* NOW WITH BEVELCURVE!!! */
464         
465         if(ob==NULL || ob->type != OB_CURVE) return;
466         cu= ob->data;
467
468         nurbs= BKE_curve_nurbs(cu);
469         nu= nurbs->first;
470
471         if(cu->path) free_path(cu->path);
472         cu->path= NULL;
473         
474         bl= cu->bev.first;
475         if(bl==NULL || !bl->nr) return;
476
477         cu->path=path= MEM_callocN(sizeof(Path), "calc_curvepath");
478         
479         /* if POLY: last vertice != first vertice */
480         cycl= (bl->poly!= -1);
481         
482         if(cycl) tot= bl->nr;
483         else tot= bl->nr-1;
484         
485         path->len= tot+1;
486         /* exception: vector handle paths and polygon paths should be subdivided at least a factor resolu */
487         if(path->len<nu->resolu*SEGMENTSU(nu)) path->len= nu->resolu*SEGMENTSU(nu);
488         
489         dist= (float *)MEM_mallocN((tot+1)*4, "calcpathdist");
490
491                 /* all lengths in *dist */
492         bevp= bevpfirst= (BevPoint *)(bl+1);
493         fp= dist;
494         *fp= 0;
495         for(a=0; a<tot; a++) {
496                 fp++;
497                 if(cycl && a==tot-1)
498                         sub_v3_v3v3(xyz, bevpfirst->vec, bevp->vec);
499                 else
500                         sub_v3_v3v3(xyz, (bevp+1)->vec, bevp->vec);
501                 
502                 *fp= *(fp-1)+len_v3(xyz);
503                 bevp++;
504         }
505         
506         path->totdist= *fp;
507         
508                 /* the path verts  in path->data */
509                 /* now also with TILT value */
510         pp= path->data = (PathPoint *)MEM_callocN(sizeof(PathPoint)*4*path->len, "pathdata"); // XXX - why *4? - in 2.4x each element was 4 and the size was 16, so better leave for now - Campbell
511         
512         bevp= bevpfirst;
513         bevpn= bevp+1;
514         bevplast= bevpfirst + (bl->nr-1);
515         fp= dist+1;
516         maxdist= dist+tot;
517         fac= 1.0f/((float)path->len-1.0f);
518                 fac = fac * path->totdist;
519         
520         for(a=0; a<path->len; a++) {
521                 
522                 d= ((float)a)*fac;
523                 
524                 /* we're looking for location (distance) 'd' in the array */
525                 while((d>= *fp) && fp<maxdist) {
526                         fp++;
527                         if(bevp<bevplast) bevp++;
528                         bevpn= bevp+1;
529                         if(bevpn>bevplast) {
530                                 if(cycl) bevpn= bevpfirst;
531                                 else bevpn= bevplast;
532                         }
533                 }
534                 
535                 fac1= *(fp)- *(fp-1);
536                 fac2= *(fp)-d;
537                 fac1= fac2/fac1;
538                 fac2= 1.0f-fac1;
539                 
540                 interp_v3_v3v3(pp->vec, bevp->vec, bevpn->vec, fac2);
541                 pp->vec[3]= fac1*bevp->alfa + fac2*bevpn->alfa;
542                 pp->radius= fac1*bevp->radius + fac2*bevpn->radius;
543                 pp->weight= fac1*bevp->weight + fac2*bevpn->weight;
544                 interp_qt_qtqt(pp->quat, bevp->quat, bevpn->quat, fac2);
545                 normalize_qt(pp->quat);
546                 
547                 pp++;
548         }
549         
550         MEM_freeN(dist);
551 }
552
553
554 /* is this only used internally?*/
555 int interval_test(int min, int max, int p1, int cycl)
556 {
557         if(cycl) {
558                 if(p1 < min) 
559                         p1=  ((p1 -min) % (max-min+1)) + max+1;
560                 else if(p1 > max)
561                         p1=  ((p1 -min) % (max-min+1)) + min;
562         }
563         else {
564                 if(p1 < min) p1= min;
565                 else if(p1 > max) p1= max;
566         }
567         return p1;
568 }
569
570
571 /* calculate the deformation implied by the curve path at a given parametric position, and returns whether this operation succeeded 
572  *      - *vec needs FOUR items!
573  *      - ctime is normalized range <0-1>
574  */
575 int where_on_path(Object *ob, float ctime, float *vec, float *dir, float *quat, float *radius, float *weight)   /* returns OK */
576 {
577         Curve *cu;
578         Nurb *nu;
579         BevList *bl;
580         Path *path;
581         PathPoint *pp, *p0, *p1, *p2, *p3;
582         float fac;
583         float data[4];
584         int cycl=0, s0, s1, s2, s3;
585
586         if(ob==NULL || ob->type != OB_CURVE) return 0;
587         cu= ob->data;
588         if(cu->path==NULL || cu->path->data==NULL) {
589                 printf("no path!\n");
590                 return 0;
591         }
592         path= cu->path;
593         pp= path->data;
594         
595         /* test for cyclic */
596         bl= cu->bev.first;
597         if (!bl) return 0;
598         if (!bl->nr) return 0;
599         if(bl->poly> -1) cycl= 1;
600
601         ctime *= (path->len-1);
602         
603         s1= (int)floor(ctime);
604         fac= (float)(s1+1)-ctime;
605
606         /* path->len is corected for cyclic */
607         s0= interval_test(0, path->len-1-cycl, s1-1, cycl);
608         s1= interval_test(0, path->len-1-cycl, s1, cycl);
609         s2= interval_test(0, path->len-1-cycl, s1+1, cycl);
610         s3= interval_test(0, path->len-1-cycl, s1+2, cycl);
611
612         p0= pp + s0;
613         p1= pp + s1;
614         p2= pp + s2;
615         p3= pp + s3;
616
617         /* note, commented out for follow constraint */
618         //if(cu->flag & CU_FOLLOW) {
619
620                 key_curve_tangent_weights(1.0f-fac, data, KEY_BSPLINE);
621
622                 interp_v3_v3v3v3v3(dir, p0->vec, p1->vec, p2->vec, p3->vec, data);
623
624                 /* make compatible with vectoquat */
625                 negate_v3(dir);
626         //}
627         
628         nu= cu->nurb.first;
629
630         /* make sure that first and last frame are included in the vectors here  */
631         if(nu->type == CU_POLY) key_curve_position_weights(1.0f-fac, data, KEY_LINEAR);
632         else if(nu->type == CU_BEZIER) key_curve_position_weights(1.0f-fac, data, KEY_LINEAR);
633         else if(s0==s1 || p2==p3) key_curve_position_weights(1.0f-fac, data, KEY_CARDINAL);
634         else key_curve_position_weights(1.0f-fac, data, KEY_BSPLINE);
635
636         vec[0]= data[0]*p0->vec[0] + data[1]*p1->vec[0] + data[2]*p2->vec[0] + data[3]*p3->vec[0] ; /* X */
637         vec[1]= data[0]*p0->vec[1] + data[1]*p1->vec[1] + data[2]*p2->vec[1] + data[3]*p3->vec[1] ; /* Y */
638         vec[2]= data[0]*p0->vec[2] + data[1]*p1->vec[2] + data[2]*p2->vec[2] + data[3]*p3->vec[2] ; /* Z */
639         vec[3]= data[0]*p0->vec[3] + data[1]*p1->vec[3] + data[2]*p2->vec[3] + data[3]*p3->vec[3] ; /* Tilt, should not be needed since we have quat still used */
640         /* Need to verify the quat interpolation is correct - XXX */
641
642         if (quat) {
643                 //float totfac, q1[4], q2[4];
644
645                 /* checks for totfac are needed when 'fac' is 1.0 key_curve_position_weights can assign zero
646                  * to more then one index in data which can give divide by zero error */
647 /*
648                 totfac= data[0]+data[1];
649                 if(totfac>0.000001)     interp_qt_qtqt(q1, p0->quat, p1->quat, data[0] / totfac);
650                 else                            QUATCOPY(q1, p1->quat);
651
652                 normalize_qt(q1);
653
654                 totfac= data[2]+data[3];
655                 if(totfac>0.000001)     interp_qt_qtqt(q2, p2->quat, p3->quat, data[2] / totfac);
656                 else                            QUATCOPY(q1, p3->quat);
657                 normalize_qt(q2);
658
659                 totfac = data[0]+data[1]+data[2]+data[3];
660                 if(totfac>0.000001)     interp_qt_qtqt(quat, q1, q2, (data[0]+data[1]) / totfac);
661                 else                            QUATCOPY(quat, q2);
662                 normalize_qt(quat);
663                 */
664                 // XXX - find some way to make quat interpolation work correctly, above code fails in rare but nasty cases.
665                 QUATCOPY(quat, p1->quat);
666         }
667
668         if(radius)
669                 *radius= data[0]*p0->radius + data[1]*p1->radius + data[2]*p2->radius + data[3]*p3->radius;
670
671         if(weight)
672                 *weight= data[0]*p0->weight + data[1]*p1->weight + data[2]*p2->weight + data[3]*p3->weight;
673
674         return 1;
675 }
676
677 /* ******************************************************************** */
678 /* Dupli-Geometry */
679
680 static DupliObject *new_dupli_object(ListBase *lb, Object *ob, float mat[][4], int lay, int index, int type, int animated)
681 {
682         DupliObject *dob= MEM_callocN(sizeof(DupliObject), "dupliobject");
683         
684         BLI_addtail(lb, dob);
685         dob->ob= ob;
686         copy_m4_m4(dob->mat, mat);
687         copy_m4_m4(dob->omat, ob->obmat);
688         dob->origlay= ob->lay;
689         dob->index= index;
690         dob->type= type;
691         dob->animated= (type == OB_DUPLIGROUP) && animated;
692         ob->lay= lay;
693         
694         return dob;
695 }
696
697 static void group_duplilist(ListBase *lb, Scene *scene, Object *ob, int level, int animated)
698 {
699         DupliObject *dob;
700         Group *group;
701         GroupObject *go;
702         float mat[4][4], tmat[4][4];
703         
704         if(ob->dup_group==NULL) return;
705         group= ob->dup_group;
706         
707         /* simple preventing of too deep nested groups */
708         if(level>MAX_DUPLI_RECUR) return;
709         
710         /* handles animated groups, and */
711         /* we need to check update for objects that are not in scene... */
712         group_handle_recalc_and_update(scene, ob, group);
713         animated= animated || group_is_animated(ob, group);
714         
715         for(go= group->gobject.first; go; go= go->next) {
716                 /* note, if you check on layer here, render goes wrong... it still deforms verts and uses parent imat */
717                 if(go->ob!=ob) {
718                         
719                         /* Group Dupli Offset, should apply after everything else */
720                         if (group->dupli_ofs[0] || group->dupli_ofs[1] || group->dupli_ofs[2]) {
721                                 copy_m4_m4(tmat, go->ob->obmat);
722                                 sub_v3_v3v3(tmat[3], tmat[3], group->dupli_ofs);
723                                 mul_m4_m4m4(mat, tmat, ob->obmat);
724                         } else {
725                                 mul_m4_m4m4(mat, go->ob->obmat, ob->obmat);
726                         }
727                         
728                         dob= new_dupli_object(lb, go->ob, mat, ob->lay, 0, OB_DUPLIGROUP, animated);
729
730                         /* check the group instance and object layers match, also that the object visible flags are ok. */
731                         if(     (dob->origlay & group->layer)==0 ||
732                                 (G.rendering==0 && dob->ob->restrictflag & OB_RESTRICT_VIEW) ||
733                                 (G.rendering && dob->ob->restrictflag & OB_RESTRICT_RENDER)
734                         ) {
735                                 dob->no_draw= 1;
736                         }
737                         else {
738                                 dob->no_draw= 0;
739                         }
740
741                         if(go->ob->transflag & OB_DUPLI) {
742                                 copy_m4_m4(dob->ob->obmat, dob->mat);
743                                 object_duplilist_recursive(&group->id, scene, go->ob, lb, ob->obmat, level+1, animated);
744                                 copy_m4_m4(dob->ob->obmat, dob->omat);
745                         }
746                 }
747         }
748 }
749
750 static void frames_duplilist(ListBase *lb, Scene *scene, Object *ob, int level, int animated)
751 {
752         extern int enable_cu_speed;     /* object.c */
753         Object copyob;
754         DupliObject *dob;
755         int cfrao, ok;
756         
757         /* simple preventing of too deep nested groups */
758         if(level>MAX_DUPLI_RECUR) return;
759         
760         cfrao= scene->r.cfra;
761         if(ob->parent==NULL && ob->constraints.first==NULL) return;
762
763         if(ob->transflag & OB_DUPLINOSPEED) enable_cu_speed= 0;
764         copyob= *ob;    /* store transform info */
765
766         for(scene->r.cfra= ob->dupsta; scene->r.cfra<=ob->dupend; scene->r.cfra++) {
767
768                 ok= 1;
769                 if(ob->dupoff) {
770                         ok= scene->r.cfra - ob->dupsta;
771                         ok= ok % (ob->dupon+ob->dupoff);
772                         if(ok < ob->dupon) ok= 1;
773                         else ok= 0;
774                 }
775                 if(ok) {
776 #if 0 // XXX old animation system
777                         do_ob_ipo(scene, ob);
778 #endif // XXX old animation system
779                         where_is_object_time(scene, ob, (float)scene->r.cfra);
780                         dob= new_dupli_object(lb, ob, ob->obmat, ob->lay, scene->r.cfra, OB_DUPLIFRAMES, animated);
781                         copy_m4_m4(dob->omat, copyob.obmat);
782                 }
783         }
784
785         *ob= copyob;    /* restore transform info */
786         scene->r.cfra= cfrao;
787         enable_cu_speed= 1;
788 }
789
790 typedef struct vertexDupliData {
791         ID *id; /* scene or group, for recursive loops */
792         int level;
793         int animated;
794         ListBase *lb;
795         float pmat[4][4];
796         float obmat[4][4]; /* Only used for dupliverts inside dupligroups, where the ob->obmat is modified */
797         Scene *scene;
798         Object *ob, *par;
799         float (*orco)[3];
800 } vertexDupliData;
801
802 /* ------------- */
803
804 static void vertex_dupli__mapFunc(void *userData, int index, float *co, float *no_f, short *no_s)
805 {
806         DupliObject *dob;
807         vertexDupliData *vdd= userData;
808         float vec[3], q2[4], mat[3][3], tmat[4][4], obmat[4][4];
809         
810         mul_v3_m4v3(vec, vdd->pmat, co);
811         sub_v3_v3(vec, vdd->pmat[3]);
812         add_v3_v3(vec, vdd->obmat[3]);
813         
814         copy_m4_m4(obmat, vdd->obmat);
815         VECCOPY(obmat[3], vec);
816         
817         if(vdd->par->transflag & OB_DUPLIROT) {
818                 if(no_f) {
819                         vec[0]= -no_f[0]; vec[1]= -no_f[1]; vec[2]= -no_f[2];
820                 }
821                 else if(no_s) {
822                         vec[0]= -no_s[0]; vec[1]= -no_s[1]; vec[2]= -no_s[2];
823                 }
824                 
825                 vec_to_quat( q2,vec, vdd->ob->trackflag, vdd->ob->upflag);
826                 
827                 quat_to_mat3( mat,q2);
828                 copy_m4_m4(tmat, obmat);
829                 mul_m4_m4m3(obmat, tmat, mat);
830         }
831         dob= new_dupli_object(vdd->lb, vdd->ob, obmat, vdd->par->lay, index, OB_DUPLIVERTS, vdd->animated);
832         if(vdd->orco)
833                 VECCOPY(dob->orco, vdd->orco[index]);
834         
835         if(vdd->ob->transflag & OB_DUPLI) {
836                 float tmpmat[4][4];
837                 copy_m4_m4(tmpmat, vdd->ob->obmat);
838                 copy_m4_m4(vdd->ob->obmat, obmat); /* pretend we are really this mat */
839                 object_duplilist_recursive((ID *)vdd->id, vdd->scene, vdd->ob, vdd->lb, obmat, vdd->level+1, vdd->animated);
840                 copy_m4_m4(vdd->ob->obmat, tmpmat);
841         }
842 }
843
844 static void vertex_duplilist(ListBase *lb, ID *id, Scene *scene, Object *par, float par_space_mat[][4], int level, int animated)
845 {
846         Object *ob, *ob_iter;
847         Mesh *me= par->data;
848         Base *base = NULL;
849         DerivedMesh *dm;
850         vertexDupliData vdd;
851         Scene *sce = NULL;
852         Group *group = NULL;
853         GroupObject * go = NULL;
854         EditMesh *em;
855         float vec[3], no[3], pmat[4][4];
856         int lay, totvert, a, oblay;
857         
858         copy_m4_m4(pmat, par->obmat);
859         
860         /* simple preventing of too deep nested groups */
861         if(level>MAX_DUPLI_RECUR) return;
862         
863         em = BKE_mesh_get_editmesh(me);
864         
865         if(em) {
866                 dm= editmesh_get_derived_cage(scene, par, em, CD_MASK_BAREMESH);
867                 BKE_mesh_end_editmesh(me, em);
868         } else
869                 dm= mesh_get_derived_deform(scene, par, CD_MASK_BAREMESH);
870         
871         if(G.rendering) {
872                 vdd.orco= (float(*)[3])get_mesh_orco_verts(par);
873                 transform_mesh_orco_verts(me, vdd.orco, me->totvert, 0);
874         }
875         else
876                 vdd.orco= NULL;
877         
878         totvert = dm->getNumVerts(dm);
879
880         /* having to loop on scene OR group objects is NOT FUN */
881         if (GS(id->name) == ID_SCE) {
882                 sce = (Scene *)id;
883                 lay= sce->lay;
884                 base= sce->base.first;
885         } else {
886                 group = (Group *)id;
887                 lay= group->layer;
888                 go = group->gobject.first;
889         }
890         
891         /* Start looping on Scene OR Group objects */
892         while (base || go) { 
893                 if (sce) {
894                         ob_iter= base->object;
895                         oblay = base->lay;
896                 } else {
897                         ob_iter= go->ob;
898                         oblay = ob_iter->lay;
899                 }
900                 
901                 if (lay & oblay && scene->obedit!=ob_iter) {
902                         ob=ob_iter->parent;
903                         while(ob) {
904                                 if(ob==par) {
905                                         ob = ob_iter;
906         /* End Scene/Group object loop, below is generic */
907                                         
908                                         
909                                         /* par_space_mat - only used for groups so we can modify the space dupli's are in
910                                            when par_space_mat is NULL ob->obmat can be used instead of ob__obmat
911                                         */
912                                         if(par_space_mat)
913                                                 mul_m4_m4m4(vdd.obmat, ob->obmat, par_space_mat);
914                                         else
915                                                 copy_m4_m4(vdd.obmat, ob->obmat);
916
917                                         vdd.id= id;
918                                         vdd.level= level;
919                                         vdd.animated= animated;
920                                         vdd.lb= lb;
921                                         vdd.ob= ob;
922                                         vdd.scene= scene;
923                                         vdd.par= par;
924                                         copy_m4_m4(vdd.pmat, pmat);
925                                         
926                                         /* mballs have a different dupli handling */
927                                         if(ob->type!=OB_MBALL) ob->flag |= OB_DONE;     /* doesnt render */
928
929                                         if(me->edit_mesh) {
930                                                 dm->foreachMappedVert(dm, vertex_dupli__mapFunc, (void*) &vdd);
931                                         }
932                                         else {
933                                                 for(a=0; a<totvert; a++) {
934                                                         dm->getVertCo(dm, a, vec);
935                                                         dm->getVertNo(dm, a, no);
936                                                         
937                                                         vertex_dupli__mapFunc(&vdd, a, vec, no, NULL);
938                                                 }
939                                         }
940                                         
941                                         break;
942                                 }
943                                 ob= ob->parent;
944                         }
945                 }
946                 if (sce)        base= base->next;       /* scene loop */
947                 else            go= go->next;           /* group loop */
948         }
949
950         if(vdd.orco)
951                 MEM_freeN(vdd.orco);
952         dm->release(dm);
953 }
954
955 static void face_duplilist(ListBase *lb, ID *id, Scene *scene, Object *par, float par_space_mat[][4], int level, int animated)
956 {
957         Object *ob, *ob_iter;
958         Base *base = NULL;
959         DupliObject *dob;
960         DerivedMesh *dm;
961         Mesh *me= par->data;
962         MTFace *mtface;
963         MFace *mface;
964         MVert *mvert;
965         float pmat[4][4], imat[3][3], (*orco)[3] = NULL, w;
966         int lay, oblay, totface, a;
967         Scene *sce = NULL;
968         Group *group = NULL;
969         GroupObject *go = NULL;
970         EditMesh *em;
971         float ob__obmat[4][4]; /* needed for groups where the object matrix needs to be modified */
972         
973         /* simple preventing of too deep nested groups */
974         if(level>MAX_DUPLI_RECUR) return;
975         
976         copy_m4_m4(pmat, par->obmat);
977         
978         em = BKE_mesh_get_editmesh(me);
979         if(em) {
980                 int totvert;
981                 
982                 dm= editmesh_get_derived_cage(scene, par, em, CD_MASK_BAREMESH);
983                 
984                 totface= dm->getNumFaces(dm);
985                 mface= MEM_mallocN(sizeof(MFace)*totface, "mface temp");
986                 dm->copyFaceArray(dm, mface);
987                 totvert= dm->getNumVerts(dm);
988                 mvert= MEM_mallocN(sizeof(MVert)*totvert, "mvert temp");
989                 dm->copyVertArray(dm, mvert);
990
991                 BKE_mesh_end_editmesh(me, em);
992         }
993         else {
994                 dm = mesh_get_derived_deform(scene, par, CD_MASK_BAREMESH);
995                 
996                 totface= dm->getNumFaces(dm);
997                 mface= dm->getFaceArray(dm);
998                 mvert= dm->getVertArray(dm);
999         }
1000
1001         if(G.rendering) {
1002
1003                 orco= (float(*)[3])get_mesh_orco_verts(par);
1004                 transform_mesh_orco_verts(me, orco, me->totvert, 0);
1005                 mtface= me->mtface;
1006         }
1007         else {
1008                 orco= NULL;
1009                 mtface= NULL;
1010         }
1011         
1012         /* having to loop on scene OR group objects is NOT FUN */
1013         if (GS(id->name) == ID_SCE) {
1014                 sce = (Scene *)id;
1015                 lay= sce->lay;
1016                 base= sce->base.first;
1017         } else {
1018                 group = (Group *)id;
1019                 lay= group->layer;
1020                 go = group->gobject.first;
1021         }
1022         
1023         /* Start looping on Scene OR Group objects */
1024         while (base || go) { 
1025                 if (sce) {
1026                         ob_iter= base->object;
1027                         oblay = base->lay;
1028                 } else {
1029                         ob_iter= go->ob;
1030                         oblay = ob_iter->lay;
1031                 }
1032                 
1033                 if (lay & oblay && scene->obedit!=ob_iter) {
1034                         ob=ob_iter->parent;
1035                         while(ob) {
1036                                 if(ob==par) {
1037                                         ob = ob_iter;
1038         /* End Scene/Group object loop, below is generic */
1039                                         
1040                                         /* par_space_mat - only used for groups so we can modify the space dupli's are in
1041                                            when par_space_mat is NULL ob->obmat can be used instead of ob__obmat
1042                                         */
1043                                         if(par_space_mat)
1044                                                 mul_m4_m4m4(ob__obmat, ob->obmat, par_space_mat);
1045                                         else
1046                                                 copy_m4_m4(ob__obmat, ob->obmat);
1047                                         
1048                                         copy_m3_m4(imat, ob->parentinv);
1049                                                 
1050                                         /* mballs have a different dupli handling */
1051                                         if(ob->type!=OB_MBALL) ob->flag |= OB_DONE;     /* doesnt render */
1052
1053                                         for(a=0; a<totface; a++) {
1054                                                 int mv1 = mface[a].v1;
1055                                                 int mv2 = mface[a].v2;
1056                                                 int mv3 = mface[a].v3;
1057                                                 int mv4 = mface[a].v4;
1058                                                 float *v1= mvert[mv1].co;
1059                                                 float *v2= mvert[mv2].co;
1060                                                 float *v3= mvert[mv3].co;
1061                                                 float *v4= (mv4)? mvert[mv4].co: NULL;
1062                                                 float cent[3], quat[4], mat[3][3], mat3[3][3], tmat[4][4], obmat[4][4];
1063
1064                                                 /* translation */
1065                                                 if(v4)
1066                                                         cent_quad_v3(cent, v1, v2, v3, v4);
1067                                                 else
1068                                                         cent_tri_v3(cent, v1, v2, v3);
1069                                                 mul_m4_v3(pmat, cent);
1070                                                 
1071                                                 sub_v3_v3v3(cent, cent, pmat[3]);
1072                                                 add_v3_v3(cent, ob__obmat[3]);
1073                                                 
1074                                                 copy_m4_m4(obmat, ob__obmat);
1075                                                 
1076                                                 VECCOPY(obmat[3], cent);
1077                                                 
1078                                                 /* rotation */
1079                                                 tri_to_quat( quat,v1, v2, v3);
1080                                                 quat_to_mat3( mat,quat);
1081                                                 
1082                                                 /* scale */
1083                                                 if(par->transflag & OB_DUPLIFACES_SCALE) {
1084                                                         float size= v4? area_quad_v3(v1, v2, v3, v4): area_tri_v3(v1, v2, v3);
1085                                                         size= sqrt(size) * par->dupfacesca;
1086                                                         mul_m3_fl(mat, size);
1087                                                 }
1088                                                 
1089                                                 copy_m3_m3(mat3, mat);
1090                                                 mul_m3_m3m3(mat, imat, mat3);
1091                                                 
1092                                                 copy_m4_m4(tmat, obmat);
1093                                                 mul_m4_m4m3(obmat, tmat, mat);
1094                                                 
1095                                                 dob= new_dupli_object(lb, ob, obmat, par->lay, a, OB_DUPLIFACES, animated);
1096                                                 if(G.rendering) {
1097                                                         w= (mv4)? 0.25f: 1.0f/3.0f;
1098
1099                                                         if(orco) {
1100                                                                 VECADDFAC(dob->orco, dob->orco, orco[mv1], w);
1101                                                                 VECADDFAC(dob->orco, dob->orco, orco[mv2], w);
1102                                                                 VECADDFAC(dob->orco, dob->orco, orco[mv3], w);
1103                                                                 if(mv4)
1104                                                                         VECADDFAC(dob->orco, dob->orco, orco[mv4], w);
1105                                                         }
1106
1107                                                         if(mtface) {
1108                                                                 dob->uv[0] += w*mtface[a].uv[0][0];
1109                                                                 dob->uv[1] += w*mtface[a].uv[0][1];
1110                                                                 dob->uv[0] += w*mtface[a].uv[1][0];
1111                                                                 dob->uv[1] += w*mtface[a].uv[1][1];
1112                                                                 dob->uv[0] += w*mtface[a].uv[2][0];
1113                                                                 dob->uv[1] += w*mtface[a].uv[2][1];
1114
1115                                                                 if(mv4) {
1116                                                                         dob->uv[0] += w*mtface[a].uv[3][0];
1117                                                                         dob->uv[1] += w*mtface[a].uv[3][1];
1118                                                                 }
1119                                                         }
1120                                                 }
1121                                                 
1122                                                 if(ob->transflag & OB_DUPLI) {
1123                                                         float tmpmat[4][4];
1124                                                         copy_m4_m4(tmpmat, ob->obmat);
1125                                                         copy_m4_m4(ob->obmat, obmat); /* pretend we are really this mat */
1126                                                         object_duplilist_recursive((ID *)id, scene, ob, lb, ob->obmat, level+1, animated);
1127                                                         copy_m4_m4(ob->obmat, tmpmat);
1128                                                 }
1129                                         }
1130                                         
1131                                         break;
1132                                 }
1133                                 ob= ob->parent;
1134                         }
1135                 }
1136                 if (sce)        base= base->next;       /* scene loop */
1137                 else            go= go->next;           /* group loop */
1138         }
1139         
1140         if(em) {
1141                 MEM_freeN(mface);
1142                 MEM_freeN(mvert);
1143         }
1144
1145         if(orco)
1146                 MEM_freeN(orco);
1147         
1148         dm->release(dm);
1149 }
1150
1151 static void new_particle_duplilist(ListBase *lb, ID *id, Scene *scene, Object *par, float par_space_mat[][4], ParticleSystem *psys, int level, int animated)
1152 {
1153         GroupObject *go;
1154         Object *ob=0, **oblist=0, obcopy, *obcopylist=0;
1155         DupliObject *dob;
1156         ParticleDupliWeight *dw;
1157         ParticleSimulationData sim = {scene, par, psys, psys_get_modifier(par, psys)};
1158         ParticleSettings *part;
1159         ParticleData *pa;
1160         ChildParticle *cpa=0;
1161         ParticleKey state;
1162         ParticleCacheKey *cache;
1163         float ctime, pa_time, scale = 1.0f;
1164         float tmat[4][4], mat[4][4], pamat[4][4], vec[3], size=0.0;
1165         float (*obmat)[4], (*oldobmat)[4];
1166         int lay, a, b, counter, hair = 0;
1167         int totpart, totchild, totgroup=0, pa_num;
1168
1169         if(psys==0) return;
1170         
1171         /* simple preventing of too deep nested groups */
1172         if(level>MAX_DUPLI_RECUR) return;
1173         
1174         part=psys->part;
1175
1176         if(part==0)
1177                 return;
1178
1179         if(!psys_check_enabled(par, psys))
1180                 return;
1181         
1182         ctime = bsystem_time(scene, par, (float)scene->r.cfra, 0.0);
1183
1184         totpart = psys->totpart;
1185         totchild = psys->totchild;
1186
1187         BLI_srandom(31415926 + psys->seed);
1188         
1189         lay= scene->lay;
1190         if((psys->renderdata || part->draw_as==PART_DRAW_REND) && ELEM(part->ren_as, PART_DRAW_OB, PART_DRAW_GR)) {
1191
1192                 /* first check for loops (particle system object used as dupli object) */
1193                 if(part->ren_as == PART_DRAW_OB) {
1194                         if(ELEM(part->dup_ob, NULL, par))
1195                                 return;
1196                 }
1197                 else { /*PART_DRAW_GR */
1198                         if(part->dup_group == NULL || part->dup_group->gobject.first == NULL)
1199                                 return;
1200
1201                         for(go=part->dup_group->gobject.first; go; go=go->next)
1202                                 if(go->ob == par)
1203                                         return;
1204                 }
1205
1206                 /* if we have a hair particle system, use the path cache */
1207                 if(part->type == PART_HAIR) {
1208                         if(psys->flag & PSYS_HAIR_DONE)
1209                                 hair= (totchild == 0 || psys->childcache) && psys->pathcache;
1210                         if(!hair)
1211                                 return;
1212                         
1213                         /* we use cache, update totchild according to cached data */
1214                         totchild = psys->totchildcache;
1215                         totpart = psys->totcached;
1216                 }
1217
1218                 psys_check_group_weights(part);
1219
1220                 psys->lattice = psys_get_lattice(&sim);
1221
1222                 /* gather list of objects or single object */
1223                 if(part->ren_as==PART_DRAW_GR) {
1224                         group_handle_recalc_and_update(scene, par, part->dup_group);
1225
1226                         if(part->draw & PART_DRAW_COUNT_GR) {
1227                                 for(dw=part->dupliweights.first; dw; dw=dw->next)
1228                                         totgroup += dw->count;
1229                         }
1230                         else {
1231                                 for(go=part->dup_group->gobject.first; go; go=go->next)
1232                                         totgroup++;
1233                         }
1234
1235                         /* we also copy the actual objects to restore afterwards, since
1236                          * where_is_object_time will change the object which breaks transform */
1237                         oblist = MEM_callocN(totgroup*sizeof(Object *), "dupgroup object list");
1238                         obcopylist = MEM_callocN(totgroup*sizeof(Object), "dupgroup copy list");
1239
1240                         
1241                         if(part->draw & PART_DRAW_COUNT_GR && totgroup) {
1242                                 dw = part->dupliweights.first;
1243
1244                                 for(a=0; a<totgroup; dw=dw->next) {
1245                                         for(b=0; b<dw->count; b++, a++) {
1246                                                 oblist[a] = dw->ob;
1247                                                 obcopylist[a] = *dw->ob;
1248                                         }
1249                                 }
1250                         }
1251                         else {
1252                                 go = part->dup_group->gobject.first;
1253                                 for(a=0; a<totgroup; a++, go=go->next) {
1254                                         oblist[a] = go->ob;
1255                                         obcopylist[a] = *go->ob;
1256                                 }
1257                         }
1258                 }
1259                 else {
1260                         ob = part->dup_ob;
1261                         obcopy = *ob;
1262                 }
1263
1264                 if(totchild==0 || part->draw & PART_DRAW_PARENT)
1265                         a = 0;
1266                 else
1267                         a = totpart;
1268
1269                 for(pa=psys->particles,counter=0; a<totpart+totchild; a++,pa++,counter++) {
1270                         if(a<totpart) {
1271                                 /* handle parent particle */
1272                                 if(pa->flag & (PARS_UNEXIST+PARS_NO_DISP))
1273                                         continue;
1274
1275                                 pa_num = pa->num;
1276                                 pa_time = pa->time;
1277                                 size = pa->size;
1278                         }
1279                         else {
1280                                 /* handle child particle */
1281                                 cpa = &psys->child[a - totpart];
1282
1283                                 pa_num = a;
1284                                 pa_time = psys->particles[cpa->parent].time;
1285                                 size = psys_get_child_size(psys, cpa, ctime, 0);
1286                         }
1287
1288                         if(part->ren_as==PART_DRAW_GR) {
1289                                 /* for groups, pick the object based on settings */
1290                                 if(part->draw&PART_DRAW_RAND_GR)
1291                                         b= BLI_rand() % totgroup;
1292                                 else if(part->from==PART_FROM_PARTICLE)
1293                                         b= pa_num % totgroup;
1294                                 else
1295                                         b= a % totgroup;
1296
1297                                 ob = oblist[b];
1298                                 obmat = oblist[b]->obmat;
1299                                 oldobmat = obcopylist[b].obmat;
1300                         }
1301                         else {
1302                                 obmat= ob->obmat;
1303                                 oldobmat= obcopy.obmat;
1304                         }
1305
1306                         if(hair) {
1307                                 /* hair we handle separate and compute transform based on hair keys */
1308                                 if(a < totpart) {
1309                                         cache = psys->pathcache[a];
1310                                         psys_get_dupli_path_transform(&sim, pa, 0, cache, pamat, &scale);
1311                                 }
1312                                 else {
1313                                         cache = psys->childcache[a-totpart];
1314                                         psys_get_dupli_path_transform(&sim, 0, cpa, cache, pamat, &scale);
1315                                 }
1316
1317                                 VECCOPY(pamat[3], cache->co);
1318                                 pamat[3][3]= 1.0f;
1319                                 
1320                         }
1321                         else {
1322                                 /* first key */
1323                                 state.time = ctime;
1324                                 if(psys_get_particle_state(&sim, a, &state, 0) == 0)
1325                                         continue;
1326
1327                                 quat_to_mat4( pamat,state.rot);
1328                                 VECCOPY(pamat[3], state.co);
1329                                 pamat[3][3]= 1.0f;
1330                         }
1331
1332                         if(part->ren_as==PART_DRAW_GR && psys->part->draw & PART_DRAW_WHOLE_GR) {
1333                                 for(go= part->dup_group->gobject.first, b=0; go; go= go->next, b++) {
1334                                         mul_m4_m4m4(tmat, oblist[b]->obmat, pamat);
1335                                         mul_mat3_m4_fl(tmat, size*scale);
1336                                         if(par_space_mat)
1337                                                 mul_m4_m4m4(mat, tmat, par_space_mat);
1338                                         else
1339                                                 copy_m4_m4(mat, tmat);
1340
1341                                         dob= new_dupli_object(lb, go->ob, mat, par->lay, counter, OB_DUPLIPARTS, animated);
1342                                         copy_m4_m4(dob->omat, obcopylist[b].obmat);
1343                                         if(G.rendering)
1344                                                 psys_get_dupli_texture(par, part, sim.psmd, pa, cpa, dob->uv, dob->orco);
1345                                 }
1346                         }
1347                         else {
1348                                 /* to give ipos in object correct offset */
1349                                 where_is_object_time(scene, ob, ctime-pa_time);
1350
1351                                 VECCOPY(vec, obmat[3]);
1352                                 obmat[3][0] = obmat[3][1] = obmat[3][2] = 0.0f;
1353                                 
1354                                 copy_m4_m4(mat, pamat);
1355
1356                                 mul_m4_m4m4(tmat, obmat, mat);
1357                                 mul_mat3_m4_fl(tmat, size*scale);
1358
1359                                 if(part->draw & PART_DRAW_GLOBAL_OB)
1360                                         VECADD(tmat[3], tmat[3], vec);
1361
1362                                 if(par_space_mat)
1363                                         mul_m4_m4m4(mat, tmat, par_space_mat);
1364                                 else
1365                                         copy_m4_m4(mat, tmat);
1366
1367                                 dob= new_dupli_object(lb, ob, mat, ob->lay, counter, OB_DUPLIPARTS, animated);
1368                                 copy_m4_m4(dob->omat, oldobmat);
1369                                 if(G.rendering)
1370                                         psys_get_dupli_texture(par, part, sim.psmd, pa, cpa, dob->uv, dob->orco);
1371                         }
1372                 }
1373
1374                 /* restore objects since they were changed in where_is_object_time */
1375                 if(part->ren_as==PART_DRAW_GR) {
1376                         for(a=0; a<totgroup; a++)
1377                                 *(oblist[a])= obcopylist[a];
1378                 }
1379                 else
1380                         *ob= obcopy;
1381         }
1382
1383         /* clean up */
1384         if(oblist)
1385                 MEM_freeN(oblist);
1386         if(obcopylist)
1387                 MEM_freeN(obcopylist);
1388
1389         if(psys->lattice) {
1390                 end_latt_deform(psys->lattice);
1391                 psys->lattice = NULL;
1392         }
1393 }
1394
1395 static Object *find_family_object(Object **obar, char *family, char ch)
1396 {
1397         Object *ob;
1398         int flen;
1399         
1400         if( obar[(int)ch] ) return obar[(int)ch];
1401         
1402         flen= strlen(family);
1403         
1404         ob= G.main->object.first;
1405         while(ob) {
1406                 if( ob->id.name[flen+2]==ch ) {
1407                         if( strncmp(ob->id.name+2, family, flen)==0 ) break;
1408                 }
1409                 ob= ob->id.next;
1410         }
1411         
1412         obar[(int)ch]= ob;
1413         
1414         return ob;
1415 }
1416
1417
1418 static void font_duplilist(ListBase *lb, Scene *scene, Object *par, int level, int animated)
1419 {
1420         Object *ob, *obar[256];
1421         Curve *cu;
1422         struct chartrans *ct, *chartransdata;
1423         float vec[3], obmat[4][4], pmat[4][4], fsize, xof, yof;
1424         int slen, a;
1425         
1426         /* simple preventing of too deep nested groups */
1427         if(level>MAX_DUPLI_RECUR) return;
1428         
1429         copy_m4_m4(pmat, par->obmat);
1430         
1431         /* in par the family name is stored, use this to find the other objects */
1432         
1433         chartransdata= BKE_text_to_curve(scene, par, FO_DUPLI);
1434         if(chartransdata==0) return;
1435         
1436         memset(obar, 0, 256*sizeof(void *));
1437         
1438         cu= par->data;
1439         slen= strlen(cu->str);
1440         fsize= cu->fsize;
1441         xof= cu->xof;
1442         yof= cu->yof;
1443         
1444         ct= chartransdata;
1445         
1446         for(a=0; a<slen; a++, ct++) {
1447                 
1448                 ob= find_family_object(obar, cu->family, cu->str[a]);
1449                 if(ob) {
1450                         vec[0]= fsize*(ct->xof - xof);
1451                         vec[1]= fsize*(ct->yof - yof);
1452                         vec[2]= 0.0;
1453                         
1454                         mul_m4_v3(pmat, vec);
1455                         
1456                         copy_m4_m4(obmat, par->obmat);
1457                         VECCOPY(obmat[3], vec);
1458                         
1459                         new_dupli_object(lb, ob, obmat, par->lay, a, OB_DUPLIVERTS, animated);
1460                 }
1461         }
1462         
1463         MEM_freeN(chartransdata);
1464 }
1465
1466 /* ------------- */
1467
1468 static void object_duplilist_recursive(ID *id, Scene *scene, Object *ob, ListBase *duplilist, float par_space_mat[][4], int level, int animated)
1469 {       
1470         if((ob->transflag & OB_DUPLI)==0)
1471                 return;
1472         
1473         /* Should the dupli's be generated for this object? - Respect restrict flags */
1474         if (G.rendering) {
1475                 if (ob->restrictflag & OB_RESTRICT_RENDER) {
1476                         return;
1477                 }
1478         } else {
1479                 if (ob->restrictflag & OB_RESTRICT_VIEW) {
1480                         return;
1481                 }
1482         }
1483
1484         if(ob->transflag & OB_DUPLIPARTS) {
1485                 ParticleSystem *psys = ob->particlesystem.first;
1486                 for(; psys; psys=psys->next)
1487                         new_particle_duplilist(duplilist, id, scene, ob, par_space_mat, psys, level+1, animated);
1488         }
1489         else if(ob->transflag & OB_DUPLIVERTS) {
1490                 if(ob->type==OB_MESH) {
1491                         vertex_duplilist(duplilist, id, scene, ob, par_space_mat, level+1, animated);
1492                 }
1493                 else if(ob->type==OB_FONT) {
1494                         if (GS(id->name)==ID_SCE) { /* TODO - support dupligroups */
1495                                 font_duplilist(duplilist, scene, ob, level+1, animated);
1496                         }
1497                 }
1498         }
1499         else if(ob->transflag & OB_DUPLIFACES) {
1500                 if(ob->type==OB_MESH)
1501                         face_duplilist(duplilist, id, scene, ob, par_space_mat, level+1, animated);
1502         }
1503         else if(ob->transflag & OB_DUPLIFRAMES) {
1504                 if (GS(id->name)==ID_SCE) { /* TODO - support dupligroups */
1505                         frames_duplilist(duplilist, scene, ob, level+1, animated);
1506                 }
1507         } else if(ob->transflag & OB_DUPLIGROUP) {
1508                 DupliObject *dob;
1509                 
1510                 group_duplilist(duplilist, scene, ob, level+1, animated); /* now recursive */
1511
1512                 if (level==0) {
1513                         for(dob= duplilist->first; dob; dob= dob->next)
1514                                 if(dob->type == OB_DUPLIGROUP)
1515                                         copy_m4_m4(dob->ob->obmat, dob->mat);
1516                 }
1517         }
1518 }
1519
1520 /* Returns a list of DupliObject
1521  * note; group dupli's already set transform matrix. see note in group_duplilist() */
1522 ListBase *object_duplilist(Scene *sce, Object *ob)
1523 {
1524         ListBase *duplilist= MEM_mallocN(sizeof(ListBase), "duplilist");
1525         duplilist->first= duplilist->last= NULL;
1526         object_duplilist_recursive((ID *)sce, sce, ob, duplilist, NULL, 0, 0);
1527         return duplilist;
1528 }
1529
1530 void free_object_duplilist(ListBase *lb)
1531 {
1532         DupliObject *dob;
1533         
1534         /* loop in reverse order, if object is instanced multiple times
1535            the original layer may not really be original otherwise, proper
1536            solution is more complicated */
1537         for(dob= lb->last; dob; dob= dob->prev) {
1538                 dob->ob->lay= dob->origlay;
1539                 copy_m4_m4(dob->ob->obmat, dob->omat);
1540         }
1541         
1542         BLI_freelistN(lb);
1543         MEM_freeN(lb);
1544 }
1545
1546 int count_duplilist(Object *ob)
1547 {
1548         if(ob->transflag & OB_DUPLI) {
1549                 if(ob->transflag & OB_DUPLIVERTS) {
1550                         if(ob->type==OB_MESH) {
1551                                 if(ob->transflag & OB_DUPLIVERTS) {
1552                                         ParticleSystem *psys = ob->particlesystem.first;
1553                                         int pdup=0;
1554
1555                                         for(; psys; psys=psys->next)
1556                                                 pdup += psys->totpart;
1557
1558                                         if(pdup==0){
1559                                                 Mesh *me= ob->data;
1560                                                 return me->totvert;
1561                                         }
1562                                         else
1563                                                 return pdup;
1564                                 }
1565                         }
1566                 }
1567                 else if(ob->transflag & OB_DUPLIFRAMES) {
1568                         int tot= ob->dupend - ob->dupsta; 
1569                         tot/= (ob->dupon+ob->dupoff);
1570                         return tot*ob->dupon;
1571                 }
1572         }
1573         return 1;
1574 }