b2b52cfda0603024b4c4a7dfd6cb613f7c924781
[blender.git] / source / blender / blenkernel / intern / effect.c
1 /*  effect.c
2  * 
3  * 
4  * $Id$
5  *
6  * ***** BEGIN GPL/BL DUAL 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. The Blender
12  * Foundation also sells licenses for use in proprietary software under
13  * the Blender License.  See http://www.blender.org/BL/ for information
14  * about this.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software Foundation,
23  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
24  *
25  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
26  * All rights reserved.
27  *
28  * The Original Code is: all of this file.
29  *
30  * Contributor(s): none yet.
31  *
32  * ***** END GPL/BL DUAL LICENSE BLOCK *****
33  */
34
35 #include <math.h>
36 #include <stdlib.h>
37
38 #include "MEM_guardedalloc.h"
39 #include "DNA_listBase.h"
40 #include "DNA_effect_types.h"
41 #include "DNA_object_types.h"
42 #include "DNA_object_force.h"
43 #include "DNA_mesh_types.h"
44 #include "DNA_meshdata_types.h"
45 #include "DNA_material_types.h"
46 #include "DNA_curve_types.h"
47 #include "DNA_key_types.h"
48 #include "DNA_texture_types.h"
49 #include "DNA_scene_types.h"
50 #include "DNA_lattice_types.h"
51 #include "DNA_ipo_types.h"
52
53 #include "BLI_blenlib.h"
54 #include "BLI_arithb.h"
55 #include "BLI_rand.h"
56
57 #include "BKE_action.h"
58 #include "BKE_anim.h"           /* needed for where_on_path */
59 #include "BKE_armature.h"
60 #include "BKE_bad_level_calls.h"
61 #include "BKE_blender.h"
62 #include "BKE_constraint.h"
63 #include "BKE_deform.h"
64 #include "BKE_displist.h"
65 #include "BKE_DerivedMesh.h"
66 #include "BKE_effect.h"
67 #include "BKE_global.h"
68 #include "BKE_ipo.h"
69 #include "BKE_key.h"
70 #include "BKE_lattice.h"
71 #include "BKE_mesh.h"
72 #include "BKE_material.h"
73 #include "BKE_main.h"
74 #include "BKE_object.h"
75 #include "BKE_screen.h"
76 #include "BKE_utildefines.h"
77
78 #include "render.h"             // externtex, bad level call (ton)
79 #include "PIL_time.h"
80
81 /* temporal struct, used for reading return of mesh_get_mapped_verts_nors() */
82 typedef struct VeNoCo {
83         float co[3], no[3];
84 } VeNoCo;
85
86 Effect *add_effect(int type)
87 {
88         Effect *eff=0;
89         PartEff *paf;
90         int a;
91         
92         switch(type) {
93         case EFF_PARTICLE:
94                 paf= MEM_callocN(sizeof(PartEff), "neweff");
95                 eff= (Effect *)paf;
96                 
97                 paf->sta= 1.0;
98                 paf->end= 100.0;
99                 paf->lifetime= 50.0;
100                 for(a=0; a<PAF_MAXMULT; a++) {
101                         paf->life[a]= 50.0;
102                         paf->child[a]= 4;
103                         paf->mat[a]= 1;
104                 }
105                 
106                 paf->totpart= 1000;
107                 paf->totkey= 8;
108                 paf->staticstep= 5;
109                 paf->defvec[2]= 1.0f;
110                 paf->nabla= 0.05f;
111                 paf->disp = 100;
112                 paf->speedtex = 8;
113                 paf->omat = 1;
114                 paf->flag= PAF_FACE;
115
116                 break;
117         }
118         
119         eff->type= eff->buttype= type;
120         eff->flag |= SELECT;
121         
122         return eff;
123 }
124
125 void free_effect(Effect *eff)
126 {
127         PartEff *paf;
128         
129         if(eff->type==EFF_PARTICLE) {
130                 paf= (PartEff *)eff;
131                 if(paf->keys) MEM_freeN(paf->keys);
132         }
133         MEM_freeN(eff); 
134 }
135
136
137 void free_effects(ListBase *lb)
138 {
139         Effect *eff;
140         
141         eff= lb->first;
142         while(eff) {
143                 BLI_remlink(lb, eff);
144                 free_effect(eff);
145                 eff= lb->first;
146         }
147 }
148
149 Effect *copy_effect(Effect *eff) 
150 {
151         Effect *effn;
152
153         effn= MEM_dupallocN(eff);
154         if(effn->type==EFF_PARTICLE) ((PartEff *)effn)->keys= 0;
155
156         return effn;    
157 }
158
159 void copy_act_effect(Object *ob)
160 {
161         /* return a copy of the active effect */
162         Effect *effn, *eff;
163         
164         eff= ob->effect.first;
165         while(eff) {
166                 if(eff->flag & SELECT) {
167                         
168                         effn= copy_effect(eff);
169                         BLI_addtail(&ob->effect, effn);
170                         
171                         eff->flag &= ~SELECT;
172                         return;
173                         
174                 }
175                 eff= eff->next;
176         }
177         
178         /* when it comes here: add new effect */
179         eff= add_effect(EFF_PARTICLE);
180         BLI_addtail(&ob->effect, eff);
181                         
182 }
183
184 void copy_effects(ListBase *lbn, ListBase *lb)
185 {
186         Effect *eff, *effn;
187
188         lbn->first= lbn->last= 0;
189
190         eff= lb->first;
191         while(eff) {
192                 effn= copy_effect(eff);
193                 BLI_addtail(lbn, effn);
194                 
195                 eff= eff->next;
196         }
197         
198 }
199
200 void deselectall_eff(Object *ob)
201 {
202         Effect *eff= ob->effect.first;
203         
204         while(eff) {
205                 eff->flag &= ~SELECT;
206                 eff= eff->next;
207         }
208 }
209
210 /* ***************** PARTICLES ***************** */
211
212 static Particle *new_particle(PartEff *paf)
213 {
214         static Particle *pa;
215         static int cur;
216
217         /* we agree: when paf->keys==0: alloc */        
218         if(paf->keys==NULL) {
219                 pa= paf->keys= MEM_callocN( paf->totkey*paf->totpart*sizeof(Particle), "particlekeys" );
220                 cur= 0;
221         }
222         else {
223                 if(cur && cur<paf->totpart) pa+=paf->totkey;
224                 cur++;
225         }
226         return pa;
227 }
228
229 PartEff *give_parteff(Object *ob)
230 {
231         PartEff *paf;
232         
233         paf= ob->effect.first;
234         while(paf) {
235                 if(paf->type==EFF_PARTICLE) return paf;
236                 paf= paf->next;
237         }
238         return 0;
239 }
240
241 void where_is_particle(PartEff *paf, Particle *pa, float ctime, float *vec)
242 {
243         Particle *p[4];
244         float dt, t[4];
245         int a;
246         
247         if(paf->totkey==1 || ctime < pa->time) {
248                 VECCOPY(vec, pa->co);
249                 return;
250         }
251         
252         /* first find the first particlekey */
253         a= (int)((paf->totkey-1)*(ctime-pa->time)/pa->lifetime);
254         if(a>=paf->totkey) a= paf->totkey-1;
255         else if(a<0) a= 0;
256         
257         pa+= a;
258         
259         if(a>0) p[0]= pa-1; else p[0]= pa;
260         p[1]= pa;
261         
262         if(a+1<paf->totkey) p[2]= pa+1; else p[2]= pa;
263         if(a+2<paf->totkey) p[3]= pa+2; else p[3]= p[2];
264         
265         if(p[1]==p[2] || p[2]->time == p[1]->time) dt= 0.0;
266         else dt= (ctime-p[1]->time)/(p[2]->time - p[1]->time);
267
268         if(paf->flag & PAF_BSPLINE) set_four_ipo(dt, t, KEY_BSPLINE);
269         else set_four_ipo(dt, t, KEY_CARDINAL);
270
271         vec[0]= t[0]*p[0]->co[0] + t[1]*p[1]->co[0] + t[2]*p[2]->co[0] + t[3]*p[3]->co[0];
272         vec[1]= t[0]*p[0]->co[1] + t[1]*p[1]->co[1] + t[2]*p[2]->co[1] + t[3]*p[3]->co[1];
273         vec[2]= t[0]*p[0]->co[2] + t[1]*p[1]->co[2] + t[2]*p[2]->co[2] + t[3]*p[3]->co[2];
274
275 }
276
277 static void particle_tex(MTex *mtex, PartEff *paf, float *co, float *no)
278 {                               
279         float tin, tr, tg, tb, ta;
280         float old;
281         
282         externtex(mtex, co, &tin, &tr, &tg, &tb, &ta);
283
284         if(paf->texmap==PAF_TEXINT) {
285                 tin*= paf->texfac;
286                 no[0]+= tin*paf->defvec[0];
287                 no[1]+= tin*paf->defvec[1];
288                 no[2]+= tin*paf->defvec[2];
289         }
290         else if(paf->texmap==PAF_TEXRGB) {
291                 no[0]+= (tr-0.5f)*paf->texfac;
292                 no[1]+= (tg-0.5f)*paf->texfac;
293                 no[2]+= (tb-0.5f)*paf->texfac;
294         }
295         else {  /* PAF_TEXGRAD */
296                 
297                 old= tin;
298                 co[0]+= paf->nabla;
299                 externtex(mtex, co, &tin, &tr, &tg, &tb, &ta);
300                 no[0]+= (old-tin)*paf->texfac;
301                 
302                 co[0]-= paf->nabla;
303                 co[1]+= paf->nabla;
304                 externtex(mtex, co, &tin, &tr, &tg, &tb, &ta);
305                 no[1]+= (old-tin)*paf->texfac;
306                 
307                 co[1]-= paf->nabla;
308                 co[2]+= paf->nabla;
309                 externtex(mtex, co, &tin, &tr, &tg, &tb, &ta);
310                 no[2]+= (old-tin)*paf->texfac;
311                 
312         }
313 }
314
315 /* -------------------------- Effectors ------------------ */
316
317 typedef struct pEffectorCache {
318         struct pEffectorCache *next, *prev;
319         struct Object *ob;
320         
321         /* precalculated variables */
322         float oldloc[3], oldspeed[3];
323         float scale, time_scale;
324         float guide_dist;
325         
326         Object obcopy;  /* for restoring transformation data */
327 } pEffectorCache;
328
329
330 /* returns ListBase handle with objects taking part in the effecting */
331 ListBase *pdInitEffectors(Object *obsrc)
332 {
333         static ListBase listb={NULL, NULL};
334         pEffectorCache *ec;
335         unsigned int layer= obsrc->lay;
336         Base *base;
337
338         for(base = G.scene->base.first; base; base= base->next) {
339                 if( (base->lay & layer) && base->object->pd && base->object!=obsrc) {
340                         Object *ob= base->object;
341                         PartDeflect *pd= ob->pd;
342                         
343                         if(pd->forcefield == PFIELD_GUIDE) {
344                                 if(ob->type==OB_CURVE && obsrc->type==OB_MESH) {        /* guides only do mesh particles */
345                                         Curve *cu= ob->data;
346                                         if(cu->flag & CU_PATH) {
347                                                 if(cu->path==NULL || cu->path->data==NULL)
348                                                         makeDispListCurveTypes(ob, 0);
349                                                 if(cu->path && cu->path->data) {
350                                                         ec= MEM_callocN(sizeof(pEffectorCache), "effector cache");
351                                                         ec->ob= ob;
352                                                         BLI_addtail(&listb, ec);
353                                                 }
354                                         }
355                                 }
356                         }
357                         else if(pd->forcefield) {
358                                 ec= MEM_callocN(sizeof(pEffectorCache), "effector cache");
359                                 ec->ob= ob;
360                                 BLI_addtail(&listb, ec);
361                         }
362                 }
363         }
364
365         /* make a full copy */
366         for(ec= listb.first; ec; ec= ec->next) {
367                 ec->obcopy= *(ec->ob);
368         }
369
370         if(listb.first)
371                 return &listb;
372         
373         return NULL;
374 }
375
376 void pdEndEffectors(ListBase *lb)
377 {
378         if(lb) {
379                 pEffectorCache *ec;
380                 /* restore full copy */
381                 for(ec= lb->first; ec; ec= ec->next)
382                         *(ec->ob)= ec->obcopy;
383
384                 BLI_freelistN(lb);
385         }
386 }
387
388 /* local for this c file, only for guides now */
389 static void precalc_effectors(Object *ob, PartEff *paf, Particle *pa, ListBase *lb)
390 {
391         pEffectorCache *ec;
392         
393         for(ec= lb->first; ec; ec= ec->next) {
394                 PartDeflect *pd= ec->ob->pd;
395                 
396                 ec->oldspeed[0]= ec->oldspeed[1]= ec->oldspeed[2]= 0.0f;
397                 
398                 if(pd->forcefield==PFIELD_GUIDE && ec->ob->type==OB_CURVE) {
399                         float vec[4], dir[3];
400                                 
401                         /* scale corrects speed vector to curve size */
402                         if(paf->totkey>1) ec->scale= (paf->totkey-1)/pa->lifetime;
403                         else ec->scale= 1.0f;
404                         
405                         /* time_scale is for random life */
406                         if(pa->lifetime>paf->lifetime)
407                                 ec->time_scale= paf->lifetime/pa->lifetime;
408                         else
409                                 ec->time_scale= pa->lifetime/paf->lifetime;
410
411                         /* distance of first path point to particle origin */
412                         where_on_path(ec->ob, 0.0f, vec, dir);
413                         VECCOPY(ec->oldloc, vec);       /* store local coord for differences */
414                         Mat4MulVecfl(ec->ob->obmat, vec);
415                         
416                         /* for static we need to move to global space */
417                         if(paf->flag & PAF_STATIC) {
418                                 VECCOPY(dir, pa->co);
419                                 Mat4MulVecfl(ob->obmat, dir);
420                                 ec->guide_dist= VecLenf(vec, dir);
421                         }
422                         else 
423                                 ec->guide_dist= VecLenf(vec, pa->co);
424                 }
425         }
426 }
427
428
429 /*  -------- pdDoEffectors() --------
430     generic force/speed system, now used for particles and softbodies
431         lb                      = listbase with objects that take part in effecting
432         opco            = global coord, as input
433     force               = force accumulator
434     speed               = actual current speed which can be altered
435         cur_time        = "external" time in frames, is constant for static particles
436         loc_time        = "local" time in frames, range <0-1> for the lifetime of particle
437     par_layer   = layer the caller is in
438         flags           = only used for softbody wind now
439         guide           = old speed of particle
440
441 */
442 void pdDoEffectors(ListBase *lb, float *opco, float *force, float *speed, float cur_time, float loc_time, unsigned int flags)
443 {
444 /*
445         Modifies the force on a particle according to its
446         relation with the effector object
447         Different kind of effectors include:
448                 Forcefields: Gravity-like attractor
449                 (force power is related to the inverse of distance to the power of a falloff value)
450                 Vortex fields: swirling effectors
451                 (particles rotate around Z-axis of the object. otherwise, same relation as)
452                 (Forcefields, but this is not done through a force/acceleration)
453                 Guide: particles on a path
454                 (particles are guided along a curve bezier or old nurbs)
455                 (is independent of other effectors)
456 */
457         Object *ob;
458         pEffectorCache *ec;
459         PartDeflect *pd;
460         float vect_to_vert[3];
461         float f_force, force_vec[3];
462         float *obloc;
463         float distance, force_val, ffall_val;
464         float guidecollect[3], guidedist= 0.0f;
465         short cur_frame;
466         
467         guidecollect[0]= guidecollect[1]= guidecollect[2]=0.0f;
468
469         /* Cycle through collected objects, get total of (1/(gravity_strength * dist^gravity_power)) */
470         /* Check for min distance here? (yes would be cool to add that, ton) */
471         
472         for(ec = lb->first; ec; ec= ec->next) {
473                 /* object effectors were fully checked to be OK to evaluate! */
474                 ob= ec->ob;
475                 pd= ob->pd;
476                         
477                 /* Get IPO force strength and fall off values here */
478                 if (has_ipo_code(ob->ipo, OB_PD_FSTR))
479                         force_val = IPO_GetFloatValue(ob->ipo, OB_PD_FSTR, cur_time);
480                 else 
481                         force_val = pd->f_strength;
482                 
483                 if (has_ipo_code(ob->ipo, OB_PD_FFALL)) 
484                         ffall_val = IPO_GetFloatValue(ob->ipo, OB_PD_FFALL, cur_time);
485                 else 
486                         ffall_val = pd->f_power;
487                         
488                 /* Need to set r.cfra for paths (investigate, ton) (uses ob->ctime now, ton) */
489                 if(ob->ctime!=cur_time) {
490                         cur_frame = G.scene->r.cfra;
491                         G.scene->r.cfra = (short)cur_time;
492                         where_is_object_time(ob, cur_time);
493                         G.scene->r.cfra = cur_frame;
494                 }
495                         
496                 /* use center of object for distance calculus */
497                 obloc= ob->obmat[3];
498                 VECSUB(vect_to_vert, obloc, opco);
499                 distance = VecLength(vect_to_vert);
500                         
501                 if((pd->flag & PFIELD_USEMAX) && distance>pd->maxdist && pd->forcefield != PFIELD_GUIDE)
502                         ;       /* don't do anything */
503                 else if(pd->forcefield == PFIELD_WIND) {
504                         VECCOPY(force_vec, ob->obmat[2]);
505                         
506                         /* wind works harder perpendicular to normal, would be nice for softbody later (ton) */
507                         
508                         /* Limit minimum distance to vertex so that */
509                         /* the force is not too big */
510                         if (distance < 0.001) distance = 0.001f;
511                         f_force = (force_val)*(1/(1000 * (float)pow((double)distance, (double)ffall_val)));
512                         /* this option for softbody only */
513                         if(flags && PE_WIND_AS_SPEED){
514                                 speed[0] -= (force_vec[0] * f_force );
515                                 speed[1] -= (force_vec[1] * f_force );
516                                 speed[2] -= (force_vec[2] * f_force );
517                         }
518                         else{
519                                 force[0] += force_vec[0]*f_force;
520                                 force[1] += force_vec[1]*f_force;
521                                 force[2] += force_vec[2]*f_force;
522                         }
523                 }
524                 else if(pd->forcefield == PFIELD_FORCE) {
525                         
526                         /* only use center of object */
527                         obloc= ob->obmat[3];
528
529                         /* Now calculate the gravitational force */
530                         VECSUB(vect_to_vert, obloc, opco);
531                         distance = VecLength(vect_to_vert);
532
533                         /* Limit minimum distance to vertex so that */
534                         /* the force is not too big */
535                         if (distance < 0.001) distance = 0.001f;
536                         f_force = (force_val)*(1.0/(1000.0 * (float)pow((double)distance, (double)ffall_val)));
537                         force[0] += (vect_to_vert[0] * f_force );
538                         force[1] += (vect_to_vert[1] * f_force );
539                         force[2] += (vect_to_vert[2] * f_force );
540                 }
541                 else if(pd->forcefield == PFIELD_VORTEX) {
542                         float vortexvec[3];
543                         
544                         /* only use center of object */
545                         obloc= ob->obmat[3];
546
547                         /* Now calculate the vortex force */
548                         VECSUB(vect_to_vert, obloc, opco);
549                         distance = VecLength(vect_to_vert);
550
551                         Crossf(force_vec, ob->obmat[2], vect_to_vert);
552                         Normalise(force_vec);
553
554                         /* Limit minimum distance to vertex so that */
555                         /* the force is not too big */
556                         if (distance < 0.001) distance = 0.001f;
557                         f_force = (force_val)*(1.0/(100.0 * (float)pow((double)distance, (double)ffall_val)));
558                         vortexvec[0]= -(force_vec[0] * f_force );
559                         vortexvec[1]= -(force_vec[1] * f_force );
560                         vortexvec[2]= -(force_vec[2] * f_force );
561                         
562                         /* this option for softbody only */
563                         if(flags &&PE_WIND_AS_SPEED) {
564                                 speed[0]+= vortexvec[0];
565                                 speed[1]+= vortexvec[1];
566                                 speed[2]+= vortexvec[2];
567                         }
568                         else {
569                                 /* since vortex alters the speed, we have to correct for the previous vortex result */
570                                 speed[0]+= vortexvec[0] - ec->oldspeed[0];
571                                 speed[1]+= vortexvec[1] - ec->oldspeed[1];
572                                 speed[2]+= vortexvec[2] - ec->oldspeed[2];
573                                 
574                                 VECCOPY(ec->oldspeed, vortexvec);
575                         }
576                 }
577                 else if(pd->forcefield == PFIELD_GUIDE) {
578                         float guidevec[4], guidedir[3];
579                         float mindist= force_val; /* force_val is actually mindist in the UI */
580                         
581                         distance= ec->guide_dist;
582                         
583                         /* WARNING: bails out with continue here */
584                         if((pd->flag & PFIELD_USEMAX) && distance>pd->maxdist) continue;
585                         
586                         /* calculate contribution factor for this guide */
587                         if(distance<=mindist) f_force= 1.0f;
588                         else if(pd->flag & PFIELD_USEMAX) {
589                                 if(distance>pd->maxdist || mindist>=pd->maxdist) f_force= 0.0f;
590                                 else {
591                                         f_force= 1.0f - (distance-mindist)/(pd->maxdist - mindist);
592                                         if(ffall_val!=0.0f)
593                                                 f_force = (float)pow(f_force, ffall_val+1.0);
594                                 }
595                         }
596                         else {
597                                 f_force= 1.0f/(1.0f + distance-mindist);
598                                 if(ffall_val!=0.0f)
599                                         f_force = (float)pow(f_force, ffall_val+1.0);
600                         }
601                         
602                         /* now derive path point from loc_time */
603                         if(pd->flag & PFIELD_GUIDE_PATH_ADD)
604                                 where_on_path(ob, f_force*loc_time*ec->time_scale, guidevec, guidedir);
605                         else
606                                 where_on_path(ob, loc_time*ec->time_scale, guidevec, guidedir);
607                         
608                         VECSUB(guidedir, guidevec, ec->oldloc);
609                         VECCOPY(ec->oldloc, guidevec);
610                         
611                         Mat4Mul3Vecfl(ob->obmat, guidedir);
612                         VecMulf(guidedir, ec->scale);   /* correction for lifetime and speed */
613                         
614                         /* we subtract the speed we gave it previous step */
615                         VECCOPY(guidevec, guidedir);
616                         VECSUB(guidedir, guidedir, ec->oldspeed);
617                         VECCOPY(ec->oldspeed, guidevec);
618                         
619                         /* if it fully contributes, we stop */
620                         if(f_force==1.0) {
621                                 VECCOPY(guidecollect, guidedir);
622                                 guidedist= 1.0f;
623                                 break;
624                         }
625                         else if(guidedist<1.0f) {
626                                 VecMulf(guidedir, f_force);
627                                 VECADD(guidecollect, guidecollect, guidedir);
628                                 guidedist += f_force;
629                         }                                       
630                 }
631         }
632
633         /* all guides are accumulated here */
634         if(guidedist!=0.0f) {
635                 if(guidedist!=1.0f) VecMulf(guidecollect, 1.0f/guidedist);
636                 VECADD(speed, speed, guidecollect);
637         }
638 }
639
640 static void cache_object_vertices(Object *ob)
641 {
642         Mesh *me;
643         MVert *mvert;
644         float *fp;
645         int a;
646         
647         me= ob->data;
648         if(me->totvert==0) return;
649
650         fp= ob->sumohandle= MEM_mallocN(3*sizeof(float)*me->totvert, "cache particles");
651         mvert= me->mvert;
652         a= me->totvert;
653         while(a--) {
654                 VECCOPY(fp, mvert->co);
655                 Mat4MulVecfl(ob->obmat, fp);
656                 mvert++;
657                 fp+= 3;
658         }
659 }
660
661 static int pdDoDeflection(RNG *rng, float opco[3], float npco[3], float opno[3],
662         float npno[3], float life, float force[3], int def_depth,
663         float cur_time, unsigned int par_layer, int *last_object,
664                 int *last_face, int *same_face)
665 {
666         /* Particle deflection code */
667         /* The code is in two sections: the first part checks whether a particle has            */
668         /* intersected a face of a deflector mesh, given its old and new co-ords, opco and npco */
669         /* and which face it hit first                                                          */
670         /* The second part calculates the new co-ordinates given that collision and updates     */
671         /* the new co-ordinates accordingly */
672         Base *base;
673         Object *ob, *deflection_object = NULL;
674         Mesh *def_mesh;
675         MFace *mface, *deflection_face = NULL;
676         float *v1, *v2, *v3, *v4, *vcache=NULL;
677         float nv1[3], nv2[3], nv3[3], nv4[3], edge1[3], edge2[3];
678         float dv1[3], dv2[3], dv3[3];
679         float vect_to_int[3], refl_vel[3];
680         float d_intersect_co[3], d_intersect_vect[3], d_nvect[3], d_i_co_above[3];
681         float forcec[3];
682         float k_point3, dist_to_plane;
683         float first_dist, ref_plane_mag;
684         float dk_plane=0, dk_point1=0;
685         float icalctop, icalcbot, n_mag;
686         float mag_iv, x_m,y_m,z_m;
687         float damping, perm_thresh;
688         float perm_val, rdamp_val;
689         int a, deflected=0, deflected_now=0;
690         float t,t2, min_t;
691         float mat[3][3], obloc[3];
692         short cur_frame;
693         float time_before, time_after;
694         float force_mag_norm;
695         int d_object=0, d_face=0, ds_object=0, ds_face=0;
696
697         first_dist = 200000;
698         min_t = 200000;
699
700         /* The first part of the code, finding the first intersected face*/
701         base= G.scene->base.first;
702         while (base) {
703                 /*Only proceed for mesh object in same layer */
704                 if(base->object->type==OB_MESH && (base->lay & par_layer)) {
705                         ob= base->object;
706                         /* only with deflecting set */
707                         if(ob->pd && ob->pd->deflect) {
708                                 def_mesh= ob->data;
709                         
710                                 d_object = d_object + 1;
711
712                                 d_face = d_face + 1;
713                                 mface= def_mesh->mface;
714                                 a = def_mesh->totface;
715                                 
716                                 
717                                 if(ob->parent==NULL && ob->ipo==NULL) { // static
718                                         if(ob->sumohandle==NULL) cache_object_vertices(ob);
719                                         vcache= ob->sumohandle;
720                                 }
721                                 else {
722                                         /*Find out where the object is at this time*/
723                                         cur_frame = G.scene->r.cfra;
724                                         G.scene->r.cfra = (short)cur_time;
725                                         where_is_object_time(ob, cur_time);
726                                         G.scene->r.cfra = cur_frame;
727                                         
728                                         /*Pass the values from ob->obmat to mat*/
729                                         /*and the location values to obloc           */
730                                         Mat3CpyMat4(mat,ob->obmat);
731                                         obloc[0] = ob->obmat[3][0];
732                                         obloc[1] = ob->obmat[3][1];
733                                         obloc[2] = ob->obmat[3][2];
734                                         vcache= NULL;
735
736                                 }
737                                 
738                                 while (a--) {
739
740                                         if(vcache) {
741                                                 v1= vcache+ 3*(mface->v1);
742                                                 VECCOPY(nv1, v1);
743                                                 v1= vcache+ 3*(mface->v2);
744                                                 VECCOPY(nv2, v1);
745                                                 v1= vcache+ 3*(mface->v3);
746                                                 VECCOPY(nv3, v1);
747                                                 v1= vcache+ 3*(mface->v4);
748                                                 VECCOPY(nv4, v1);
749                                         }
750                                         else {
751                                                 /* Calculate the global co-ordinates of the vertices*/
752                                                 v1= (def_mesh->mvert+(mface->v1))->co;
753                                                 v2= (def_mesh->mvert+(mface->v2))->co;
754                                                 v3= (def_mesh->mvert+(mface->v3))->co;
755                                                 v4= (def_mesh->mvert+(mface->v4))->co;
756         
757                                                 VECCOPY(nv1, v1);
758                                                 VECCOPY(nv2, v2);
759                                                 VECCOPY(nv3, v3);
760                                                 VECCOPY(nv4, v4);
761         
762                                                 /*Apply the objects deformation matrix*/
763                                                 Mat3MulVecfl(mat, nv1);
764                                                 Mat3MulVecfl(mat, nv2);
765                                                 Mat3MulVecfl(mat, nv3);
766                                                 Mat3MulVecfl(mat, nv4);
767         
768                                                 VECADD(nv1, nv1, obloc);
769                                                 VECADD(nv2, nv2, obloc);
770                                                 VECADD(nv3, nv3, obloc);
771                                                 VECADD(nv4, nv4, obloc);
772                                         }
773                                         
774                                         deflected_now = 0;
775
776                                                 
777                                                 
778 //                                      t= 0.5; // this is labda of line, can use it optimize quad intersection
779 // sorry but no .. see below (BM)                                       
780                                         if( LineIntersectsTriangle(opco, npco, nv1, nv2, nv3, &t) ) {
781                                                 if (t < min_t) {
782                                                         deflected = 1;
783                                                         deflected_now = 1;
784                                                 }
785                                         }
786 //                                      else if (mface->v4 && (t>=0.0 && t<=1.0)) {
787 // no, you can't skip testing the other triangle
788 // it might give a smaller t on (close to) the edge .. this is numerics not esoteric maths :)
789 // note: the 2 triangles don't need to share a plane ! (BM)
790                                         if (mface->v4) {
791                                                 if( LineIntersectsTriangle(opco, npco, nv1, nv3, nv4, &t2) ) {
792                                                         if (t2 < min_t) {
793                                                                 deflected = 1;
794                                                                 deflected_now = 2;
795                                                         }
796                                                 }
797                                         }
798                                         
799                                         if ((deflected_now > 0) && ((t < min_t) ||(t2 < min_t))) {
800                         min_t = t;
801                         ds_object = d_object;
802                                                 ds_face = d_face;
803                                                 deflection_object = ob;
804                                                 deflection_face = mface;
805                                                 if (deflected_now==1) {
806                         min_t = t;
807                                                         VECCOPY(dv1, nv1);
808                                                         VECCOPY(dv2, nv2);
809                                                         VECCOPY(dv3, nv3);
810                                                 }
811                                                 else {
812                         min_t = t2;
813                                                         VECCOPY(dv1, nv1);
814                                                         VECCOPY(dv2, nv3);
815                                                         VECCOPY(dv3, nv4);
816                                                 }
817                                         }
818                                         mface++;
819                                 }
820                         }
821                 }
822                 base = base->next;
823         }
824
825
826         /* Here's the point to do the permeability calculation */
827         /* Set deflected to 0 if a random number is below the value */
828         /* Get the permeability IPO here*/
829         if (deflected) {
830                 
831                 if (has_ipo_code(deflection_object->ipo, OB_PD_PERM)) 
832                         perm_val = IPO_GetFloatValue(deflection_object->ipo, OB_PD_PERM, cur_time);
833                 else 
834                         perm_val = deflection_object->pd->pdef_perm;
835
836                 perm_thresh = rng_getFloat(rng) - perm_val;
837                 if (perm_thresh < 0 ) {
838                         deflected = 0;
839                 }
840         }
841
842         /* Now for the second part of the deflection code - work out the new speed */
843         /* and position of the particle if a collision occurred */
844         if (deflected) {
845         VECSUB(edge1, dv1, dv2);
846                 VECSUB(edge2, dv3, dv2);
847                 Crossf(d_nvect, edge2, edge1);
848                 n_mag = Normalise(d_nvect);
849                 dk_plane = INPR(d_nvect, nv1);
850                 dk_point1 = INPR(d_nvect,opco);
851
852                 VECSUB(d_intersect_vect, npco, opco);
853
854                 d_intersect_co[0] = opco[0] + (min_t * (npco[0] - opco[0]));
855                 d_intersect_co[1] = opco[1] + (min_t * (npco[1] - opco[1]));
856                 d_intersect_co[2] = opco[2] + (min_t * (npco[2] - opco[2]));
857                 
858                 d_i_co_above[0] = (d_intersect_co[0] + (0.001f * d_nvect[0]));
859                 d_i_co_above[1] = (d_intersect_co[1] + (0.001f * d_nvect[1]));
860                 d_i_co_above[2] = (d_intersect_co[2] + (0.001f * d_nvect[2]));
861                 mag_iv = Normalise(d_intersect_vect);
862                 VECCOPY(npco, d_intersect_co);
863                 
864                 VECSUB(vect_to_int, opco, d_intersect_co);
865                 first_dist = Normalise(vect_to_int);
866
867                 /* Work out the lengths of time before and after collision*/
868                 time_before = (life*(first_dist / (mag_iv)));
869                 time_after =  (life*((mag_iv - first_dist) / (mag_iv)));
870
871                 /* We have to recalculate what the speed would have been at the */
872                 /* point of collision, not the key frame time */
873                 npno[0]= opno[0] + time_before*force[0];
874                 npno[1]= opno[1] + time_before*force[1];
875                 npno[2]= opno[2] + time_before*force[2];
876
877
878                 /* Reflect the speed vector in the face */
879                 x_m = (2 * npno[0] * d_nvect[0]);
880                 y_m = (2 * npno[1] * d_nvect[1]);
881                 z_m = (2 * npno[2] * d_nvect[2]);
882                 refl_vel[0] = npno[0] - (d_nvect[0] * (x_m + y_m + z_m));
883                 refl_vel[1] = npno[1] - (d_nvect[1] * (x_m + y_m + z_m));
884                 refl_vel[2] = npno[2] - (d_nvect[2] * (x_m + y_m + z_m));
885
886                 /*A random variation in the damping factor........ */
887                 /*Get the IPO values for damping here*/
888                 
889                 if (has_ipo_code(deflection_object->ipo, OB_PD_SDAMP)) 
890                         damping = IPO_GetFloatValue(deflection_object->ipo, OB_PD_SDAMP, cur_time);
891                 else 
892                         damping = deflection_object->pd->pdef_damp;
893                 
894                 if (has_ipo_code(deflection_object->ipo, OB_PD_RDAMP)) 
895                         rdamp_val = IPO_GetFloatValue(deflection_object->ipo, OB_PD_RDAMP, cur_time);
896                 else 
897                         rdamp_val = deflection_object->pd->pdef_rdamp;
898
899                 damping = damping + ((1.0f - damping) * rng_getFloat(rng) *rdamp_val);
900                 damping = damping * damping;
901         ref_plane_mag = INPR(refl_vel,d_nvect);
902
903                 if (damping > 0.999) damping = 0.999f;
904
905                 /* Now add in the damping force - only damp in the direction of */
906                 /* the faces normal vector */
907                 npno[0] = (refl_vel[0] - (d_nvect[0] * ref_plane_mag * damping));
908                 npno[1] = (refl_vel[1] - (d_nvect[1] * ref_plane_mag * damping));
909                 npno[2] = (refl_vel[2] - (d_nvect[2] * ref_plane_mag * damping));
910
911                 /* Now reset opno */
912                 VECCOPY(opno,npno);
913                 VECCOPY(forcec, force);
914
915                 /* If the particle has bounced more than four times on the same */
916                 /* face within this cycle (depth > 4, same face > 4 )           */
917                 /* Then set the force to be only that component of the force    */
918                 /* in the same direction as the face normal                     */
919                 /* i.e. subtract the component of the force in the direction    */
920                 /* of the face normal from the actual force                     */
921                 if ((ds_object == *last_object) && (ds_face == *last_face)) {
922                         /* Increment same_face */
923                         *same_face = *same_face + 1;
924                         if ((*same_face > 3) && (def_depth > 3)) {
925                 force_mag_norm = INPR(forcec, d_nvect);
926                 forcec[0] = forcec[0] - (d_nvect[0] * force_mag_norm);
927                 forcec[1] = forcec[1] - (d_nvect[1] * force_mag_norm);
928                 forcec[2] = forcec[2] - (d_nvect[2] * force_mag_norm);
929                         }
930                 }
931                 else *same_face = 1;
932
933                 *last_object = ds_object;
934                 *last_face = ds_face;
935
936                 /* We have the particles speed at the point of collision    */
937                 /* Now we want the particles speed at the current key frame */
938
939                 npno[0]= npno[0] + time_after*forcec[0];
940                 npno[1]= npno[1] + time_after*forcec[1];
941                 npno[2]= npno[2] + time_after*forcec[2];
942
943                 /* Now we have to recalculate pa->co for the remainder*/
944                 /* of the time since the intersect*/
945                 npco[0]= npco[0] + time_after*npno[0];
946                 npco[1]= npco[1] + time_after*npno[1];
947                 npco[2]= npco[2] + time_after*npno[2];
948
949                 /* And set the old co-ordinates back to the point just above the intersection */
950                 VECCOPY(opco, d_i_co_above);
951
952                 /* Finally update the time */
953                 life = time_after;
954                 cur_time += time_before;
955
956                 /* The particle may have fallen through the face again by now!!*/
957                 /* So check if the particle has changed sides of the plane compared*/
958                 /* the co-ordinates at the last keyframe*/
959                 /* But only do this as a last resort, if we've got to the end of the */
960                 /* number of collisions allowed */
961                 if (def_depth==9) {
962                         k_point3 = INPR(d_nvect,npco);
963                         if (((dk_plane > k_point3) && (dk_plane < dk_point1))||((dk_plane < k_point3) && (dk_plane > dk_point1))) {
964
965                                 /* Yup, the pesky particle may have fallen through a hole!!! */
966                 /* So we'll cheat a bit and move the particle along the normal vector */
967                 /* until it's just the other side of the plane */
968                 icalctop = (dk_plane - d_nvect[0]*npco[0] - d_nvect[1]*npco[1] - d_nvect[2]*npco[2]);
969                 icalcbot = (d_nvect[0]*d_nvect[0] + d_nvect[1]*d_nvect[1] + d_nvect[2]*d_nvect[2]);
970                 dist_to_plane = icalctop / icalcbot;
971
972                 /*  Now just increase the distance a little to place */
973                 /* the point the other side of the plane */
974                 dist_to_plane *= 1.1f;
975                 npco[0]= npco[0] + (dist_to_plane * d_nvect[0]);
976                 npco[1]= npco[1] + (dist_to_plane * d_nvect[1]);
977                 npco[2]= npco[2] + (dist_to_plane * d_nvect[2]);
978
979                         }
980                 }
981         }
982         return deflected;
983 }
984
985 /*
986         rng= random number generator
987         ob = object that spawns the particles
988         depth = for fireworks
989         nr = index nr of current particle
990         paf = the particle system
991         part = current particle
992         force = force vector
993         deform = flag to indicate lattice deform
994  */
995 static void make_particle_keys(RNG *rng, Object *ob, int depth, int nr, PartEff *paf, Particle *part, float *force, int deform, MTex *mtex, ListBase *effectorbase)
996 {
997         Particle *pa, *opa = NULL;
998         float damp, deltalife, life;
999         float cur_time;
1000         float opco[3], opno[3], npco[3], npno[3], new_force[3], new_speed[3];
1001         int b, rt1, rt2, deflected, deflection, finish_defs, def_count;
1002         int last_ob, last_fc, same_fc;
1003
1004         damp= 1.0f-paf->damp;
1005         pa= part;
1006
1007         /* start speed: random */
1008         if(paf->randfac!=0.0) {
1009                 pa->no[0]+= paf->randfac*(rng_getFloat(rng) - 0.5f);
1010                 pa->no[1]+= paf->randfac*(rng_getFloat(rng) - 0.5f);
1011                 pa->no[2]+= paf->randfac*(rng_getFloat(rng) - 0.5f);
1012         }
1013
1014         /* start speed: texture */
1015         if(mtex && paf->texfac!=0.0) {
1016                 particle_tex(mtex, paf, pa->co, pa->no);
1017         }
1018
1019         /* effectors here? */
1020         if(effectorbase)
1021                 precalc_effectors(ob, paf, pa, effectorbase);
1022         
1023         if(paf->totkey>1) deltalife= pa->lifetime/(paf->totkey-1);
1024         else deltalife= pa->lifetime;
1025
1026         /* longer lifetime results in longer distance covered */
1027         VecMulf(pa->no, deltalife);
1028         
1029         opa= pa;
1030         pa++;
1031
1032         for(b=1; b<paf->totkey; b++) {
1033
1034                 /* new time */
1035                 pa->time= opa->time+deltalife;
1036                 cur_time = pa->time;
1037
1038                 /* set initial variables                                */
1039                 VECCOPY(opco, opa->co);
1040                 VECCOPY(new_force, force);
1041                 VECCOPY(new_speed, opa->no);
1042                 VecMulf(new_speed, 1.0f/deltalife);
1043                 //new_speed[0] = new_speed[1] = new_speed[2] = 0.0f;
1044
1045                 /* handle differences between static (local coords, fixed frame) and dynamic */
1046                 if(effectorbase) {
1047                         float loc_time= ((float)b)/(float)(paf->totkey-1);
1048                         
1049                         if(paf->flag & PAF_STATIC) {
1050                                 float opco1[3], new_force1[3];
1051                                 
1052                                 /* move co and force to global coords */
1053                                 VECCOPY(opco1, opco);
1054                                 Mat4MulVecfl(ob->obmat, opco1);
1055                                 VECCOPY(new_force1, new_force);
1056                                 Mat4Mul3Vecfl(ob->obmat, new_force1);
1057                                 Mat4Mul3Vecfl(ob->obmat, new_speed);
1058                                 
1059                                 cur_time = G.scene->r.cfra;
1060                                 
1061                                 /* force fields */
1062                                 pdDoEffectors(effectorbase, opco1, new_force1, new_speed, cur_time, loc_time, 0);
1063                                 
1064                                 /* move co, force and newspeed back to local */
1065                                 VECCOPY(opco, opco1);
1066                                 Mat4MulVecfl(ob->imat, opco);
1067                                 VECCOPY(new_force, new_force1);
1068                                 Mat4Mul3Vecfl(ob->imat, new_force);
1069                                 Mat4Mul3Vecfl(ob->imat, new_speed);
1070                         }
1071                         else {
1072                                  /* force fields */
1073                                 pdDoEffectors(effectorbase, opco, new_force, new_speed, cur_time, loc_time, 0);
1074                         }
1075                 }
1076                 
1077                 /* new speed */
1078                 pa->no[0]= deltalife * (new_speed[0] + new_force[0]);
1079                 pa->no[1]= deltalife * (new_speed[1] + new_force[1]);
1080                 pa->no[2]= deltalife * (new_speed[2] + new_force[2]);
1081                 
1082                 /* new location */
1083                 pa->co[0]= opa->co[0] + pa->no[0];
1084                 pa->co[1]= opa->co[1] + pa->no[1];
1085                 pa->co[2]= opa->co[2] + pa->no[2];
1086
1087                 /* Particle deflection code */
1088                 if((paf->flag & PAF_STATIC)==0) {
1089                         deflection = 0;
1090                         finish_defs = 1;
1091                         def_count = 0;
1092
1093                         VECCOPY(opno, opa->no);
1094                         VECCOPY(npco, pa->co);
1095                         VECCOPY(npno, pa->no);
1096
1097                         life = deltalife;
1098                         cur_time -= deltalife;
1099
1100                         last_ob = -1;
1101                         last_fc = -1;
1102                         same_fc = 0;
1103
1104                         /* First call the particle deflection check for the particle moving   */
1105                         /* between the old co-ordinates and the new co-ordinates              */
1106                         /* If a deflection occurs, call the code again, this time between the */
1107                         /* intersection point and the updated new co-ordinates                */
1108                         /* Bail out if we've done the calculation 10 times - this seems ok     */
1109                         /* for most scenes I've tested */
1110                         while (finish_defs) {
1111                                 deflected =  pdDoDeflection(rng, opco, npco, opno, npno, life, new_force,
1112                                                                 def_count, cur_time, ob->lay,
1113                                                                 &last_ob, &last_fc, &same_fc);
1114                                 if (deflected) {
1115                                         def_count = def_count + 1;
1116                                         deflection = 1;
1117                                         if (def_count==10) finish_defs = 0;
1118                                 }
1119                                 else {
1120                                         finish_defs = 0;
1121                                 }
1122                         }
1123
1124                         /* Only update the particle positions and speed if we had a deflection */
1125                         if (deflection) {
1126                                 pa->co[0] = npco[0];
1127                                 pa->co[1] = npco[1];
1128                                 pa->co[2] = npco[2];
1129                                 pa->no[0] = npno[0];
1130                                 pa->no[1] = npno[1];
1131                                 pa->no[2] = npno[2];
1132                         }
1133                 }
1134                 
1135                 /* speed: texture */
1136                 if(mtex && paf->texfac!=0.0) {
1137                         particle_tex(mtex, paf, pa->co, pa->no);
1138                 }
1139                 if(damp!=1.0) {
1140                         pa->no[0]*= damp;
1141                         pa->no[1]*= damp;
1142                         pa->no[2]*= damp;
1143                 }
1144                 
1145                 opa= pa;
1146                 pa++;
1147                 /* opa is used later on too! */
1148         }
1149
1150         if(deform) {
1151                 /* deform all keys */
1152                 pa= part;
1153                 b= paf->totkey;
1154                 while(b--) {
1155                         calc_latt_deform(pa->co, 1.0f);
1156                         pa++;
1157                 }
1158         }
1159         
1160         /* the big multiplication */
1161         if(depth<PAF_MAXMULT && paf->mult[depth]!=0.0) {
1162                 
1163                 /* new 'child' emerges from an average 'mult' part from 
1164                         the particles */
1165                 damp = (float)nr;
1166                 rt1= (int)(damp*paf->mult[depth]);
1167                 rt2= (int)((damp+1.0)*paf->mult[depth]);
1168                 if(rt1!=rt2) {
1169                         
1170                         for(b=0; b<paf->child[depth]; b++) {
1171                                 pa= new_particle(paf);
1172                                 *pa= *opa;
1173                                 pa->lifetime= paf->life[depth];
1174                                 if(paf->randlife!=0.0) {
1175                                         pa->lifetime*= 1.0f + paf->randlife*(rng_getFloat(rng) - 0.5f);
1176                                 }
1177                                 pa->mat_nr= paf->mat[depth];
1178
1179                                 make_particle_keys(rng, ob, depth+1, b, paf, pa, force, deform, mtex, effectorbase);
1180                         }
1181                 }
1182         }
1183 }
1184
1185 static void init_mv_jit(float *jit, int num, int seed2)
1186 {
1187         RNG *rng;
1188         float *jit2, x, rad1, rad2, rad3;
1189         int i, num2;
1190
1191         if(num==0) return;
1192
1193         rad1= (float)(1.0/sqrt((float)num));
1194         rad2= (float)(1.0/((float)num));
1195         rad3= (float)sqrt((float)num)/((float)num);
1196
1197         rng = rng_new(31415926 + num + seed2);
1198         x= 0;
1199         num2 = 2 * num;
1200         for(i=0; i<num2; i+=2) {
1201         
1202                 jit[i]= x + rad1*(0.5f - rng_getFloat(rng));
1203                 jit[i+1]= i/(2.0f*num) + rad1*(0.5f - rng_getFloat(rng));
1204                 
1205                 jit[i]-= (float)floor(jit[i]);
1206                 jit[i+1]-= (float)floor(jit[i+1]);
1207                 
1208                 x+= rad3;
1209                 x -= (float)floor(x);
1210         }
1211
1212         jit2= MEM_mallocN(12 + 2*sizeof(float)*num, "initjit");
1213
1214         for (i=0 ; i<4 ; i++) {
1215                 RE_jitterate1(jit, jit2, num, rad1);
1216                 RE_jitterate1(jit, jit2, num, rad1);
1217                 RE_jitterate2(jit, jit2, num, rad2);
1218         }
1219         MEM_freeN(jit2);
1220         rng_free(rng);
1221 }
1222
1223 #define JIT_RAND        32
1224
1225 /* for a position within a face, tot is total amount of faces */
1226 static void give_mesh_particle_coord(PartEff *paf, VeNoCo *noco, MFace *mface, int partnr, int subnr, float *co, float *no)
1227 {
1228         static float *jit= NULL;
1229         static float *trands= NULL;
1230         static int jitlevel= 1;
1231         float *v1, *v2, *v3, *v4;
1232         float u, v;
1233         float *n1, *n2, *n3, *n4;
1234         
1235         /* free signal */
1236         if(paf==NULL) {
1237                 if(jit) MEM_freeN(jit);
1238                 jit= NULL;
1239                 if(trands) MEM_freeN(trands);
1240                 trands= NULL;
1241                 return;
1242         }
1243         
1244         /* first time initialize jitter or trand, partnr then is total amount of particles, subnr total amount of faces */
1245         if(trands==NULL && jit==NULL) {
1246                 RNG *rng = rng_new(31415926 + paf->seed);
1247                 int i, tot;
1248
1249                 if(paf->flag & PAF_TRAND)
1250                         tot= partnr;
1251                 else 
1252                         tot= JIT_RAND;  /* arbitrary... allows JIT_RAND times more particles in a face for jittered distro */
1253                         
1254                 trands= MEM_callocN(2+2*tot*sizeof(float), "trands");
1255                 for(i=0; i<tot; i++) {
1256                         trands[2*i]= rng_getFloat(rng);
1257                         trands[2*i+1]= rng_getFloat(rng);
1258                 }
1259                 rng_free(rng);
1260
1261                 if((paf->flag & PAF_TRAND)==0) {
1262                         jitlevel= paf->userjit;
1263                         
1264                         if(jitlevel == 0) {
1265                                 jitlevel= partnr/subnr;
1266                                 if(paf->flag & PAF_EDISTR) jitlevel*= 2;        /* looks better in general, not very scietific */
1267                                 if(jitlevel<3) jitlevel= 3;
1268                                 if(jitlevel>100) jitlevel= 100;
1269                         }
1270                         
1271                         jit= MEM_callocN(2+ jitlevel*2*sizeof(float), "jit");
1272                         init_mv_jit(jit, jitlevel, paf->seed);
1273                         BLI_array_randomize(jit, 2*sizeof(float), jitlevel, paf->seed); /* for custom jit or even distribution */
1274                 }
1275                 return;
1276         }
1277         
1278         if(paf->flag & PAF_TRAND) {
1279                 u= trands[2*partnr];
1280                 v= trands[2*partnr+1];
1281         }
1282         else {
1283                 /* jittered distribution gets fixed random offset */
1284                 if(subnr>=jitlevel) {
1285                         int jitrand= (subnr/jitlevel) % JIT_RAND;
1286                 
1287                         subnr %= jitlevel;
1288                         u= jit[2*subnr] + trands[2*jitrand];
1289                         v= jit[2*subnr+1] + trands[2*jitrand+1];
1290                         if(u > 1.0f) u-= 1.0f;
1291                         if(v > 1.0f) v-= 1.0f;
1292                 }
1293                 else {
1294                         u= jit[2*subnr];
1295                         v= jit[2*subnr+1];
1296                 }
1297         }
1298         
1299         v1= (noco+(mface->v1))->co;
1300         v2= (noco+(mface->v2))->co;
1301         v3= (noco+(mface->v3))->co;
1302         n1= (noco+(mface->v1))->no;
1303         n2= (noco+(mface->v2))->no;
1304         n3= (noco+(mface->v3))->no;
1305         
1306         if(mface->v4) {
1307                 float uv= u*v;
1308                 float muv= (1.0f-u)*(v);
1309                 float umv= (u)*(1.0f-v);
1310                 float mumv= (1.0f-u)*(1.0f-v);
1311                 
1312                 v4= (noco+(mface->v4))->co;
1313                 n4= (noco+(mface->v4))->no;
1314                 
1315                 co[0]= mumv*v1[0] + muv*v2[0] + uv*v3[0] + umv*v4[0];
1316                 co[1]= mumv*v1[1] + muv*v2[1] + uv*v3[1] + umv*v4[1];
1317                 co[2]= mumv*v1[2] + muv*v2[2] + uv*v3[2] + umv*v4[2];
1318
1319                 no[0]= mumv*n1[0] + muv*n2[0] + uv*n3[0] + umv*n4[0];
1320                 no[1]= mumv*n1[1] + muv*n2[1] + uv*n3[1] + umv*n4[1];
1321                 no[2]= mumv*n1[2] + muv*n2[2] + uv*n3[2] + umv*n4[2];
1322         }
1323         else {
1324                 /* mirror triangle uv coordinates when on other side */
1325                 if(u + v > 1.0f) {
1326                         u= 1.0f-u;
1327                         v= 1.0f-v;
1328                 }
1329                 co[0]= v1[0] + u*(v3[0]-v1[0]) + v*(v2[0]-v1[0]);
1330                 co[1]= v1[1] + u*(v3[1]-v1[1]) + v*(v2[1]-v1[1]);
1331                 co[2]= v1[2] + u*(v3[2]-v1[2]) + v*(v2[2]-v1[2]);
1332                 
1333                 no[0]= n1[0] + u*(n3[0]-n1[0]) + v*(n2[0]-n1[0]);
1334                 no[1]= n1[1] + u*(n3[1]-n1[1]) + v*(n2[1]-n1[1]);
1335                 no[2]= n1[2] + u*(n3[2]-n1[2]) + v*(n2[2]-n1[2]);
1336         }
1337 }
1338
1339
1340 /* Gets a MDeformVert's weight in group (0 if not in group) */
1341 /* note; this call could be in mesh.c or deform.c, but OK... it's in armature.c too! (ton) */
1342 static float vert_weight(MDeformVert *dvert, int group)
1343 {
1344         MDeformWeight *dw;
1345         int i;
1346         
1347         if(dvert) {
1348                 dw= dvert->dw;
1349                 for(i= dvert->totweight; i>0; i--, dw++) {
1350                         if(dw->def_nr == group) return dw->weight;
1351                         if(i==1) break; /*otherwise dw will point to somewhere it shouldn't*/
1352                 }
1353         }
1354         return 0.0;
1355 }
1356
1357 /* Gets a faces average weight in a group, helper for below, face and weights are always set */
1358 static float face_weight(MFace *face, float *weights)
1359 {
1360         float tweight;
1361         
1362         tweight = weights[face->v1] + weights[face->v2] + weights[face->v3];
1363         
1364         if(face->v4) {
1365                 tweight += weights[face->v4];
1366                 tweight /= 4.0;
1367         }
1368         else {
1369                 tweight /= 3.0;
1370         }
1371
1372         return tweight;
1373 }
1374
1375 /* helper function for build_particle_system() */
1376 static void make_weight_tables(PartEff *paf, Mesh *me, int totpart, VeNoCo *vertlist, int totvert, MFace *facelist, int totface, float **vweights, float **fweights)
1377 {
1378         MFace *mface;
1379         float *foweights=NULL, *voweights=NULL;
1380         float totvweight=0.0f, totfweight=0.0f;
1381         int a;
1382         
1383         if((paf->flag & PAF_FACE)==0) totface= 0;
1384         
1385         /* collect emitting vertices & faces if vert groups used */
1386         if(paf->vertgroup && me->dvert) {
1387                 
1388                 /* allocate weights array for all vertices, also for lookup of faces later on. note it's a malloc */
1389                 *vweights= voweights= MEM_mallocN( totvert*sizeof(float), "pafvoweights" );
1390                 totvweight= 0.0f;
1391                 for(a=0; a<totvert; a++) {
1392                         voweights[a]= vert_weight(me->dvert+a, paf->vertgroup-1);
1393                         totvweight+= voweights[a];
1394                 }
1395                 
1396                 if(totface) {
1397                         /* allocate weights array for faces, note it's a malloc */
1398                         *fweights= foweights= MEM_mallocN(totface*sizeof(float), "paffoweights" );
1399                         for(a=0, mface=facelist; a<totface; a++, mface++) {
1400                                 foweights[a] = face_weight(mface, voweights);
1401                         }
1402                 }
1403         }
1404         
1405         /* make weights for faces or for even area distribution */
1406         if(totface && (paf->flag & PAF_EDISTR)) {
1407                 float maxfarea= 0.0f, curfarea;
1408                 
1409                 /* two cases for area distro, second case we already have group weights */
1410                 if(foweights==NULL) {
1411                         /* allocate weights array for faces, note it's a malloc */
1412                         *fweights= foweights= MEM_mallocN(totface*sizeof(float), "paffoweights" );
1413                         
1414                         for(a=0, mface=facelist; a<totface; a++, mface++) {
1415                                 if (mface->v4)
1416                                         curfarea= AreaQ3Dfl(vertlist[mface->v1].co, vertlist[mface->v2].co, vertlist[mface->v3].co, vertlist[mface->v4].co);
1417                                 else
1418                                         curfarea= AreaT3Dfl(vertlist[mface->v1].co,  vertlist[mface->v2].co, vertlist[mface->v3].co);
1419                                 if(curfarea>maxfarea)
1420                                         maxfarea = curfarea;
1421                                 foweights[a]= curfarea;
1422                         }
1423                 }
1424                 else {
1425                         for(a=0, mface=facelist; a<totface; a++, mface++) {
1426                                 if(foweights[a]!=0.0f) {
1427                                         if (mface->v4)
1428                                                 curfarea= AreaQ3Dfl(vertlist[mface->v1].co, vertlist[mface->v2].co, vertlist[mface->v3].co, vertlist[mface->v4].co);
1429                                         else
1430                                                 curfarea= AreaT3Dfl(vertlist[mface->v1].co,  vertlist[mface->v2].co, vertlist[mface->v3].co);
1431                                         if(curfarea>maxfarea)
1432                                                 maxfarea = curfarea;
1433                                         foweights[a]*= curfarea;
1434                                 }
1435                         }
1436                 }
1437                 
1438                 /* normalize weights for max face area, calculate tot */
1439                 if(maxfarea!=0.0f) {
1440                         maxfarea= 1.0f/maxfarea;
1441                         for(a=0; a< totface; a++) {
1442                                 if(foweights[a]!=0.0) {
1443                                         foweights[a] *= maxfarea;
1444                                         totfweight+= foweights[a];
1445                                 }
1446                         }
1447                 }
1448         }
1449         else if(foweights) {
1450                 /* only add totfweight value */
1451                 for(a=0; a< totface; a++) {
1452                         if(foweights[a]!=0.0) {
1453                                 totfweight+= foweights[a];
1454                         }
1455                 }
1456         }
1457         
1458         /* if weight arrays, we turn these arrays into the amount of particles */
1459         if(totvert && voweights) {
1460                 float mult= (float)totpart/totvweight;
1461                 
1462                 for(a=0; a< totvert; a++) {
1463                         if(voweights[a]!=0.0)
1464                                 voweights[a] *= mult;
1465                 }
1466         }
1467         
1468         if(totface && foweights) {
1469                 float mult= (float)totpart/totfweight;
1470                 
1471                 for(a=0; a< totface; a++) {
1472                         if(foweights[a]!=0.0)
1473                                 foweights[a] *= mult;
1474                 }
1475         }
1476 }
1477
1478 /* helper function for build_particle_system() */
1479 static void make_length_tables(PartEff *paf, Mesh *me, int totvert, MFace *facelist, int totface, float **vlengths, float **flengths)
1480 {
1481         MFace *mface;
1482         float *folengths=NULL, *volengths=NULL;
1483         int a;
1484         
1485         if((paf->flag & PAF_FACE)==0) totface= 0;
1486         
1487         /* collect emitting vertices & faces if vert groups used */
1488         if(paf->vertgroup_v && me->dvert) {
1489                 
1490                 /* allocate lengths array for all vertices, also for lookup of faces later on. note it's a malloc */
1491                 *vlengths= volengths= MEM_mallocN( totvert*sizeof(float), "pafvolengths" );
1492                 for(a=0; a<totvert; a++) {
1493                         volengths[a]= vert_weight(me->dvert+a, paf->vertgroup_v-1);
1494                 }
1495                 
1496                 if(totface) {
1497                         /* allocate lengths array for faces, note it's a malloc */
1498                         *flengths= folengths= MEM_mallocN(totface*sizeof(float), "paffolengths" );
1499                         for(a=0, mface=facelist; a<totface; a++, mface++) {
1500                                 folengths[a] = face_weight(mface, volengths);
1501                         }
1502                 }
1503         }
1504 }
1505
1506
1507 /* for paf start to end, store all matrices for objects */
1508 typedef struct pMatrixCache {
1509         float obmat[4][4];
1510         float imat[3][3];
1511 } pMatrixCache;
1512
1513 static pMatrixCache *cache_object_matrices(Object *ob, int start, int end)
1514 {
1515         pMatrixCache *mcache, *mc;
1516         Object *par;
1517         float framelenold, sfrao;
1518         int cfrao;
1519         
1520         mcache= mc= MEM_mallocN( (end-start+1)*sizeof(pMatrixCache), "ob matrix cache");
1521         
1522         framelenold= G.scene->r.framelen;
1523         G.scene->r.framelen= 1.0f;
1524         cfrao= G.scene->r.cfra;
1525         sfrao= ob->sf;
1526         ob->sf= 0.0f;
1527         
1528         for(G.scene->r.cfra= start; G.scene->r.cfra<=end; G.scene->r.cfra++, mc++) {
1529                 
1530                 par= ob;
1531                 while(par) {
1532                         par->ctime= -1234567.0;         /* hrms? */
1533                         do_ob_key(par);
1534                         if(par->type==OB_ARMATURE) {
1535                                 do_all_pose_actions(par);       // only does this object actions
1536                                 where_is_pose(par);
1537                         }
1538                         par= par->parent;
1539                 }
1540
1541                 where_is_object(ob);
1542                 Mat4CpyMat4(mc->obmat, ob->obmat);
1543                 Mat4Invert(ob->imat, ob->obmat);
1544                 Mat3CpyMat4(mc->imat, ob->imat);
1545                 Mat3Transp(mc->imat);
1546         }
1547         
1548         
1549         /* restore */
1550         G.scene->r.cfra= cfrao;
1551         G.scene->r.framelen= framelenold;
1552         ob->sf= sfrao;
1553         
1554         /* restore hierarchy */
1555         par= ob;
1556         while(par) {
1557                 /* do not do ob->ipo: keep insertkey */
1558                 par->ctime= -1234567.0;         /* hrms? */
1559                 do_ob_key(par);
1560                 
1561                 if(par->type==OB_ARMATURE) {
1562                         do_all_pose_actions(par);       // only does this object actions
1563                         where_is_pose(par);
1564                 }
1565                 par= par->parent;
1566         }
1567         
1568         where_is_object(ob);
1569         
1570         return mcache;
1571 }
1572
1573 /* main particle building function 
1574    one day particles should become dynamic (realtime) with the current method as a 'bake' (ton) */
1575 void build_particle_system(Object *ob)
1576 {
1577         RNG *rng;
1578         PartEff *paf;
1579         Particle *pa;
1580         Mesh *me;
1581         Base *base;
1582         MTex *mtexmove=0, *mtextime=0;
1583         Material *ma;
1584         MFace *facelist= NULL;
1585         pMatrixCache *mcache=NULL, *mcnow, *mcprev;
1586         ListBase *effectorbase;
1587         VeNoCo *vertexcosnos;
1588         double startseconds= PIL_check_seconds_timer();
1589         float ftime, dtime, force[3], vec[3], fac, co[3], no[3];
1590         float *voweights= NULL, *foweights= NULL, maxw=1.0f;
1591         float *volengths= NULL, *folengths= NULL;
1592         int deform=0, a, totpart, paf_sta, paf_end;
1593         int waitcursor_set= 0, totvert, totface, curface, curvert;
1594         
1595         /* return conditions */
1596         if(ob->type!=OB_MESH) return;
1597         me= ob->data;
1598
1599         paf= give_parteff(ob);
1600         if(paf==NULL) return;
1601         if(paf->keys) MEM_freeN(paf->keys);     /* free as early as possible, for returns */
1602         paf->keys= NULL;
1603         
1604         if(paf->end < paf->sta) return;
1605         
1606         if( (paf->flag & PAF_OFACE) && (paf->flag & PAF_FACE)==0) return;
1607         
1608         if(me->totvert==0) return;
1609         
1610         if(ob==G.obedit) return;
1611         
1612         totpart= (R.flag & R_RENDERING)?paf->totpart:(paf->disp*paf->totpart)/100;
1613         if(totpart==0) return;
1614         
1615         /* No returns after this line! */
1616         
1617         /* material */
1618         ma= give_current_material(ob, paf->omat);
1619         if(ma) {
1620                 if(paf->speedtex)
1621                         mtexmove= ma->mtex[paf->speedtex-1];
1622                 mtextime= ma->mtex[paf->timetex-1];
1623         }
1624
1625         disable_speed_curve(1); /* check this... */
1626
1627         /* initialize particles */
1628         new_particle(paf);
1629
1630         /* reset deflector cache, sumohandle is free, but its still sorta abuse... (ton) */
1631         for(base= G.scene->base.first; base; base= base->next)
1632                 base->object->sumohandle= NULL;
1633
1634         /* all object positions from start to end */
1635         paf_sta= (int)floor(paf->sta);
1636         paf_end= (int)ceil(paf->end);
1637         if((paf->flag & PAF_STATIC)==0)
1638                 mcache= cache_object_matrices(ob, paf_sta, paf_end);
1639         
1640         /* mult generations? */
1641         for(a=0; a<PAF_MAXMULT; a++) {
1642                 if(paf->mult[a]!=0.0) {
1643                         /* interesting formula! this way after 'x' generations the total is paf->totpart */
1644                         totpart= (int)(totpart / (1.0+paf->mult[a]*paf->child[a]));
1645                 }
1646                 else break;
1647         }
1648
1649         /* for static particles, calculate system on current frame (? ton) */
1650         if(ma) do_mat_ipo(ma);
1651         
1652         /* matrix invert for static too */
1653         Mat4Invert(ob->imat, ob->obmat);
1654         
1655         /* new random generator */
1656         rng = rng_new(paf->seed);
1657         
1658         /* otherwise it goes way too fast */
1659         force[0]= paf->force[0]*0.05f;
1660         force[1]= paf->force[1]*0.05f;
1661         force[2]= paf->force[2]*0.05f;
1662         
1663         if( paf->flag & PAF_STATIC ) deform= 0;
1664         else {
1665                 deform= (ob->parent && ob->parent->type==OB_LATTICE && ob->partype==PARSKEL);
1666                 if(deform) init_latt_deform(ob->parent, 0);
1667         }
1668         
1669         /* get the effectors */
1670         effectorbase= pdInitEffectors(ob);
1671         
1672         /* init geometry, return is 6 x float * me->totvert in size */
1673         vertexcosnos= (VeNoCo *)mesh_get_mapped_verts_nors(ob);
1674         facelist= me->mface;
1675         totvert= me->totvert;
1676         totface= me->totface;
1677         
1678         /* if vertexweights or even distribution, it makes weight tables, also checks where it emits from */
1679         make_weight_tables(paf, me, totpart, vertexcosnos, totvert, facelist, totface, &voweights, &foweights);
1680         
1681         /* vertexweights can define lengths too */
1682         make_length_tables(paf, me, totvert, facelist, totface, &volengths, &folengths);
1683         
1684         /* now define where to emit from, if there are face weights we skip vertices */
1685         if(paf->flag & PAF_OFACE) totvert= 0;
1686         if((paf->flag & PAF_FACE)==0) totface= 0;
1687         if(foweights) totvert= 0;
1688         
1689         /* initialize give_mesh_particle_coord */
1690         if(totface)
1691                 give_mesh_particle_coord(paf, vertexcosnos, facelist, totpart, totface, NULL, NULL);
1692         
1693         /* correction for face timing when using weighted average */
1694         if(totface && foweights) {
1695                 maxw= (paf->end-paf->sta)/foweights[0];
1696         }
1697         else if(totvert && voweights) {
1698                 maxw= (paf->end-paf->sta)/voweights[0];
1699         }
1700         
1701         /* for loop below */
1702         if (paf->flag & PAF_STATIC) {
1703                 ftime = G.scene->r.cfra;
1704                 dtime= 0.0f;
1705         } else {
1706                 ftime= paf->sta;
1707                 dtime= (paf->end - paf->sta)/(float)totpart;
1708         }
1709         
1710         curface= curvert= 0;
1711         for(a=0; a<totpart; a++, ftime+=dtime) {
1712                 
1713                 /* we set waitcursor only when a half second expired, particles now are realtime updated */
1714                 if(waitcursor_set==0 && (a % 256)==255) {
1715                         double seconds= PIL_check_seconds_timer();
1716                         if(seconds - startseconds > 0.5) {
1717                                 waitcursor(1);
1718                                 waitcursor_set= 1;
1719                         }
1720                 }
1721                 
1722                 pa= new_particle(paf);
1723                 pa->time= ftime;
1724
1725                 /* get coordinates from faces, only when vertices set to zero */
1726                 if(totvert==0 && totface) {
1727                         int curjit;
1728                         
1729                         /* use weight table, we have to do faces in order to be able to use jitter table... */
1730                         if(foweights) {
1731                                 
1732                                 if(foweights[curface] < 1.0f) {
1733                                         float remainder= 0.0f;
1734                                         
1735                                         while(remainder + foweights[curface] < 1.0f && curface<totface-1) {
1736                                                 remainder += foweights[curface];
1737                                                 curface++;
1738                                         }
1739                                         foweights[curface] += remainder;
1740                                         maxw= (paf->end-paf->sta)/foweights[curface];
1741                                 }
1742                                 
1743                                 if(foweights[curface]==0.0f)
1744                                         break;  /* WARN skips here out of particle generating */
1745                                 else {
1746                                         if(foweights[curface] > 1.0f)
1747                                                 foweights[curface] -= 1.0f;
1748                                         
1749                                         curjit= (int) foweights[curface];
1750                                         give_mesh_particle_coord(paf, vertexcosnos, facelist+curface, a, curjit, co, no);
1751                                         
1752                                         /* time correction to make particles appear evenly, maxw does interframe (0-1) */
1753                                         pa->time= paf->sta + maxw*foweights[curface];
1754                                 }
1755                         }
1756                         else {
1757                                 curface= a % totface;
1758                                 curjit= a/totface;
1759                                 give_mesh_particle_coord(paf, vertexcosnos, facelist+curface, a, curjit, co, no);
1760                         }
1761                 }
1762                 /* get coordinates from vertices */
1763                 if(totvert) {
1764                         /* use weight table */
1765                         if(voweights) {
1766                                 
1767                                 if(voweights[curvert] < 1.0f) {
1768                                         float remainder= 0.0f;
1769                                         
1770                                         while(remainder + voweights[curvert] < 1.0f && curvert<totvert-1) {
1771                                                 remainder += voweights[curvert];
1772                                                 curvert++;
1773                                         }
1774                                         voweights[curvert] += remainder;
1775                                         maxw= (paf->end-paf->sta)/voweights[curvert];
1776                                 }
1777                                 
1778                                 if(voweights[curvert]==0.0f)
1779                                         break;  /* WARN skips here out of particle generating */
1780                                 else {
1781                                         if(voweights[curvert] > 1.0f)
1782                                                 voweights[curvert] -= 1.0f;
1783                                         
1784                                         /* time correction to make particles appear evenly */
1785                                         pa->time= paf->sta + maxw*voweights[curvert];
1786                                 }
1787                         }
1788                         else {
1789                                 curvert= a % totvert;
1790                                 if(a >= totvert && totface)
1791                                         totvert= 0;
1792                         }
1793                         
1794                         VECCOPY(co, vertexcosnos[curvert].co);
1795                         VECCOPY(no, vertexcosnos[curvert].no);
1796                 }
1797                 
1798                 VECCOPY(pa->co, co);
1799                 
1800                 /* dynamic options */
1801                 if((paf->flag & PAF_STATIC)==0) {
1802                         int cur;
1803                         
1804                         /* particle retiming with texture */
1805                         if(mtextime && (paf->flag2 & PAF_TEXTIME)) {
1806                                 float tin, tr, tg, tb, ta, orco[3];
1807                                 
1808                                 /* calculate normalized orco */
1809                                 orco[0] = (co[0]-me->loc[0])/me->size[0];
1810                                 orco[1] = (co[1]-me->loc[1])/me->size[1];
1811                                 orco[2] = (co[2]-me->loc[2])/me->size[2];
1812                                 externtex(mtextime, orco, &tin, &tr, &tg, &tb, &ta);
1813                                 
1814                                 if(paf->flag2neg & PAF_TEXTIME)
1815                                         pa->time = paf->sta + (paf->end - paf->sta)*tin;
1816                                 else
1817                                         pa->time = paf->sta + (paf->end - paf->sta)*(1.0f-tin);
1818                         }
1819
1820                         /* set ob at correct time, we use cached matrices */
1821                         cur= (int)floor(pa->time) + 1 ;         /* + 1 has a reason: (obmat/prevobmat) otherwise comet-tails start too late */
1822                         
1823                         if(cur <= paf_end) mcnow= mcache + cur - paf_sta;
1824                         else mcnow= mcache + paf_end - paf_sta + 1;
1825                         
1826                         if(cur > paf_sta) mcprev= mcnow-1;
1827                         else mcprev= mcache;
1828                         
1829                         /* move to global space */
1830                         Mat4MulVecfl(mcnow->obmat, pa->co);
1831                 
1832                         VECCOPY(vec, co);
1833                         Mat4MulVecfl(mcprev->obmat, vec);
1834                         
1835                         /* first start speed: object */
1836                         VECSUB(pa->no, pa->co, vec);
1837
1838                         VecMulf(pa->no, paf->obfac);
1839                         
1840                         /* calculate the correct inter-frame */ 
1841                         fac= (pa->time- (float)floor(pa->time));
1842                         pa->co[0]= fac*pa->co[0] + (1.0f-fac)*vec[0];
1843                         pa->co[1]= fac*pa->co[1] + (1.0f-fac)*vec[1];
1844                         pa->co[2]= fac*pa->co[2] + (1.0f-fac)*vec[2];
1845
1846                         /* start speed: normal */
1847                         if(paf->normfac!=0.0) {
1848                                 /* imat is transpose ! */
1849                                 VECCOPY(vec, no);
1850                                 Mat3MulVecfl(mcnow->imat, vec);
1851                         
1852                                 Normalise(vec);
1853                                 VecMulf(vec, paf->normfac);
1854                                 VECADD(pa->no, pa->no, vec);
1855                         }
1856                 }
1857                 else {
1858                         if(paf->normfac!=0.0) {
1859                                 VECCOPY(pa->no, no);
1860                                 Normalise(pa->no);
1861                                 VecMulf(pa->no, paf->normfac);
1862                         }
1863                 }
1864                 
1865                 pa->lifetime= paf->lifetime;
1866                 if(paf->randlife!=0.0) {
1867                         pa->lifetime*= 1.0f + paf->randlife*(rng_getFloat(rng) - 0.5f);
1868                 }
1869                 pa->mat_nr= paf->omat;
1870                 
1871                 if(folengths)
1872                         pa->lifetime*= folengths[curface];
1873
1874                 make_particle_keys(rng, ob, 0, a, paf, pa, force, deform, mtexmove, effectorbase);
1875         }
1876         
1877         /* free stuff */
1878         give_mesh_particle_coord(NULL, NULL, NULL, 0, 0, NULL, NULL);
1879         MEM_freeN(vertexcosnos);
1880         if(voweights) MEM_freeN(voweights);
1881         if(foweights) MEM_freeN(foweights);
1882         if(volengths) MEM_freeN(volengths);
1883         if(folengths) MEM_freeN(folengths);
1884         if(mcache) MEM_freeN(mcache);
1885         rng_free(rng);
1886
1887         if(deform) end_latt_deform();
1888         
1889         if(effectorbase)
1890                 pdEndEffectors(effectorbase);   
1891         
1892         /* reset deflector cache */
1893         for(base= G.scene->base.first; base; base= base->next) {
1894                 if(base->object->sumohandle) {
1895                         MEM_freeN(base->object->sumohandle);
1896                         base->object->sumohandle= NULL;
1897                 }
1898         }
1899
1900         disable_speed_curve(0);
1901         
1902         if(waitcursor_set) waitcursor(0);
1903 }
1904