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