Merging r46074 through r46095 from trunk into soc-2011-tomato
[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_get(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, const float co[3],
844                                   const float no_f[3], const short no_s[3])
845 {
846         DupliObject *dob;
847         vertexDupliData *vdd= userData;
848         float vec[3], q2[4], mat[3][3], tmat[4][4], obmat[4][4];
849         int origlay;
850         
851         mul_v3_m4v3(vec, vdd->pmat, co);
852         sub_v3_v3(vec, vdd->pmat[3]);
853         add_v3_v3(vec, vdd->obmat[3]);
854         
855         copy_m4_m4(obmat, vdd->obmat);
856         copy_v3_v3(obmat[3], vec);
857         
858         if (vdd->par->transflag & OB_DUPLIROT) {
859                 if (no_f) {
860                         vec[0]= -no_f[0]; vec[1]= -no_f[1]; vec[2]= -no_f[2];
861                 }
862                 else if (no_s) {
863                         vec[0]= -no_s[0]; vec[1]= -no_s[1]; vec[2]= -no_s[2];
864                 }
865                 
866                 vec_to_quat(q2, vec, vdd->ob->trackflag, vdd->ob->upflag);
867                 
868                 quat_to_mat3(mat, q2);
869                 copy_m4_m4(tmat, obmat);
870                 mul_m4_m4m3(obmat, tmat, mat);
871         }
872
873         origlay = vdd->ob->lay;
874         
875         dob= new_dupli_object(vdd->lb, vdd->ob, obmat, vdd->par->lay, index, OB_DUPLIVERTS, vdd->animated);
876
877         /* restore the original layer so that each dupli will have proper dob->origlay */
878         vdd->ob->lay = origlay;
879
880         if (vdd->orco)
881                 copy_v3_v3(dob->orco, vdd->orco[index]);
882         
883         if (vdd->ob->transflag & OB_DUPLI) {
884                 float tmpmat[4][4];
885                 copy_m4_m4(tmpmat, vdd->ob->obmat);
886                 copy_m4_m4(vdd->ob->obmat, obmat); /* pretend we are really this mat */
887                 object_duplilist_recursive((ID *)vdd->id, vdd->scene, vdd->ob, vdd->lb, obmat, vdd->level+1, vdd->animated);
888                 copy_m4_m4(vdd->ob->obmat, tmpmat);
889         }
890 }
891
892 static void vertex_duplilist(ListBase *lb, ID *id, Scene *scene, Object *par, float par_space_mat[][4], int level, int animated)
893 {
894         Object *ob, *ob_iter;
895         Mesh *me= par->data;
896         Base *base = NULL;
897         DerivedMesh *dm;
898         vertexDupliData vdd;
899         Scene *sce = NULL;
900         Group *group = NULL;
901         GroupObject * go = NULL;
902         BMEditMesh *em;
903         float vec[3], no[3], pmat[4][4];
904         int totvert, a, oblay;
905         unsigned int lay;
906         
907         copy_m4_m4(pmat, par->obmat);
908         
909         /* simple preventing of too deep nested groups */
910         if (level>MAX_DUPLI_RECUR) return;
911         
912         em = me->edit_btmesh;
913         
914         if (em) {
915                 dm= editbmesh_get_derived_cage(scene, par, em, CD_MASK_BAREMESH);
916         }
917         else
918                 dm= mesh_get_derived_deform(scene, par, CD_MASK_BAREMESH);
919         
920         if (G.rendering) {
921                 vdd.orco= (float(*)[3])get_mesh_orco_verts(par);
922                 transform_mesh_orco_verts(me, vdd.orco, me->totvert, 0);
923         }
924         else
925                 vdd.orco= NULL;
926         
927         totvert = dm->getNumVerts(dm);
928
929         /* having to loop on scene OR group objects is NOT FUN */
930         if (GS(id->name) == ID_SCE) {
931                 sce = (Scene *)id;
932                 lay= sce->lay;
933                 base= sce->base.first;
934         }
935         else {
936                 group = (Group *)id;
937                 lay= group->layer;
938                 go = group->gobject.first;
939         }
940         
941         /* Start looping on Scene OR Group objects */
942         while (base || go) { 
943                 if (sce) {
944                         ob_iter= base->object;
945                         oblay = base->lay;
946                 }
947                 else {
948                         ob_iter= go->ob;
949                         oblay = ob_iter->lay;
950                 }
951                 
952                 if (lay & oblay && scene->obedit!=ob_iter) {
953                         ob=ob_iter->parent;
954                         while (ob) {
955                                 if (ob==par) {
956                                         ob = ob_iter;
957         /* End Scene/Group object loop, below is generic */
958                                         
959                                         
960                                         /* par_space_mat - only used for groups so we can modify the space dupli's are in
961                                          * when par_space_mat is NULL ob->obmat can be used instead of ob__obmat
962                                          */
963                                         if (par_space_mat)
964                                                 mult_m4_m4m4(vdd.obmat, par_space_mat, ob->obmat);
965                                         else
966                                                 copy_m4_m4(vdd.obmat, ob->obmat);
967
968                                         vdd.id= id;
969                                         vdd.level= level;
970                                         vdd.animated= animated;
971                                         vdd.lb= lb;
972                                         vdd.ob= ob;
973                                         vdd.scene= scene;
974                                         vdd.par= par;
975                                         copy_m4_m4(vdd.pmat, pmat);
976                                         
977                                         /* mballs have a different dupli handling */
978                                         if (ob->type!=OB_MBALL) ob->flag |= OB_DONE;    /* doesnt render */
979
980                                         if (me->edit_btmesh) {
981                                                 dm->foreachMappedVert(dm, vertex_dupli__mapFunc, (void*) &vdd);
982                                         }
983                                         else {
984                                                 for (a=0; a<totvert; a++) {
985                                                         dm->getVertCo(dm, a, vec);
986                                                         dm->getVertNo(dm, a, no);
987                                                         
988                                                         vertex_dupli__mapFunc(&vdd, a, vec, no, NULL);
989                                                 }
990                                         }
991                                         if (sce) {
992                                                 /* Set proper layer in case of scene looping,
993                                                  * in case of groups the object layer will be
994                                                  * changed when it's duplicated due to the
995                                                  * group duplication.
996                                                  */
997                                                 ob->lay = vdd.par->lay;
998                                         }
999                                         
1000                                         break;
1001                                 }
1002                                 ob= ob->parent;
1003                         }
1004                 }
1005                 if (sce)        base= base->next;       /* scene loop */
1006                 else            go= go->next;           /* group loop */
1007         }
1008
1009         if (vdd.orco)
1010                 MEM_freeN(vdd.orco);
1011         dm->release(dm);
1012 }
1013
1014 static void face_duplilist(ListBase *lb, ID *id, Scene *scene, Object *par, float par_space_mat[][4], int level, int animated)
1015 {
1016         Object *ob, *ob_iter;
1017         Base *base = NULL;
1018         DupliObject *dob;
1019         DerivedMesh *dm;
1020         Mesh *me= par->data;
1021         MLoopUV *mloopuv;
1022         MPoly *mpoly, *mp;
1023         MLoop *mloop;
1024         MVert *mvert;
1025         float pmat[4][4], imat[3][3], (*orco)[3] = NULL, w;
1026         int lay, oblay, totface, a;
1027         Scene *sce = NULL;
1028         Group *group = NULL;
1029         GroupObject *go = NULL;
1030         BMEditMesh *em;
1031         float ob__obmat[4][4]; /* needed for groups where the object matrix needs to be modified */
1032         
1033         /* simple preventing of too deep nested groups */
1034         if (level>MAX_DUPLI_RECUR) return;
1035         
1036         copy_m4_m4(pmat, par->obmat);
1037         em = me->edit_btmesh;
1038
1039         if (em) {
1040                 dm= editbmesh_get_derived_cage(scene, par, em, CD_MASK_BAREMESH);
1041         }
1042         else {
1043                 dm = mesh_get_derived_deform(scene, par, CD_MASK_BAREMESH);
1044         }
1045
1046         totface= dm->getNumPolys(dm);
1047         mpoly= dm->getPolyArray(dm);
1048         mloop= dm->getLoopArray(dm);
1049         mvert= dm->getVertArray(dm);
1050
1051         if (G.rendering) {
1052
1053                 orco= (float(*)[3])get_mesh_orco_verts(par);
1054                 transform_mesh_orco_verts(me, orco, me->totvert, 0);
1055                 mloopuv= me->mloopuv;
1056         }
1057         else {
1058                 orco= NULL;
1059                 mloopuv= NULL;
1060         }
1061         
1062         /* having to loop on scene OR group objects is NOT FUN */
1063         if (GS(id->name) == ID_SCE) {
1064                 sce = (Scene *)id;
1065                 lay= sce->lay;
1066                 base= sce->base.first;
1067         }
1068         else {
1069                 group = (Group *)id;
1070                 lay= group->layer;
1071                 go = group->gobject.first;
1072         }
1073         
1074         /* Start looping on Scene OR Group objects */
1075         while (base || go) { 
1076                 if (sce) {
1077                         ob_iter= base->object;
1078                         oblay = base->lay;
1079                 }
1080                 else {
1081                         ob_iter= go->ob;
1082                         oblay = ob_iter->lay;
1083                 }
1084                 
1085                 if (lay & oblay && scene->obedit!=ob_iter) {
1086                         ob=ob_iter->parent;
1087                         while (ob) {
1088                                 if (ob==par) {
1089                                         ob = ob_iter;
1090         /* End Scene/Group object loop, below is generic */
1091                                         
1092                                         /* par_space_mat - only used for groups so we can modify the space dupli's are in
1093                                          * when par_space_mat is NULL ob->obmat can be used instead of ob__obmat
1094                                          */
1095                                         if (par_space_mat)
1096                                                 mult_m4_m4m4(ob__obmat, par_space_mat, ob->obmat);
1097                                         else
1098                                                 copy_m4_m4(ob__obmat, ob->obmat);
1099                                         
1100                                         copy_m3_m4(imat, ob->parentinv);
1101                                                 
1102                                         /* mballs have a different dupli handling */
1103                                         if (ob->type!=OB_MBALL) ob->flag |= OB_DONE;    /* doesnt render */
1104
1105                                         for (a=0, mp= mpoly; a<totface; a++, mp++) {
1106                                                 int mv1;
1107                                                 int mv2;
1108                                                 int mv3;
1109                                                 /* int mv4; */ /* UNUSED */
1110                                                 float *v1;
1111                                                 float *v2;
1112                                                 float *v3;
1113                                                 /* float *v4; */ /* UNUSED */
1114                                                 float cent[3], quat[4], mat[3][3], mat3[3][3], tmat[4][4], obmat[4][4];
1115                                                 MLoop *loopstart= mloop + mp->loopstart;
1116
1117                                                 if (mp->totloop < 3) {
1118                                                         /* highly unlikely but to be safe */
1119                                                         continue;
1120                                                 }
1121                                                 else {
1122                                                         v1= mvert[(mv1= loopstart[0].v)].co;
1123                                                         v2= mvert[(mv2= loopstart[1].v)].co;
1124                                                         v3= mvert[(mv3= loopstart[2].v)].co;
1125 #if 0
1126                                                         if (mp->totloop > 3) {
1127                                                                 v4= mvert[(mv4= loopstart[3].v)].co;
1128                                                         }
1129 #endif
1130                                                 }
1131
1132                                                 /* translation */
1133                                                 mesh_calc_poly_center(mp, loopstart, mvert, cent);
1134
1135                                                 mul_m4_v3(pmat, cent);
1136                                                 
1137                                                 sub_v3_v3v3(cent, cent, pmat[3]);
1138                                                 add_v3_v3(cent, ob__obmat[3]);
1139                                                 
1140                                                 copy_m4_m4(obmat, ob__obmat);
1141                                                 
1142                                                 copy_v3_v3(obmat[3], cent);
1143                                                 
1144                                                 /* rotation */
1145                                                 tri_to_quat(quat, v1, v2, v3);
1146                                                 quat_to_mat3(mat, quat);
1147                                                 
1148                                                 /* scale */
1149                                                 if (par->transflag & OB_DUPLIFACES_SCALE) {
1150                                                         float size= mesh_calc_poly_area(mp, loopstart, mvert, NULL);
1151                                                         size= sqrtf(size) * par->dupfacesca;
1152                                                         mul_m3_fl(mat, size);
1153                                                 }
1154                                                 
1155                                                 copy_m3_m3(mat3, mat);
1156                                                 mul_m3_m3m3(mat, imat, mat3);
1157                                                 
1158                                                 copy_m4_m4(tmat, obmat);
1159                                                 mul_m4_m4m3(obmat, tmat, mat);
1160                                                 
1161                                                 dob= new_dupli_object(lb, ob, obmat, par->lay, a, OB_DUPLIFACES, animated);
1162                                                 if (G.rendering) {
1163                                                         w= 1.0f / (float)mp->totloop;
1164
1165                                                         if (orco) {
1166                                                                 int j;
1167                                                                 for (j = 0; j < mpoly->totloop; j++) {
1168                                                                         madd_v3_v3fl(dob->orco, orco[loopstart[j].v], w);
1169                                                                 }
1170                                                         }
1171
1172                                                         if (mloopuv) {
1173                                                                 int j;
1174                                                                 for (j = 0; j < mpoly->totloop; j++) {
1175                                                                         madd_v2_v2fl(dob->orco, mloopuv[loopstart[j].v].uv, w);
1176                                                                 }
1177                                                         }
1178                                                 }
1179                                                 
1180                                                 if (ob->transflag & OB_DUPLI) {
1181                                                         float tmpmat[4][4];
1182                                                         copy_m4_m4(tmpmat, ob->obmat);
1183                                                         copy_m4_m4(ob->obmat, obmat); /* pretend we are really this mat */
1184                                                         object_duplilist_recursive((ID *)id, scene, ob, lb, ob->obmat, level+1, animated);
1185                                                         copy_m4_m4(ob->obmat, tmpmat);
1186                                                 }
1187                                         }
1188                                         
1189                                         break;
1190                                 }
1191                                 ob= ob->parent;
1192                         }
1193                 }
1194                 if (sce)        base= base->next;       /* scene loop */
1195                 else            go= go->next;           /* group loop */
1196         }
1197
1198         if (orco)
1199                 MEM_freeN(orco);
1200         
1201         dm->release(dm);
1202 }
1203
1204 static void new_particle_duplilist(ListBase *lb, ID *id, Scene *scene, Object *par, float par_space_mat[][4], ParticleSystem *psys, int level, int animated)
1205 {
1206         GroupObject *go;
1207         Object *ob=NULL, **oblist=NULL, obcopy, *obcopylist=NULL;
1208         DupliObject *dob;
1209         ParticleDupliWeight *dw;
1210         ParticleSettings *part;
1211         ParticleData *pa;
1212         ChildParticle *cpa=NULL;
1213         ParticleKey state;
1214         ParticleCacheKey *cache;
1215         float ctime, pa_time, scale = 1.0f;
1216         float tmat[4][4], mat[4][4], pamat[4][4], vec[3], size=0.0;
1217         float (*obmat)[4], (*oldobmat)[4];
1218         int a, b, counter, hair = 0;
1219         int totpart, totchild, totgroup=0 /*, pa_num */;
1220
1221         int no_draw_flag = PARS_UNEXIST;
1222
1223         if (psys==NULL) return;
1224         
1225         /* simple preventing of too deep nested groups */
1226         if (level>MAX_DUPLI_RECUR) return;
1227         
1228         part=psys->part;
1229
1230         if (part==NULL)
1231                 return;
1232
1233         if (!psys_check_enabled(par, psys))
1234                 return;
1235
1236         if (G.rendering == 0)
1237                 no_draw_flag |= PARS_NO_DISP;
1238         
1239         ctime = BKE_curframe(scene); /* NOTE: in old animsys, used parent object's timeoffset... */
1240
1241         totpart = psys->totpart;
1242         totchild = psys->totchild;
1243
1244         BLI_srandom(31415926 + psys->seed);
1245
1246         if ((psys->renderdata || part->draw_as==PART_DRAW_REND) && ELEM(part->ren_as, PART_DRAW_OB, PART_DRAW_GR)) {
1247                 ParticleSimulationData sim= {NULL};
1248                 sim.scene= scene;
1249                 sim.ob= par;
1250                 sim.psys= psys;
1251                 sim.psmd= psys_get_modifier(par, psys);
1252                 /* make sure emitter imat is in global coordinates instead of render view coordinates */
1253                 invert_m4_m4(par->imat, par->obmat);
1254
1255                 /* first check for loops (particle system object used as dupli object) */
1256                 if (part->ren_as == PART_DRAW_OB) {
1257                         if (ELEM(part->dup_ob, NULL, par))
1258                                 return;
1259                 }
1260                 else { /*PART_DRAW_GR */
1261                         if (part->dup_group == NULL || part->dup_group->gobject.first == NULL)
1262                                 return;
1263
1264                         for (go=part->dup_group->gobject.first; go; go=go->next)
1265                                 if (go->ob == par)
1266                                         return;
1267                 }
1268
1269                 /* if we have a hair particle system, use the path cache */
1270                 if (part->type == PART_HAIR) {
1271                         if (psys->flag & PSYS_HAIR_DONE)
1272                                 hair= (totchild == 0 || psys->childcache) && psys->pathcache;
1273                         if (!hair)
1274                                 return;
1275                         
1276                         /* we use cache, update totchild according to cached data */
1277                         totchild = psys->totchildcache;
1278                         totpart = psys->totcached;
1279                 }
1280
1281                 psys_check_group_weights(part);
1282
1283                 psys->lattice = psys_get_lattice(&sim);
1284
1285                 /* gather list of objects or single object */
1286                 if (part->ren_as==PART_DRAW_GR) {
1287                         group_handle_recalc_and_update(scene, par, part->dup_group);
1288
1289                         if (part->draw & PART_DRAW_COUNT_GR) {
1290                                 for (dw=part->dupliweights.first; dw; dw=dw->next)
1291                                         totgroup += dw->count;
1292                         }
1293                         else {
1294                                 for (go=part->dup_group->gobject.first; go; go=go->next)
1295                                         totgroup++;
1296                         }
1297
1298                         /* we also copy the actual objects to restore afterwards, since
1299                          * where_is_object_time will change the object which breaks transform */
1300                         oblist = MEM_callocN(totgroup*sizeof(Object *), "dupgroup object list");
1301                         obcopylist = MEM_callocN(totgroup*sizeof(Object), "dupgroup copy list");
1302
1303                         
1304                         if (part->draw & PART_DRAW_COUNT_GR && totgroup) {
1305                                 dw = part->dupliweights.first;
1306
1307                                 for (a=0; a<totgroup; dw=dw->next) {
1308                                         for (b=0; b<dw->count; b++, a++) {
1309                                                 oblist[a] = dw->ob;
1310                                                 obcopylist[a] = *dw->ob;
1311                                         }
1312                                 }
1313                         }
1314                         else {
1315                                 go = part->dup_group->gobject.first;
1316                                 for (a=0; a<totgroup; a++, go=go->next) {
1317                                         oblist[a] = go->ob;
1318                                         obcopylist[a] = *go->ob;
1319                                 }
1320                         }
1321                 }
1322                 else {
1323                         ob = part->dup_ob;
1324                         obcopy = *ob;
1325                 }
1326
1327                 if (totchild==0 || part->draw & PART_DRAW_PARENT)
1328                         a = 0;
1329                 else
1330                         a = totpart;
1331
1332                 for (pa=psys->particles, counter=0; a<totpart+totchild; a++, pa++, counter++) {
1333                         if (a<totpart) {
1334                                 /* handle parent particle */
1335                                 if (pa->flag & no_draw_flag)
1336                                         continue;
1337
1338                                 /* pa_num = pa->num; */ /* UNUSED */
1339                                 pa_time = pa->time;
1340                                 size = pa->size;
1341                         }
1342                         else {
1343                                 /* handle child particle */
1344                                 cpa = &psys->child[a - totpart];
1345
1346                                 /* pa_num = a; */ /* UNUSED */
1347                                 pa_time = psys->particles[cpa->parent].time;
1348                                 size = psys_get_child_size(psys, cpa, ctime, NULL);
1349                         }
1350
1351                         /* some hair paths might be non-existent so they can't be used for duplication */
1352                         if (hair &&
1353                             ((a < totpart && psys->pathcache[a]->steps < 0) ||
1354                              (a >= totpart && psys->childcache[a-totpart]->steps < 0)))
1355                         {
1356                                 continue;
1357                         }
1358
1359                         if (part->ren_as==PART_DRAW_GR) {
1360                                 /* prevent divide by zero below [#28336] */
1361                                 if (totgroup == 0)
1362                                         continue;
1363
1364                                 /* for groups, pick the object based on settings */
1365                                 if (part->draw&PART_DRAW_RAND_GR)
1366                                         b= BLI_rand() % totgroup;
1367                                 else
1368                                         b= a % totgroup;
1369
1370                                 ob = oblist[b];
1371                                 obmat = oblist[b]->obmat;
1372                                 oldobmat = obcopylist[b].obmat;
1373                         }
1374                         else {
1375                                 obmat= ob->obmat;
1376                                 oldobmat= obcopy.obmat;
1377                         }
1378
1379                         if (hair) {
1380                                 /* hair we handle separate and compute transform based on hair keys */
1381                                 if (a < totpart) {
1382                                         cache = psys->pathcache[a];
1383                                         psys_get_dupli_path_transform(&sim, pa, NULL, cache, pamat, &scale);
1384                                 }
1385                                 else {
1386                                         cache = psys->childcache[a-totpart];
1387                                         psys_get_dupli_path_transform(&sim, NULL, cpa, cache, pamat, &scale);
1388                                 }
1389
1390                                 copy_v3_v3(pamat[3], cache->co);
1391                                 pamat[3][3]= 1.0f;
1392                                 
1393                         }
1394                         else {
1395                                 /* first key */
1396                                 state.time = ctime;
1397                                 if (psys_get_particle_state(&sim, a, &state, 0) == 0) {
1398                                         continue;
1399                                 }
1400                                 else {
1401                                         float tquat[4];
1402                                         normalize_qt_qt(tquat, state.rot);
1403                                         quat_to_mat4(pamat, tquat);
1404                                         copy_v3_v3(pamat[3], state.co);
1405                                         pamat[3][3]= 1.0f;
1406                                 }
1407                         }
1408
1409                         if (part->ren_as==PART_DRAW_GR && psys->part->draw & PART_DRAW_WHOLE_GR) {
1410                                 for (go= part->dup_group->gobject.first, b=0; go; go= go->next, b++) {
1411
1412                                         copy_m4_m4(tmat, oblist[b]->obmat);
1413                                         /* apply particle scale */
1414                                         mul_mat3_m4_fl(tmat, size*scale);
1415                                         mul_v3_fl(tmat[3], size*scale);
1416                                         /* group dupli offset, should apply after everything else */
1417                                         if (!is_zero_v3(part->dup_group->dupli_ofs))
1418                                                 sub_v3_v3v3(tmat[3], tmat[3], part->dup_group->dupli_ofs);
1419                                         /* individual particle transform */
1420                                         mult_m4_m4m4(tmat, pamat, tmat);
1421
1422                                         if (par_space_mat)
1423                                                 mult_m4_m4m4(mat, par_space_mat, tmat);
1424                                         else
1425                                                 copy_m4_m4(mat, tmat);
1426
1427                                         dob= new_dupli_object(lb, go->ob, mat, par->lay, counter, OB_DUPLIPARTS, animated);
1428                                         copy_m4_m4(dob->omat, obcopylist[b].obmat);
1429                                         if (G.rendering)
1430                                                 psys_get_dupli_texture(psys, part, sim.psmd, pa, cpa, dob->uv, dob->orco);
1431                                 }
1432                         }
1433                         else {
1434                                 /* to give ipos in object correct offset */
1435                                 where_is_object_time(scene, ob, ctime-pa_time);
1436
1437                                 copy_v3_v3(vec, obmat[3]);
1438                                 obmat[3][0] = obmat[3][1] = obmat[3][2] = 0.0f;
1439
1440                                 /* particle rotation uses x-axis as the aligned axis, so pre-rotate the object accordingly */
1441                                 if ((part->draw & PART_DRAW_ROTATE_OB) == 0) {
1442                                         float xvec[3], q[4];
1443                                         xvec[0] = -1.f;
1444                                         xvec[1] = xvec[2] = 0;
1445                                         vec_to_quat(q, xvec, ob->trackflag, ob->upflag);
1446                                         quat_to_mat4(obmat, q);
1447                                         obmat[3][3]= 1.0f;
1448                                 }
1449                                 
1450                                 /* Normal particles and cached hair live in global space so we need to
1451                                  * remove the real emitter's transformation before 2nd order duplication.
1452                                  */
1453                                 if (par_space_mat && GS(id->name) != ID_GR)
1454                                         mult_m4_m4m4(mat, psys->imat, pamat);
1455                                 else
1456                                         copy_m4_m4(mat, pamat);
1457
1458                                 mult_m4_m4m4(tmat, mat, obmat);
1459                                 mul_mat3_m4_fl(tmat, size*scale);
1460
1461                                 if (par_space_mat)
1462                                         mult_m4_m4m4(mat, par_space_mat, tmat);
1463                                 else
1464                                         copy_m4_m4(mat, tmat);
1465
1466                                 if (part->draw & PART_DRAW_GLOBAL_OB)
1467                                         add_v3_v3v3(mat[3], mat[3], vec);
1468
1469                                 dob= new_dupli_object(lb, ob, mat, ob->lay, counter, GS(id->name) == ID_GR ? OB_DUPLIGROUP : OB_DUPLIPARTS, animated);
1470                                 copy_m4_m4(dob->omat, oldobmat);
1471                                 if (G.rendering)
1472                                         psys_get_dupli_texture(psys, part, sim.psmd, pa, cpa, dob->uv, dob->orco);
1473                         }
1474                 }
1475
1476                 /* restore objects since they were changed in where_is_object_time */
1477                 if (part->ren_as==PART_DRAW_GR) {
1478                         for (a=0; a<totgroup; a++)
1479                                 *(oblist[a])= obcopylist[a];
1480                 }
1481                 else
1482                         *ob= obcopy;
1483         }
1484
1485         /* clean up */
1486         if (oblist)
1487                 MEM_freeN(oblist);
1488         if (obcopylist)
1489                 MEM_freeN(obcopylist);
1490
1491         if (psys->lattice) {
1492                 end_latt_deform(psys->lattice);
1493                 psys->lattice = NULL;
1494         }
1495 }
1496
1497 static Object *find_family_object(Object **obar, char *family, char ch)
1498 {
1499         Object *ob;
1500         int flen;
1501         
1502         if ( obar[(int)ch] ) return obar[(int)ch];
1503         
1504         flen= strlen(family);
1505         
1506         ob= G.main->object.first;
1507         while (ob) {
1508                 if (ob->id.name[flen + 2] == ch) {
1509                         if ( strncmp(ob->id.name+2, family, flen)==0 ) break;
1510                 }
1511                 ob= ob->id.next;
1512         }
1513         
1514         obar[(int)ch]= ob;
1515         
1516         return ob;
1517 }
1518
1519
1520 static void font_duplilist(ListBase *lb, Scene *scene, Object *par, int level, int animated)
1521 {
1522         Object *ob, *obar[256]= {NULL};
1523         Curve *cu;
1524         struct chartrans *ct, *chartransdata;
1525         float vec[3], obmat[4][4], pmat[4][4], fsize, xof, yof;
1526         int slen, a;
1527         
1528         /* simple preventing of too deep nested groups */
1529         if (level>MAX_DUPLI_RECUR) return;
1530         
1531         copy_m4_m4(pmat, par->obmat);
1532         
1533         /* in par the family name is stored, use this to find the other objects */
1534         
1535         chartransdata= BKE_text_to_curve(G.main, scene, par, FO_DUPLI);
1536         if (chartransdata==NULL) return;
1537
1538         cu= par->data;
1539         slen= strlen(cu->str);
1540         fsize= cu->fsize;
1541         xof= cu->xof;
1542         yof= cu->yof;
1543         
1544         ct= chartransdata;
1545         
1546         for (a=0; a<slen; a++, ct++) {
1547                 
1548                 ob= find_family_object(obar, cu->family, cu->str[a]);
1549                 if (ob) {
1550                         vec[0]= fsize*(ct->xof - xof);
1551                         vec[1]= fsize*(ct->yof - yof);
1552                         vec[2]= 0.0;
1553                         
1554                         mul_m4_v3(pmat, vec);
1555                         
1556                         copy_m4_m4(obmat, par->obmat);
1557                         copy_v3_v3(obmat[3], vec);
1558                         
1559                         new_dupli_object(lb, ob, obmat, par->lay, a, OB_DUPLIVERTS, animated);
1560                 }
1561         }
1562         
1563         MEM_freeN(chartransdata);
1564 }
1565
1566 /* ------------- */
1567
1568 static void object_duplilist_recursive(ID *id, Scene *scene, Object *ob, ListBase *duplilist, float par_space_mat[][4], int level, int animated)
1569 {       
1570         if ((ob->transflag & OB_DUPLI)==0)
1571                 return;
1572         
1573         /* Should the dupli's be generated for this object? - Respect restrict flags */
1574         if (G.rendering) {
1575                 if (ob->restrictflag & OB_RESTRICT_RENDER) {
1576                         return;
1577                 }
1578         }
1579         else {
1580                 if (ob->restrictflag & OB_RESTRICT_VIEW) {
1581                         return;
1582                 }
1583         }
1584
1585         if (ob->transflag & OB_DUPLIPARTS) {
1586                 ParticleSystem *psys = ob->particlesystem.first;
1587                 for (; psys; psys=psys->next)
1588                         new_particle_duplilist(duplilist, id, scene, ob, par_space_mat, psys, level+1, animated);
1589         }
1590         else if (ob->transflag & OB_DUPLIVERTS) {
1591                 if (ob->type==OB_MESH) {
1592                         vertex_duplilist(duplilist, id, scene, ob, par_space_mat, level+1, animated);
1593                 }
1594                 else if (ob->type==OB_FONT) {
1595                         if (GS(id->name)==ID_SCE) { /* TODO - support dupligroups */
1596                                 font_duplilist(duplilist, scene, ob, level+1, animated);
1597                         }
1598                 }
1599         }
1600         else if (ob->transflag & OB_DUPLIFACES) {
1601                 if (ob->type==OB_MESH)
1602                         face_duplilist(duplilist, id, scene, ob, par_space_mat, level+1, animated);
1603         }
1604         else if (ob->transflag & OB_DUPLIFRAMES) {
1605                 if (GS(id->name)==ID_SCE) { /* TODO - support dupligroups */
1606                         frames_duplilist(duplilist, scene, ob, level+1, animated);
1607                 }
1608         }
1609         else if (ob->transflag & OB_DUPLIGROUP) {
1610                 DupliObject *dob;
1611                 
1612                 group_duplilist(duplilist, scene, ob, level+1, animated); /* now recursive */
1613
1614                 if (level==0) {
1615                         for (dob= duplilist->first; dob; dob= dob->next)
1616                                 if (dob->type == OB_DUPLIGROUP)
1617                                         copy_m4_m4(dob->ob->obmat, dob->mat);
1618                 }
1619         }
1620 }
1621
1622 /* Returns a list of DupliObject
1623  * note; group dupli's already set transform matrix. see note in group_duplilist() */
1624 ListBase *object_duplilist(Scene *sce, Object *ob)
1625 {
1626         ListBase *duplilist= MEM_mallocN(sizeof(ListBase), "duplilist");
1627         duplilist->first= duplilist->last= NULL;
1628         object_duplilist_recursive((ID *)sce, sce, ob, duplilist, NULL, 0, 0);
1629         return duplilist;
1630 }
1631
1632 void free_object_duplilist(ListBase *lb)
1633 {
1634         DupliObject *dob;
1635         
1636         /* loop in reverse order, if object is instanced multiple times
1637          * the original layer may not really be original otherwise, proper
1638          * solution is more complicated */
1639         for (dob= lb->last; dob; dob= dob->prev) {
1640                 dob->ob->lay= dob->origlay;
1641                 copy_m4_m4(dob->ob->obmat, dob->omat);
1642         }
1643         
1644         BLI_freelistN(lb);
1645         MEM_freeN(lb);
1646 }
1647
1648 int count_duplilist(Object *ob)
1649 {
1650         if (ob->transflag & OB_DUPLI) {
1651                 if (ob->transflag & OB_DUPLIVERTS) {
1652                         if (ob->type==OB_MESH) {
1653                                 if (ob->transflag & OB_DUPLIVERTS) {
1654                                         ParticleSystem *psys = ob->particlesystem.first;
1655                                         int pdup=0;
1656
1657                                         for (; psys; psys=psys->next)
1658                                                 pdup += psys->totpart;
1659
1660                                         if (pdup==0) {
1661                                                 Mesh *me= ob->data;
1662                                                 return me->totvert;
1663                                         }
1664                                         else
1665                                                 return pdup;
1666                                 }
1667                         }
1668                 }
1669                 else if (ob->transflag & OB_DUPLIFRAMES) {
1670                         int tot= ob->dupend - ob->dupsta; 
1671                         tot/= (ob->dupon+ob->dupoff);
1672                         return tot*ob->dupon;
1673                 }
1674         }
1675         return 1;
1676 }