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