use unsigned int for all layers.
[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                 totfac= data[0]+data[3];
646                 if(totfac>FLT_EPSILON)  interp_qt_qtqt(q1, p0->quat, p3->quat, data[3] / totfac);
647                 else                                    QUATCOPY(q1, p1->quat);
648
649                 totfac= data[1]+data[2];
650                 if(totfac>FLT_EPSILON)  interp_qt_qtqt(q2, p1->quat, p2->quat, data[2] / totfac);
651                 else                                    QUATCOPY(q2, p3->quat);
652
653                 totfac = data[0]+data[1]+data[2]+data[3];
654                 if(totfac>FLT_EPSILON)  interp_qt_qtqt(quat, q1, q2, (data[1]+data[2]) / totfac);
655                 else                                    QUATCOPY(quat, q2);
656         }
657
658         if(radius)
659                 *radius= data[0]*p0->radius + data[1]*p1->radius + data[2]*p2->radius + data[3]*p3->radius;
660
661         if(weight)
662                 *weight= data[0]*p0->weight + data[1]*p1->weight + data[2]*p2->weight + data[3]*p3->weight;
663
664         return 1;
665 }
666
667 /* ******************************************************************** */
668 /* Dupli-Geometry */
669
670 static DupliObject *new_dupli_object(ListBase *lb, Object *ob, float mat[][4], int lay, int index, int type, int animated)
671 {
672         DupliObject *dob= MEM_callocN(sizeof(DupliObject), "dupliobject");
673         
674         BLI_addtail(lb, dob);
675         dob->ob= ob;
676         copy_m4_m4(dob->mat, mat);
677         copy_m4_m4(dob->omat, ob->obmat);
678         dob->origlay= ob->lay;
679         dob->index= index;
680         dob->type= type;
681         dob->animated= (type == OB_DUPLIGROUP) && animated;
682         ob->lay= lay;
683         
684         return dob;
685 }
686
687 static void group_duplilist(ListBase *lb, Scene *scene, Object *ob, int level, int animated)
688 {
689         DupliObject *dob;
690         Group *group;
691         GroupObject *go;
692         float mat[4][4], tmat[4][4];
693         
694         if(ob->dup_group==NULL) return;
695         group= ob->dup_group;
696         
697         /* simple preventing of too deep nested groups */
698         if(level>MAX_DUPLI_RECUR) return;
699         
700         /* handles animated groups, and */
701         /* we need to check update for objects that are not in scene... */
702         group_handle_recalc_and_update(scene, ob, group);
703         animated= animated || group_is_animated(ob, group);
704         
705         for(go= group->gobject.first; go; go= go->next) {
706                 /* note, if you check on layer here, render goes wrong... it still deforms verts and uses parent imat */
707                 if(go->ob!=ob) {
708                         
709                         /* Group Dupli Offset, should apply after everything else */
710                         if (group->dupli_ofs[0] || group->dupli_ofs[1] || group->dupli_ofs[2]) {
711                                 copy_m4_m4(tmat, go->ob->obmat);
712                                 sub_v3_v3v3(tmat[3], tmat[3], group->dupli_ofs);
713                                 mul_m4_m4m4(mat, tmat, ob->obmat);
714                         } else {
715                                 mul_m4_m4m4(mat, go->ob->obmat, ob->obmat);
716                         }
717                         
718                         dob= new_dupli_object(lb, go->ob, mat, ob->lay, 0, OB_DUPLIGROUP, animated);
719
720                         /* check the group instance and object layers match, also that the object visible flags are ok. */
721                         if(     (dob->origlay & group->layer)==0 ||
722                                 (G.rendering==0 && dob->ob->restrictflag & OB_RESTRICT_VIEW) ||
723                                 (G.rendering && dob->ob->restrictflag & OB_RESTRICT_RENDER)
724                         ) {
725                                 dob->no_draw= 1;
726                         }
727                         else {
728                                 dob->no_draw= 0;
729                         }
730
731                         if(go->ob->transflag & OB_DUPLI) {
732                                 copy_m4_m4(dob->ob->obmat, dob->mat);
733                                 object_duplilist_recursive(&group->id, scene, go->ob, lb, ob->obmat, level+1, animated);
734                                 copy_m4_m4(dob->ob->obmat, dob->omat);
735                         }
736                 }
737         }
738 }
739
740 static void frames_duplilist(ListBase *lb, Scene *scene, Object *ob, int level, int animated)
741 {
742         extern int enable_cu_speed;     /* object.c */
743         Object copyob;
744         DupliObject *dob;
745         int cfrao, ok;
746         
747         /* simple preventing of too deep nested groups */
748         if(level>MAX_DUPLI_RECUR) return;
749         
750         cfrao= scene->r.cfra;
751         if(ob->parent==NULL && ob->constraints.first==NULL) return;
752
753         if(ob->transflag & OB_DUPLINOSPEED) enable_cu_speed= 0;
754         copyob= *ob;    /* store transform info */
755
756         for(scene->r.cfra= ob->dupsta; scene->r.cfra<=ob->dupend; scene->r.cfra++) {
757
758                 ok= 1;
759                 if(ob->dupoff) {
760                         ok= scene->r.cfra - ob->dupsta;
761                         ok= ok % (ob->dupon+ob->dupoff);
762                         if(ok < ob->dupon) ok= 1;
763                         else ok= 0;
764                 }
765                 if(ok) {
766 #if 0 // XXX old animation system
767                         do_ob_ipo(scene, ob);
768 #endif // XXX old animation system
769                         where_is_object_time(scene, ob, (float)scene->r.cfra);
770                         dob= new_dupli_object(lb, ob, ob->obmat, ob->lay, scene->r.cfra, OB_DUPLIFRAMES, animated);
771                         copy_m4_m4(dob->omat, copyob.obmat);
772                 }
773         }
774
775         *ob= copyob;    /* restore transform info */
776         scene->r.cfra= cfrao;
777         enable_cu_speed= 1;
778 }
779
780 typedef struct vertexDupliData {
781         ID *id; /* scene or group, for recursive loops */
782         int level;
783         int animated;
784         ListBase *lb;
785         float pmat[4][4];
786         float obmat[4][4]; /* Only used for dupliverts inside dupligroups, where the ob->obmat is modified */
787         Scene *scene;
788         Object *ob, *par;
789         float (*orco)[3];
790 } vertexDupliData;
791
792 /* ------------- */
793
794 static void vertex_dupli__mapFunc(void *userData, int index, float *co, float *no_f, short *no_s)
795 {
796         DupliObject *dob;
797         vertexDupliData *vdd= userData;
798         float vec[3], q2[4], mat[3][3], tmat[4][4], obmat[4][4];
799         
800         mul_v3_m4v3(vec, vdd->pmat, co);
801         sub_v3_v3(vec, vdd->pmat[3]);
802         add_v3_v3(vec, vdd->obmat[3]);
803         
804         copy_m4_m4(obmat, vdd->obmat);
805         VECCOPY(obmat[3], vec);
806         
807         if(vdd->par->transflag & OB_DUPLIROT) {
808                 if(no_f) {
809                         vec[0]= -no_f[0]; vec[1]= -no_f[1]; vec[2]= -no_f[2];
810                 }
811                 else if(no_s) {
812                         vec[0]= -no_s[0]; vec[1]= -no_s[1]; vec[2]= -no_s[2];
813                 }
814                 
815                 vec_to_quat( q2,vec, vdd->ob->trackflag, vdd->ob->upflag);
816                 
817                 quat_to_mat3( mat,q2);
818                 copy_m4_m4(tmat, obmat);
819                 mul_m4_m4m3(obmat, tmat, mat);
820         }
821         dob= new_dupli_object(vdd->lb, vdd->ob, obmat, vdd->par->lay, index, OB_DUPLIVERTS, vdd->animated);
822         if(vdd->orco)
823                 VECCOPY(dob->orco, vdd->orco[index]);
824         
825         if(vdd->ob->transflag & OB_DUPLI) {
826                 float tmpmat[4][4];
827                 copy_m4_m4(tmpmat, vdd->ob->obmat);
828                 copy_m4_m4(vdd->ob->obmat, obmat); /* pretend we are really this mat */
829                 object_duplilist_recursive((ID *)vdd->id, vdd->scene, vdd->ob, vdd->lb, obmat, vdd->level+1, vdd->animated);
830                 copy_m4_m4(vdd->ob->obmat, tmpmat);
831         }
832 }
833
834 static void vertex_duplilist(ListBase *lb, ID *id, Scene *scene, Object *par, float par_space_mat[][4], int level, int animated)
835 {
836         Object *ob, *ob_iter;
837         Mesh *me= par->data;
838         Base *base = NULL;
839         DerivedMesh *dm;
840         vertexDupliData vdd;
841         Scene *sce = NULL;
842         Group *group = NULL;
843         GroupObject * go = NULL;
844         EditMesh *em;
845         float vec[3], no[3], pmat[4][4];
846         int totvert, a, oblay;
847         unsigned int lay;
848         
849         copy_m4_m4(pmat, par->obmat);
850         
851         /* simple preventing of too deep nested groups */
852         if(level>MAX_DUPLI_RECUR) return;
853         
854         em = BKE_mesh_get_editmesh(me);
855         
856         if(em) {
857                 dm= editmesh_get_derived_cage(scene, par, em, CD_MASK_BAREMESH);
858                 BKE_mesh_end_editmesh(me, em);
859         } else
860                 dm= mesh_get_derived_deform(scene, par, CD_MASK_BAREMESH);
861         
862         if(G.rendering) {
863                 vdd.orco= (float(*)[3])get_mesh_orco_verts(par);
864                 transform_mesh_orco_verts(me, vdd.orco, me->totvert, 0);
865         }
866         else
867                 vdd.orco= NULL;
868         
869         totvert = dm->getNumVerts(dm);
870
871         /* having to loop on scene OR group objects is NOT FUN */
872         if (GS(id->name) == ID_SCE) {
873                 sce = (Scene *)id;
874                 lay= sce->lay;
875                 base= sce->base.first;
876         } else {
877                 group = (Group *)id;
878                 lay= group->layer;
879                 go = group->gobject.first;
880         }
881         
882         /* Start looping on Scene OR Group objects */
883         while (base || go) { 
884                 if (sce) {
885                         ob_iter= base->object;
886                         oblay = base->lay;
887                 } else {
888                         ob_iter= go->ob;
889                         oblay = ob_iter->lay;
890                 }
891                 
892                 if (lay & oblay && scene->obedit!=ob_iter) {
893                         ob=ob_iter->parent;
894                         while(ob) {
895                                 if(ob==par) {
896                                         ob = ob_iter;
897         /* End Scene/Group object loop, below is generic */
898                                         
899                                         
900                                         /* par_space_mat - only used for groups so we can modify the space dupli's are in
901                                            when par_space_mat is NULL ob->obmat can be used instead of ob__obmat
902                                         */
903                                         if(par_space_mat)
904                                                 mul_m4_m4m4(vdd.obmat, ob->obmat, par_space_mat);
905                                         else
906                                                 copy_m4_m4(vdd.obmat, ob->obmat);
907
908                                         vdd.id= id;
909                                         vdd.level= level;
910                                         vdd.animated= animated;
911                                         vdd.lb= lb;
912                                         vdd.ob= ob;
913                                         vdd.scene= scene;
914                                         vdd.par= par;
915                                         copy_m4_m4(vdd.pmat, pmat);
916                                         
917                                         /* mballs have a different dupli handling */
918                                         if(ob->type!=OB_MBALL) ob->flag |= OB_DONE;     /* doesnt render */
919
920                                         if(me->edit_mesh) {
921                                                 dm->foreachMappedVert(dm, vertex_dupli__mapFunc, (void*) &vdd);
922                                         }
923                                         else {
924                                                 for(a=0; a<totvert; a++) {
925                                                         dm->getVertCo(dm, a, vec);
926                                                         dm->getVertNo(dm, a, no);
927                                                         
928                                                         vertex_dupli__mapFunc(&vdd, a, vec, no, NULL);
929                                                 }
930                                         }
931                                         
932                                         break;
933                                 }
934                                 ob= ob->parent;
935                         }
936                 }
937                 if (sce)        base= base->next;       /* scene loop */
938                 else            go= go->next;           /* group loop */
939         }
940
941         if(vdd.orco)
942                 MEM_freeN(vdd.orco);
943         dm->release(dm);
944 }
945
946 static void face_duplilist(ListBase *lb, ID *id, Scene *scene, Object *par, float par_space_mat[][4], int level, int animated)
947 {
948         Object *ob, *ob_iter;
949         Base *base = NULL;
950         DupliObject *dob;
951         DerivedMesh *dm;
952         Mesh *me= par->data;
953         MTFace *mtface;
954         MFace *mface;
955         MVert *mvert;
956         float pmat[4][4], imat[3][3], (*orco)[3] = NULL, w;
957         int lay, oblay, totface, a;
958         Scene *sce = NULL;
959         Group *group = NULL;
960         GroupObject *go = NULL;
961         EditMesh *em;
962         float ob__obmat[4][4]; /* needed for groups where the object matrix needs to be modified */
963         
964         /* simple preventing of too deep nested groups */
965         if(level>MAX_DUPLI_RECUR) return;
966         
967         copy_m4_m4(pmat, par->obmat);
968         
969         em = BKE_mesh_get_editmesh(me);
970         if(em) {
971                 int totvert;
972                 
973                 dm= editmesh_get_derived_cage(scene, par, em, CD_MASK_BAREMESH);
974                 
975                 totface= dm->getNumFaces(dm);
976                 mface= MEM_mallocN(sizeof(MFace)*totface, "mface temp");
977                 dm->copyFaceArray(dm, mface);
978                 totvert= dm->getNumVerts(dm);
979                 mvert= MEM_mallocN(sizeof(MVert)*totvert, "mvert temp");
980                 dm->copyVertArray(dm, mvert);
981
982                 BKE_mesh_end_editmesh(me, em);
983         }
984         else {
985                 dm = mesh_get_derived_deform(scene, par, CD_MASK_BAREMESH);
986                 
987                 totface= dm->getNumFaces(dm);
988                 mface= dm->getFaceArray(dm);
989                 mvert= dm->getVertArray(dm);
990         }
991
992         if(G.rendering) {
993
994                 orco= (float(*)[3])get_mesh_orco_verts(par);
995                 transform_mesh_orco_verts(me, orco, me->totvert, 0);
996                 mtface= me->mtface;
997         }
998         else {
999                 orco= NULL;
1000                 mtface= NULL;
1001         }
1002         
1003         /* having to loop on scene OR group objects is NOT FUN */
1004         if (GS(id->name) == ID_SCE) {
1005                 sce = (Scene *)id;
1006                 lay= sce->lay;
1007                 base= sce->base.first;
1008         } else {
1009                 group = (Group *)id;
1010                 lay= group->layer;
1011                 go = group->gobject.first;
1012         }
1013         
1014         /* Start looping on Scene OR Group objects */
1015         while (base || go) { 
1016                 if (sce) {
1017                         ob_iter= base->object;
1018                         oblay = base->lay;
1019                 } else {
1020                         ob_iter= go->ob;
1021                         oblay = ob_iter->lay;
1022                 }
1023                 
1024                 if (lay & oblay && scene->obedit!=ob_iter) {
1025                         ob=ob_iter->parent;
1026                         while(ob) {
1027                                 if(ob==par) {
1028                                         ob = ob_iter;
1029         /* End Scene/Group object loop, below is generic */
1030                                         
1031                                         /* par_space_mat - only used for groups so we can modify the space dupli's are in
1032                                            when par_space_mat is NULL ob->obmat can be used instead of ob__obmat
1033                                         */
1034                                         if(par_space_mat)
1035                                                 mul_m4_m4m4(ob__obmat, ob->obmat, par_space_mat);
1036                                         else
1037                                                 copy_m4_m4(ob__obmat, ob->obmat);
1038                                         
1039                                         copy_m3_m4(imat, ob->parentinv);
1040                                                 
1041                                         /* mballs have a different dupli handling */
1042                                         if(ob->type!=OB_MBALL) ob->flag |= OB_DONE;     /* doesnt render */
1043
1044                                         for(a=0; a<totface; a++) {
1045                                                 int mv1 = mface[a].v1;
1046                                                 int mv2 = mface[a].v2;
1047                                                 int mv3 = mface[a].v3;
1048                                                 int mv4 = mface[a].v4;
1049                                                 float *v1= mvert[mv1].co;
1050                                                 float *v2= mvert[mv2].co;
1051                                                 float *v3= mvert[mv3].co;
1052                                                 float *v4= (mv4)? mvert[mv4].co: NULL;
1053                                                 float cent[3], quat[4], mat[3][3], mat3[3][3], tmat[4][4], obmat[4][4];
1054
1055                                                 /* translation */
1056                                                 if(v4)
1057                                                         cent_quad_v3(cent, v1, v2, v3, v4);
1058                                                 else
1059                                                         cent_tri_v3(cent, v1, v2, v3);
1060                                                 mul_m4_v3(pmat, cent);
1061                                                 
1062                                                 sub_v3_v3v3(cent, cent, pmat[3]);
1063                                                 add_v3_v3(cent, ob__obmat[3]);
1064                                                 
1065                                                 copy_m4_m4(obmat, ob__obmat);
1066                                                 
1067                                                 VECCOPY(obmat[3], cent);
1068                                                 
1069                                                 /* rotation */
1070                                                 tri_to_quat( quat,v1, v2, v3);
1071                                                 quat_to_mat3( mat,quat);
1072                                                 
1073                                                 /* scale */
1074                                                 if(par->transflag & OB_DUPLIFACES_SCALE) {
1075                                                         float size= v4? area_quad_v3(v1, v2, v3, v4): area_tri_v3(v1, v2, v3);
1076                                                         size= sqrt(size) * par->dupfacesca;
1077                                                         mul_m3_fl(mat, size);
1078                                                 }
1079                                                 
1080                                                 copy_m3_m3(mat3, mat);
1081                                                 mul_m3_m3m3(mat, imat, mat3);
1082                                                 
1083                                                 copy_m4_m4(tmat, obmat);
1084                                                 mul_m4_m4m3(obmat, tmat, mat);
1085                                                 
1086                                                 dob= new_dupli_object(lb, ob, obmat, par->lay, a, OB_DUPLIFACES, animated);
1087                                                 if(G.rendering) {
1088                                                         w= (mv4)? 0.25f: 1.0f/3.0f;
1089
1090                                                         if(orco) {
1091                                                                 VECADDFAC(dob->orco, dob->orco, orco[mv1], w);
1092                                                                 VECADDFAC(dob->orco, dob->orco, orco[mv2], w);
1093                                                                 VECADDFAC(dob->orco, dob->orco, orco[mv3], w);
1094                                                                 if(mv4)
1095                                                                         VECADDFAC(dob->orco, dob->orco, orco[mv4], w);
1096                                                         }
1097
1098                                                         if(mtface) {
1099                                                                 dob->uv[0] += w*mtface[a].uv[0][0];
1100                                                                 dob->uv[1] += w*mtface[a].uv[0][1];
1101                                                                 dob->uv[0] += w*mtface[a].uv[1][0];
1102                                                                 dob->uv[1] += w*mtface[a].uv[1][1];
1103                                                                 dob->uv[0] += w*mtface[a].uv[2][0];
1104                                                                 dob->uv[1] += w*mtface[a].uv[2][1];
1105
1106                                                                 if(mv4) {
1107                                                                         dob->uv[0] += w*mtface[a].uv[3][0];
1108                                                                         dob->uv[1] += w*mtface[a].uv[3][1];
1109                                                                 }
1110                                                         }
1111                                                 }
1112                                                 
1113                                                 if(ob->transflag & OB_DUPLI) {
1114                                                         float tmpmat[4][4];
1115                                                         copy_m4_m4(tmpmat, ob->obmat);
1116                                                         copy_m4_m4(ob->obmat, obmat); /* pretend we are really this mat */
1117                                                         object_duplilist_recursive((ID *)id, scene, ob, lb, ob->obmat, level+1, animated);
1118                                                         copy_m4_m4(ob->obmat, tmpmat);
1119                                                 }
1120                                         }
1121                                         
1122                                         break;
1123                                 }
1124                                 ob= ob->parent;
1125                         }
1126                 }
1127                 if (sce)        base= base->next;       /* scene loop */
1128                 else            go= go->next;           /* group loop */
1129         }
1130         
1131         if(em) {
1132                 MEM_freeN(mface);
1133                 MEM_freeN(mvert);
1134         }
1135
1136         if(orco)
1137                 MEM_freeN(orco);
1138         
1139         dm->release(dm);
1140 }
1141
1142 static void new_particle_duplilist(ListBase *lb, ID *UNUSED(id), Scene *scene, Object *par, float par_space_mat[][4], ParticleSystem *psys, int level, int animated)
1143 {
1144         GroupObject *go;
1145         Object *ob=0, **oblist=0, obcopy, *obcopylist=0;
1146         DupliObject *dob;
1147         ParticleDupliWeight *dw;
1148         ParticleSimulationData sim = {scene, par, psys, psys_get_modifier(par, psys)};
1149         ParticleSettings *part;
1150         ParticleData *pa;
1151         ChildParticle *cpa=0;
1152         ParticleKey state;
1153         ParticleCacheKey *cache;
1154         float ctime, pa_time, scale = 1.0f;
1155         float tmat[4][4], mat[4][4], pamat[4][4], vec[3], size=0.0;
1156         float (*obmat)[4], (*oldobmat)[4];
1157         int a, b, counter, hair = 0;
1158         int totpart, totchild, totgroup=0, pa_num;
1159         unsigned int lay;
1160
1161         if(psys==0) return;
1162         
1163         /* simple preventing of too deep nested groups */
1164         if(level>MAX_DUPLI_RECUR) return;
1165         
1166         part=psys->part;
1167
1168         if(part==0)
1169                 return;
1170
1171         if(!psys_check_enabled(par, psys))
1172                 return;
1173         
1174         ctime = bsystem_time(scene, par, (float)scene->r.cfra, 0.0);
1175
1176         totpart = psys->totpart;
1177         totchild = psys->totchild;
1178
1179         BLI_srandom(31415926 + psys->seed);
1180         
1181         lay= scene->lay;
1182         if((psys->renderdata || part->draw_as==PART_DRAW_REND) && ELEM(part->ren_as, PART_DRAW_OB, PART_DRAW_GR)) {
1183
1184                 /* first check for loops (particle system object used as dupli object) */
1185                 if(part->ren_as == PART_DRAW_OB) {
1186                         if(ELEM(part->dup_ob, NULL, par))
1187                                 return;
1188                 }
1189                 else { /*PART_DRAW_GR */
1190                         if(part->dup_group == NULL || part->dup_group->gobject.first == NULL)
1191                                 return;
1192
1193                         for(go=part->dup_group->gobject.first; go; go=go->next)
1194                                 if(go->ob == par)
1195                                         return;
1196                 }
1197
1198                 /* if we have a hair particle system, use the path cache */
1199                 if(part->type == PART_HAIR) {
1200                         if(psys->flag & PSYS_HAIR_DONE)
1201                                 hair= (totchild == 0 || psys->childcache) && psys->pathcache;
1202                         if(!hair)
1203                                 return;
1204                         
1205                         /* we use cache, update totchild according to cached data */
1206                         totchild = psys->totchildcache;
1207                         totpart = psys->totcached;
1208                 }
1209
1210                 psys_check_group_weights(part);
1211
1212                 psys->lattice = psys_get_lattice(&sim);
1213
1214                 /* gather list of objects or single object */
1215                 if(part->ren_as==PART_DRAW_GR) {
1216                         group_handle_recalc_and_update(scene, par, part->dup_group);
1217
1218                         if(part->draw & PART_DRAW_COUNT_GR) {
1219                                 for(dw=part->dupliweights.first; dw; dw=dw->next)
1220                                         totgroup += dw->count;
1221                         }
1222                         else {
1223                                 for(go=part->dup_group->gobject.first; go; go=go->next)
1224                                         totgroup++;
1225                         }
1226
1227                         /* we also copy the actual objects to restore afterwards, since
1228                          * where_is_object_time will change the object which breaks transform */
1229                         oblist = MEM_callocN(totgroup*sizeof(Object *), "dupgroup object list");
1230                         obcopylist = MEM_callocN(totgroup*sizeof(Object), "dupgroup copy list");
1231
1232                         
1233                         if(part->draw & PART_DRAW_COUNT_GR && totgroup) {
1234                                 dw = part->dupliweights.first;
1235
1236                                 for(a=0; a<totgroup; dw=dw->next) {
1237                                         for(b=0; b<dw->count; b++, a++) {
1238                                                 oblist[a] = dw->ob;
1239                                                 obcopylist[a] = *dw->ob;
1240                                         }
1241                                 }
1242                         }
1243                         else {
1244                                 go = part->dup_group->gobject.first;
1245                                 for(a=0; a<totgroup; a++, go=go->next) {
1246                                         oblist[a] = go->ob;
1247                                         obcopylist[a] = *go->ob;
1248                                 }
1249                         }
1250                 }
1251                 else {
1252                         ob = part->dup_ob;
1253                         obcopy = *ob;
1254                 }
1255
1256                 if(totchild==0 || part->draw & PART_DRAW_PARENT)
1257                         a = 0;
1258                 else
1259                         a = totpart;
1260
1261                 for(pa=psys->particles,counter=0; a<totpart+totchild; a++,pa++,counter++) {
1262                         if(a<totpart) {
1263                                 /* handle parent particle */
1264                                 if(pa->flag & (PARS_UNEXIST+PARS_NO_DISP))
1265                                         continue;
1266
1267                                 pa_num = pa->num;
1268                                 pa_time = pa->time;
1269                                 size = pa->size;
1270                         }
1271                         else {
1272                                 /* handle child particle */
1273                                 cpa = &psys->child[a - totpart];
1274
1275                                 pa_num = a;
1276                                 pa_time = psys->particles[cpa->parent].time;
1277                                 size = psys_get_child_size(psys, cpa, ctime, 0);
1278                         }
1279
1280                         /* some hair paths might be non-existent so they can't be used for duplication */
1281                         if(hair &&
1282                                 ((a < totpart && psys->pathcache[a]->steps < 0) ||
1283                                 (a >= totpart && psys->childcache[a-totpart]->steps < 0)))
1284                                 continue;
1285
1286                         if(part->ren_as==PART_DRAW_GR) {
1287                                 /* for groups, pick the object based on settings */
1288                                 if(part->draw&PART_DRAW_RAND_GR)
1289                                         b= BLI_rand() % totgroup;
1290                                 else if(part->from==PART_FROM_PARTICLE)
1291                                         b= pa_num % totgroup;
1292                                 else
1293                                         b= a % totgroup;
1294
1295                                 ob = oblist[b];
1296                                 obmat = oblist[b]->obmat;
1297                                 oldobmat = obcopylist[b].obmat;
1298                         }
1299                         else {
1300                                 obmat= ob->obmat;
1301                                 oldobmat= obcopy.obmat;
1302                         }
1303
1304                         if(hair) {
1305                                 /* hair we handle separate and compute transform based on hair keys */
1306                                 if(a < totpart) {
1307                                         cache = psys->pathcache[a];
1308                                         psys_get_dupli_path_transform(&sim, pa, 0, cache, pamat, &scale);
1309                                 }
1310                                 else {
1311                                         cache = psys->childcache[a-totpart];
1312                                         psys_get_dupli_path_transform(&sim, 0, cpa, cache, pamat, &scale);
1313                                 }
1314
1315                                 VECCOPY(pamat[3], cache->co);
1316                                 pamat[3][3]= 1.0f;
1317                                 
1318                         }
1319                         else {
1320                                 /* first key */
1321                                 state.time = ctime;
1322                                 if(psys_get_particle_state(&sim, a, &state, 0) == 0)
1323                                         continue;
1324
1325                                 quat_to_mat4( pamat,state.rot);
1326                                 VECCOPY(pamat[3], state.co);
1327                                 pamat[3][3]= 1.0f;
1328                         }
1329
1330                         if(part->ren_as==PART_DRAW_GR && psys->part->draw & PART_DRAW_WHOLE_GR) {
1331                                 for(go= part->dup_group->gobject.first, b=0; go; go= go->next, b++) {
1332                                         mul_m4_m4m4(tmat, oblist[b]->obmat, pamat);
1333                                         mul_mat3_m4_fl(tmat, size*scale);
1334                                         if(par_space_mat)
1335                                                 mul_m4_m4m4(mat, tmat, par_space_mat);
1336                                         else
1337                                                 copy_m4_m4(mat, tmat);
1338
1339                                         dob= new_dupli_object(lb, go->ob, mat, par->lay, counter, OB_DUPLIPARTS, animated);
1340                                         copy_m4_m4(dob->omat, obcopylist[b].obmat);
1341                                         if(G.rendering)
1342                                                 psys_get_dupli_texture(par, part, sim.psmd, pa, cpa, dob->uv, dob->orco);
1343                                 }
1344                         }
1345                         else {
1346                                 /* to give ipos in object correct offset */
1347                                 where_is_object_time(scene, ob, ctime-pa_time);
1348
1349                                 VECCOPY(vec, obmat[3]);
1350                                 obmat[3][0] = obmat[3][1] = obmat[3][2] = 0.0f;
1351                                 
1352                                 /* Normal particles and cached hair live in global space so we need to
1353                                  * remove the real emitter's transformation before 2nd order duplication.
1354                                  */
1355                                 if(par_space_mat)
1356                                         mul_m4_m4m4(mat, pamat, psys->imat);
1357                                 else
1358                                         copy_m4_m4(mat, pamat);
1359
1360                                 mul_m4_m4m4(tmat, obmat, mat);
1361                                 mul_mat3_m4_fl(tmat, size*scale);
1362
1363                                 if(par_space_mat)
1364                                         mul_m4_m4m4(mat, tmat, par_space_mat);
1365                                 else
1366                                         copy_m4_m4(mat, tmat);
1367
1368                                 if(part->draw & PART_DRAW_GLOBAL_OB)
1369                                         VECADD(mat[3], mat[3], vec);
1370
1371                                 dob= new_dupli_object(lb, ob, mat, ob->lay, counter, OB_DUPLIPARTS, animated);
1372                                 copy_m4_m4(dob->omat, oldobmat);
1373                                 if(G.rendering)
1374                                         psys_get_dupli_texture(par, part, sim.psmd, pa, cpa, dob->uv, dob->orco);
1375                         }
1376                 }
1377
1378                 /* restore objects since they were changed in where_is_object_time */
1379                 if(part->ren_as==PART_DRAW_GR) {
1380                         for(a=0; a<totgroup; a++)
1381                                 *(oblist[a])= obcopylist[a];
1382                 }
1383                 else
1384                         *ob= obcopy;
1385         }
1386
1387         /* clean up */
1388         if(oblist)
1389                 MEM_freeN(oblist);
1390         if(obcopylist)
1391                 MEM_freeN(obcopylist);
1392
1393         if(psys->lattice) {
1394                 end_latt_deform(psys->lattice);
1395                 psys->lattice = NULL;
1396         }
1397 }
1398
1399 static Object *find_family_object(Object **obar, char *family, char ch)
1400 {
1401         Object *ob;
1402         int flen;
1403         
1404         if( obar[(int)ch] ) return obar[(int)ch];
1405         
1406         flen= strlen(family);
1407         
1408         ob= G.main->object.first;
1409         while(ob) {
1410                 if( ob->id.name[flen+2]==ch ) {
1411                         if( strncmp(ob->id.name+2, family, flen)==0 ) break;
1412                 }
1413                 ob= ob->id.next;
1414         }
1415         
1416         obar[(int)ch]= ob;
1417         
1418         return ob;
1419 }
1420
1421
1422 static void font_duplilist(ListBase *lb, Scene *scene, Object *par, int level, int animated)
1423 {
1424         Object *ob, *obar[256];
1425         Curve *cu;
1426         struct chartrans *ct, *chartransdata;
1427         float vec[3], obmat[4][4], pmat[4][4], fsize, xof, yof;
1428         int slen, a;
1429         
1430         /* simple preventing of too deep nested groups */
1431         if(level>MAX_DUPLI_RECUR) return;
1432         
1433         copy_m4_m4(pmat, par->obmat);
1434         
1435         /* in par the family name is stored, use this to find the other objects */
1436         
1437         chartransdata= BKE_text_to_curve(scene, par, FO_DUPLI);
1438         if(chartransdata==0) return;
1439         
1440         memset(obar, 0, 256*sizeof(void *));
1441         
1442         cu= par->data;
1443         slen= strlen(cu->str);
1444         fsize= cu->fsize;
1445         xof= cu->xof;
1446         yof= cu->yof;
1447         
1448         ct= chartransdata;
1449         
1450         for(a=0; a<slen; a++, ct++) {
1451                 
1452                 ob= find_family_object(obar, cu->family, cu->str[a]);
1453                 if(ob) {
1454                         vec[0]= fsize*(ct->xof - xof);
1455                         vec[1]= fsize*(ct->yof - yof);
1456                         vec[2]= 0.0;
1457                         
1458                         mul_m4_v3(pmat, vec);
1459                         
1460                         copy_m4_m4(obmat, par->obmat);
1461                         VECCOPY(obmat[3], vec);
1462                         
1463                         new_dupli_object(lb, ob, obmat, par->lay, a, OB_DUPLIVERTS, animated);
1464                 }
1465         }
1466         
1467         MEM_freeN(chartransdata);
1468 }
1469
1470 /* ------------- */
1471
1472 static void object_duplilist_recursive(ID *id, Scene *scene, Object *ob, ListBase *duplilist, float par_space_mat[][4], int level, int animated)
1473 {       
1474         if((ob->transflag & OB_DUPLI)==0)
1475                 return;
1476         
1477         /* Should the dupli's be generated for this object? - Respect restrict flags */
1478         if (G.rendering) {
1479                 if (ob->restrictflag & OB_RESTRICT_RENDER) {
1480                         return;
1481                 }
1482         } else {
1483                 if (ob->restrictflag & OB_RESTRICT_VIEW) {
1484                         return;
1485                 }
1486         }
1487
1488         if(ob->transflag & OB_DUPLIPARTS) {
1489                 ParticleSystem *psys = ob->particlesystem.first;
1490                 for(; psys; psys=psys->next)
1491                         new_particle_duplilist(duplilist, id, scene, ob, par_space_mat, psys, level+1, animated);
1492         }
1493         else if(ob->transflag & OB_DUPLIVERTS) {
1494                 if(ob->type==OB_MESH) {
1495                         vertex_duplilist(duplilist, id, scene, ob, par_space_mat, level+1, animated);
1496                 }
1497                 else if(ob->type==OB_FONT) {
1498                         if (GS(id->name)==ID_SCE) { /* TODO - support dupligroups */
1499                                 font_duplilist(duplilist, scene, ob, level+1, animated);
1500                         }
1501                 }
1502         }
1503         else if(ob->transflag & OB_DUPLIFACES) {
1504                 if(ob->type==OB_MESH)
1505                         face_duplilist(duplilist, id, scene, ob, par_space_mat, level+1, animated);
1506         }
1507         else if(ob->transflag & OB_DUPLIFRAMES) {
1508                 if (GS(id->name)==ID_SCE) { /* TODO - support dupligroups */
1509                         frames_duplilist(duplilist, scene, ob, level+1, animated);
1510                 }
1511         } else if(ob->transflag & OB_DUPLIGROUP) {
1512                 DupliObject *dob;
1513                 
1514                 group_duplilist(duplilist, scene, ob, level+1, animated); /* now recursive */
1515
1516                 if (level==0) {
1517                         for(dob= duplilist->first; dob; dob= dob->next)
1518                                 if(dob->type == OB_DUPLIGROUP)
1519                                         copy_m4_m4(dob->ob->obmat, dob->mat);
1520                 }
1521         }
1522 }
1523
1524 /* Returns a list of DupliObject
1525  * note; group dupli's already set transform matrix. see note in group_duplilist() */
1526 ListBase *object_duplilist(Scene *sce, Object *ob)
1527 {
1528         ListBase *duplilist= MEM_mallocN(sizeof(ListBase), "duplilist");
1529         duplilist->first= duplilist->last= NULL;
1530         object_duplilist_recursive((ID *)sce, sce, ob, duplilist, NULL, 0, 0);
1531         return duplilist;
1532 }
1533
1534 void free_object_duplilist(ListBase *lb)
1535 {
1536         DupliObject *dob;
1537         
1538         /* loop in reverse order, if object is instanced multiple times
1539            the original layer may not really be original otherwise, proper
1540            solution is more complicated */
1541         for(dob= lb->last; dob; dob= dob->prev) {
1542                 dob->ob->lay= dob->origlay;
1543                 copy_m4_m4(dob->ob->obmat, dob->omat);
1544         }
1545         
1546         BLI_freelistN(lb);
1547         MEM_freeN(lb);
1548 }
1549
1550 int count_duplilist(Object *ob)
1551 {
1552         if(ob->transflag & OB_DUPLI) {
1553                 if(ob->transflag & OB_DUPLIVERTS) {
1554                         if(ob->type==OB_MESH) {
1555                                 if(ob->transflag & OB_DUPLIVERTS) {
1556                                         ParticleSystem *psys = ob->particlesystem.first;
1557                                         int pdup=0;
1558
1559                                         for(; psys; psys=psys->next)
1560                                                 pdup += psys->totpart;
1561
1562                                         if(pdup==0){
1563                                                 Mesh *me= ob->data;
1564                                                 return me->totvert;
1565                                         }
1566                                         else
1567                                                 return pdup;
1568                                 }
1569                         }
1570                 }
1571                 else if(ob->transflag & OB_DUPLIFRAMES) {
1572                         int tot= ob->dupend - ob->dupsta; 
1573                         tot/= (ob->dupon+ob->dupoff);
1574                         return tot*ob->dupon;
1575                 }
1576         }
1577         return 1;
1578 }