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