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