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