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