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