322904136eaa902f30704619457e18487fdcbfd8
[blender-staging.git] / source / blender / blenkernel / intern / particle.c
1 /* particle.c
2  *
3  *
4  * $Id$
5  *
6  * ***** BEGIN GPL LICENSE BLOCK *****
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License
10  * as published by the Free Software Foundation; either version 2
11  * of the License, or (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software Foundation,
20  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
21  *
22  * The Original Code is Copyright (C) 2007 by Janne Karhu.
23  * All rights reserved.
24  *
25  * The Original Code is: all of this file.
26  *
27  * Contributor(s): none yet.
28  *
29  * ***** END GPL LICENSE BLOCK *****
30  */
31
32 #include <stdlib.h>
33 #include <math.h>
34 #include <string.h>
35
36 #include "MEM_guardedalloc.h"
37
38 #include "DNA_scene_types.h"
39 #include "DNA_boid_types.h"
40 #include "DNA_group_types.h"
41 #include "DNA_particle_types.h"
42 #include "DNA_mesh_types.h"
43 #include "DNA_meshdata_types.h"
44 #include "DNA_modifier_types.h"
45 #include "DNA_object_force.h"
46 #include "DNA_texture_types.h"
47 #include "DNA_material_types.h"
48 #include "DNA_object_types.h"
49 #include "DNA_curve_types.h"
50 #include "DNA_key_types.h"
51 #include "DNA_ipo_types.h"      // XXX old animation system stuff to remove!
52
53 #include "BLI_arithb.h"
54 #include "BLI_blenlib.h"
55 #include "BLI_dynstr.h"
56 #include "BLI_kdtree.h"
57 #include "BLI_listbase.h"
58 #include "BLI_rand.h"
59 #include "BLI_threads.h"
60
61 #include "BKE_anim.h"
62
63 #include "BKE_boids.h"
64 #include "BKE_cloth.h"
65 #include "BKE_effect.h"
66 #include "BKE_global.h"
67 #include "BKE_group.h"
68 #include "BKE_main.h"
69 #include "BKE_lattice.h"
70 #include "BKE_utildefines.h"
71 #include "BKE_displist.h"
72 #include "BKE_particle.h"
73 #include "BKE_DerivedMesh.h"
74 #include "BKE_object.h"
75 #include "BKE_cloth.h"
76 #include "BKE_material.h"
77 #include "BKE_key.h"
78 #include "BKE_library.h"
79 #include "BKE_depsgraph.h"
80 #include "BKE_modifier.h"
81 #include "BKE_mesh.h"
82 #include "BKE_cdderivedmesh.h"
83 #include "BKE_pointcache.h"
84
85 #include "RE_render_ext.h"
86
87 static void get_cpa_texture(DerivedMesh *dm, Material *ma, int face_index,
88                                 float *fuv, float *orco, ParticleTexture *ptex, int event);
89 static void get_child_modifier_parameters(ParticleSettings *part, ParticleThreadContext *ctx,
90                                 ChildParticle *cpa, short cpa_from, int cpa_num, float *cpa_fuv, float *orco, ParticleTexture *ptex);
91 static void do_child_modifiers(ParticleSimulationData *sim,
92                                 ParticleTexture *ptex, ParticleKey *par, float *par_rot, ChildParticle *cpa,
93                                 float *orco, float mat[4][4], ParticleKey *state, float t);
94
95 /* few helpers for countall etc. */
96 int count_particles(ParticleSystem *psys){
97         ParticleSettings *part=psys->part;
98         PARTICLE_P;
99         int tot=0;
100
101         LOOP_SHOWN_PARTICLES {
102                 if(pa->alive == PARS_UNBORN && (part->flag & PART_UNBORN)==0);
103                 else if(pa->alive == PARS_DEAD && (part->flag & PART_DIED)==0);
104                 else tot++;
105         }
106         return tot;
107 }
108 int count_particles_mod(ParticleSystem *psys, int totgr, int cur){
109         ParticleSettings *part=psys->part;
110         PARTICLE_P;
111         int tot=0;
112
113         LOOP_SHOWN_PARTICLES {
114                 if(pa->alive == PARS_UNBORN && (part->flag & PART_UNBORN)==0);
115                 else if(pa->alive == PARS_DEAD && (part->flag & PART_DIED)==0);
116                 else if(p%totgr==cur) tot++;
117         }
118         return tot;
119 }
120 /* we allocate path cache memory in chunks instead of a big continguous
121  * chunk, windows' memory allocater fails to find big blocks of memory often */
122
123 #define PATH_CACHE_BUF_SIZE 1024
124
125 static ParticleCacheKey **psys_alloc_path_cache_buffers(ListBase *bufs, int tot, int steps)
126 {
127         LinkData *buf;
128         ParticleCacheKey **cache;
129         int i, totkey, totbufkey;
130
131         tot= MAX2(tot, 1);
132         totkey = 0;
133         cache = MEM_callocN(tot*sizeof(void*), "PathCacheArray");
134
135         while(totkey < tot) {
136                 totbufkey= MIN2(tot-totkey, PATH_CACHE_BUF_SIZE);
137                 buf= MEM_callocN(sizeof(LinkData), "PathCacheLinkData");
138                 buf->data= MEM_callocN(sizeof(ParticleCacheKey)*totbufkey*steps, "ParticleCacheKey");
139
140                 for(i=0; i<totbufkey; i++)
141                         cache[totkey+i] = ((ParticleCacheKey*)buf->data) + i*steps;
142
143                 totkey += totbufkey;
144                 BLI_addtail(bufs, buf);
145         }
146
147         return cache;
148 }
149
150 static void psys_free_path_cache_buffers(ParticleCacheKey **cache, ListBase *bufs)
151 {
152         LinkData *buf;
153
154         if(cache)
155                 MEM_freeN(cache);
156
157         for(buf= bufs->first; buf; buf=buf->next)
158                 MEM_freeN(buf->data);
159         BLI_freelistN(bufs);
160 }
161
162 /************************************************/
163 /*                      Getting stuff                                           */
164 /************************************************/
165 /* get object's active particle system safely */
166 ParticleSystem *psys_get_current(Object *ob)
167 {
168         ParticleSystem *psys;
169         if(ob==0) return 0;
170
171         for(psys=ob->particlesystem.first; psys; psys=psys->next){
172                 if(psys->flag & PSYS_CURRENT)
173                         return psys;
174         }
175         
176         return 0;
177 }
178 short psys_get_current_num(Object *ob)
179 {
180         ParticleSystem *psys;
181         short i;
182
183         if(ob==0) return 0;
184
185         for(psys=ob->particlesystem.first, i=0; psys; psys=psys->next, i++)
186                 if(psys->flag & PSYS_CURRENT)
187                         return i;
188         
189         return i;
190 }
191 void psys_set_current_num(Object *ob, int index)
192 {
193         ParticleSystem *psys;
194         short i;
195
196         if(ob==0) return;
197
198         for(psys=ob->particlesystem.first, i=0; psys; psys=psys->next, i++) {
199                 if(i == index)
200                         psys->flag |= PSYS_CURRENT;
201                 else
202                         psys->flag &= ~PSYS_CURRENT;
203         }
204 }
205 Object *psys_find_object(Scene *scene, ParticleSystem *psys)
206 {
207         Base *base = scene->base.first;
208         ParticleSystem *tpsys;
209
210         for(base = scene->base.first; base; base = base->next) {
211                 for(tpsys = base->object->particlesystem.first; psys; psys=psys->next) {
212                         if(tpsys == psys)
213                                 return base->object;
214                 }
215         }
216
217         return NULL;
218 }
219 Object *psys_get_lattice(ParticleSimulationData *sim)
220 {
221         Object *lattice=0;
222         
223         if(psys_in_edit_mode(sim->scene, sim->psys)==0){
224
225                 ModifierData *md = (ModifierData*)psys_get_modifier(sim->ob, sim->psys);
226
227                 for(; md; md=md->next){
228                         if(md->type==eModifierType_Lattice){
229                                 LatticeModifierData *lmd = (LatticeModifierData *)md;
230                                 lattice=lmd->object;
231                                 break;
232                         }
233                 }
234                 if(lattice)
235                         init_latt_deform(lattice,0);
236         }
237
238         return lattice;
239 }
240 void psys_disable_all(Object *ob)
241 {
242         ParticleSystem *psys=ob->particlesystem.first;
243
244         for(; psys; psys=psys->next)
245                 psys->flag |= PSYS_DISABLED;
246 }
247 void psys_enable_all(Object *ob)
248 {
249         ParticleSystem *psys=ob->particlesystem.first;
250
251         for(; psys; psys=psys->next)
252                 psys->flag &= ~PSYS_DISABLED;
253 }
254 int psys_in_edit_mode(Scene *scene, ParticleSystem *psys)
255 {
256         return (scene->basact && (scene->basact->object->mode & OB_MODE_PARTICLE_EDIT) && psys==psys_get_current((scene->basact)->object) && (psys->edit || psys->pointcache->edit));
257 }
258 static void psys_create_frand(ParticleSystem *psys)
259 {
260         int i;
261         float *rand = psys->frand = MEM_callocN(PSYS_FRAND_COUNT * sizeof(float), "particle randoms");
262
263         BLI_srandom(psys->seed);
264
265         for(i=0; i<1024; i++, rand++)
266                 *rand = BLI_frand();
267 }
268 int psys_check_enabled(Object *ob, ParticleSystem *psys)
269 {
270         ParticleSystemModifierData *psmd;
271         Mesh *me;
272
273         if(psys->flag & PSYS_DISABLED || psys->flag & PSYS_DELETE || !psys->part)
274                 return 0;
275
276         if(ob->type == OB_MESH) {
277                 me= (Mesh*)ob->data;
278                 if(me->mr && me->mr->current != 1)
279                         return 0;
280         }
281
282         psmd= psys_get_modifier(ob, psys);
283         if(psys->renderdata) {
284                 if(!(psmd->modifier.mode & eModifierMode_Render))
285                         return 0;
286         }
287         else if(!(psmd->modifier.mode & eModifierMode_Realtime))
288                 return 0;
289
290         /* perhaps not the perfect place, but we have to be sure the rands are there before usage */
291         if(!psys->frand)
292                 psys_create_frand(psys);
293         else if(psys->recalc & PSYS_RECALC_RESET) {
294                 MEM_freeN(psys->frand);
295                 psys_create_frand(psys);
296         }
297         
298         return 1;
299 }
300
301 int psys_check_edited(ParticleSystem *psys)
302 {
303         if(psys->part && psys->part->type==PART_HAIR)
304                 return (psys->flag & PSYS_EDITED || (psys->edit && psys->edit->edited));
305         else
306                 return (psys->pointcache->edit && psys->pointcache->edit->edited);
307 }
308
309 void psys_check_group_weights(ParticleSettings *part)
310 {
311         ParticleDupliWeight *dw, *tdw;
312         GroupObject *go;
313         int current = 0;
314
315         if(part->ren_as == PART_DRAW_GR && part->dup_group && part->dup_group->gobject.first) {
316                 /* first remove all weights that don't have an object in the group */
317                 dw = part->dupliweights.first;
318                 while(dw) {
319                         if(!object_in_group(dw->ob, part->dup_group)) {
320                                 tdw = dw->next;
321                                 BLI_freelinkN(&part->dupliweights, dw);
322                                 dw = tdw;
323                         }
324                         else
325                                 dw = dw->next;
326                 }
327
328                 /* then add objects in the group to new list */
329                 go = part->dup_group->gobject.first;
330                 while(go) {
331                         dw = part->dupliweights.first;
332                         while(dw && dw->ob != go->ob)
333                                 dw = dw->next;
334                         
335                         if(!dw) {
336                                 dw = MEM_callocN(sizeof(ParticleDupliWeight), "ParticleDupliWeight");
337                                 dw->ob = go->ob;
338                                 dw->count = 1;
339                                 BLI_addtail(&part->dupliweights, dw);
340                         }
341
342                         go = go->next;  
343                 }
344
345                 dw = part->dupliweights.first;
346                 for(; dw; dw=dw->next) {
347                         if(dw->flag & PART_DUPLIW_CURRENT) {
348                                 current = 1;
349                                 break;
350                         }
351                 }
352
353                 if(!current) {
354                         dw = part->dupliweights.first;
355                         if(dw)
356                                 dw->flag |= PART_DUPLIW_CURRENT;
357                 }
358         }
359         else {
360                 BLI_freelistN(&part->dupliweights);
361         }
362 }
363 /************************************************/
364 /*                      Freeing stuff                                           */
365 /************************************************/
366 void psys_free_settings(ParticleSettings *part)
367 {
368         free_partdeflect(part->pd);
369         free_partdeflect(part->pd2);
370
371         if(part->effector_weights)
372                 MEM_freeN(part->effector_weights);
373
374         BLI_freelistN(&part->dupliweights);
375
376         boid_free_settings(part->boids);
377 }
378
379 void free_hair(Object *ob, ParticleSystem *psys, int dynamics)
380 {
381         PARTICLE_P;
382
383         if(psys->part->type != PART_HAIR)
384                 return;
385
386         LOOP_PARTICLES {
387                 if(pa->hair)
388                         MEM_freeN(pa->hair);
389                 pa->hair = NULL;
390                 pa->totkey = 0;
391         }
392
393         psys->flag &= ~PSYS_HAIR_DONE;
394
395         if(psys->clmd) {
396                 if(dynamics) {
397                         BKE_ptcache_free_list(&psys->ptcaches);
398                         psys->clmd->point_cache = psys->pointcache = NULL;
399                         psys->clmd->ptcaches.first = psys->clmd->ptcaches.first = NULL;
400
401                         modifier_free((ModifierData*)psys->clmd);
402                         
403                         psys->clmd = NULL;
404                 }
405                 else {
406                         cloth_free_modifier(ob, psys->clmd);
407                 }
408         }
409
410         if(psys->hair_in_dm)
411                 psys->hair_in_dm->release(psys->hair_in_dm);
412         psys->hair_in_dm = NULL;
413
414         if(psys->hair_out_dm)
415                 psys->hair_out_dm->release(psys->hair_out_dm);
416         psys->hair_out_dm = NULL;
417 }
418 void free_keyed_keys(ParticleSystem *psys)
419 {
420         PARTICLE_P;
421
422         if(psys->part->type == PART_HAIR)
423                 return;
424
425         if(psys->particles && psys->particles->keys) {
426                 MEM_freeN(psys->particles->keys);
427
428                 LOOP_PARTICLES {
429                         if(pa->keys) {
430                                 pa->keys= NULL;
431                                 pa->totkey= 0;
432                         }
433                 }
434         }
435 }
436 static void free_child_path_cache(ParticleSystem *psys)
437 {
438         psys_free_path_cache_buffers(psys->childcache, &psys->childcachebufs);
439         psys->childcache = NULL;
440         psys->totchildcache = 0;
441 }
442 void psys_free_path_cache(ParticleSystem *psys, PTCacheEdit *edit)
443 {
444         if(edit) {
445                 psys_free_path_cache_buffers(edit->pathcache, &edit->pathcachebufs);
446                 edit->pathcache= NULL;
447                 edit->totcached= 0;
448         }
449         if(psys) {
450                 psys_free_path_cache_buffers(psys->pathcache, &psys->pathcachebufs);
451                 psys->pathcache= NULL;
452                 psys->totcached= 0;
453
454                 free_child_path_cache(psys);
455         }
456 }
457 void psys_free_children(ParticleSystem *psys)
458 {
459         if(psys->child) {
460                 MEM_freeN(psys->child);
461                 psys->child=0;
462                 psys->totchild=0;
463         }
464
465         free_child_path_cache(psys);
466 }
467 void psys_free_particles(ParticleSystem *psys)
468 {
469         PARTICLE_P;
470
471         if(psys->particles) {
472                 if(psys->part->type==PART_HAIR) {
473                         LOOP_PARTICLES {
474                                 if(pa->hair)
475                                         MEM_freeN(pa->hair);
476                         }
477                 }
478                 
479                 if(psys->particles->keys)
480                         MEM_freeN(psys->particles->keys);
481                 
482                 if(psys->particles->boid)
483                         MEM_freeN(psys->particles->boid);
484
485                 MEM_freeN(psys->particles);
486                 psys->particles= NULL;
487                 psys->totpart= 0;
488         }
489 }
490 void psys_free_pdd(ParticleSystem *psys)
491 {
492         if(psys->pdd) {
493                 if(psys->pdd->cdata)
494                         MEM_freeN(psys->pdd->cdata);
495                 psys->pdd->cdata = NULL;
496
497                 if(psys->pdd->vdata)
498                         MEM_freeN(psys->pdd->vdata);
499                 psys->pdd->vdata = NULL;
500
501                 if(psys->pdd->ndata)
502                         MEM_freeN(psys->pdd->ndata);
503                 psys->pdd->ndata = NULL;
504
505                 if(psys->pdd->vedata)
506                         MEM_freeN(psys->pdd->vedata);
507                 psys->pdd->vedata = NULL;
508
509                 psys->pdd->totpoint = 0;
510                 psys->pdd->tot_vec_size = 0;
511         }
512 }
513 /* free everything */
514 void psys_free(Object *ob, ParticleSystem * psys)
515 {       
516         if(psys){
517                 int nr = 0;
518                 ParticleSystem * tpsys;
519                 
520                 psys_free_path_cache(psys, NULL);
521
522                 free_hair(ob, psys, 1);
523
524                 psys_free_particles(psys);
525
526                 if(psys->edit && psys->free_edit)
527                         psys->free_edit(psys->edit);
528
529                 if(psys->child){
530                         MEM_freeN(psys->child);
531                         psys->child = 0;
532                         psys->totchild = 0;
533                 }
534                 
535                 // check if we are last non-visible particle system
536                 for(tpsys=ob->particlesystem.first; tpsys; tpsys=tpsys->next){
537                         if(tpsys->part)
538                         {
539                                 if(ELEM(tpsys->part->ren_as,PART_DRAW_OB,PART_DRAW_GR))
540                                 {
541                                         nr++;
542                                         break;
543                                 }
544                         }
545                 }
546                 // clear do-not-draw-flag
547                 if(!nr)
548                         ob->transflag &= ~OB_DUPLIPARTS;
549
550                 if(psys->part){
551                         psys->part->id.us--;            
552                         psys->part=0;
553                 }
554
555                 BKE_ptcache_free_list(&psys->ptcaches);
556                 psys->pointcache = NULL;
557                 
558                 BLI_freelistN(&psys->targets);
559
560                 BLI_kdtree_free(psys->tree);
561
562                 pdEndEffectors(&psys->effectors);
563
564                 if(psys->frand)
565                         MEM_freeN(psys->frand);
566
567                 if(psys->pdd) {
568                         psys_free_pdd(psys);
569                         MEM_freeN(psys->pdd);
570                 }
571
572                 MEM_freeN(psys);
573         }
574 }
575
576 /************************************************/
577 /*                      Rendering                                                       */
578 /************************************************/
579 /* these functions move away particle data and bring it back after
580  * rendering, to make different render settings possible without
581  * removing the previous data. this should be solved properly once */
582
583 typedef struct ParticleRenderElem {
584         int curchild, totchild, reduce;
585         float lambda, t, scalemin, scalemax;
586 } ParticleRenderElem;
587
588 typedef struct ParticleRenderData {
589         ChildParticle *child;
590         ParticleCacheKey **pathcache;
591         ParticleCacheKey **childcache;
592         ListBase pathcachebufs, childcachebufs;
593         int totchild, totcached, totchildcache;
594         DerivedMesh *dm;
595         int totdmvert, totdmedge, totdmface;
596
597         float mat[4][4];
598         float viewmat[4][4], winmat[4][4];
599         int winx, winy;
600
601         int dosimplify;
602         int timeoffset;
603         ParticleRenderElem *elems;
604         int *origindex;
605 } ParticleRenderData;
606
607 static float psys_render_viewport_falloff(double rate, float dist, float width)
608 {
609         return pow(rate, dist/width);
610 }
611
612 static float psys_render_projected_area(ParticleSystem *psys, float *center, float area, double vprate, float *viewport)
613 {
614         ParticleRenderData *data= psys->renderdata;
615         float co[4], view[3], ortho1[3], ortho2[3], w, dx, dy, radius;
616         
617         /* transform to view space */
618         VECCOPY(co, center);
619         co[3]= 1.0f;
620         Mat4MulVec4fl(data->viewmat, co);
621         
622         /* compute two vectors orthogonal to view vector */
623         VECCOPY(view, co);
624         Normalize(view);
625         VecOrthoBasisf(view, ortho1, ortho2);
626
627         /* compute on screen minification */
628         w= co[2]*data->winmat[2][3] + data->winmat[3][3];
629         dx= data->winx*ortho2[0]*data->winmat[0][0];
630         dy= data->winy*ortho2[1]*data->winmat[1][1];
631         w= sqrt(dx*dx + dy*dy)/w;
632
633         /* w squared because we are working with area */
634         area= area*w*w;
635
636         /* viewport of the screen test */
637
638         /* project point on screen */
639         Mat4MulVec4fl(data->winmat, co);
640         if(co[3] != 0.0f) {
641                 co[0]= 0.5f*data->winx*(1.0f + co[0]/co[3]);
642                 co[1]= 0.5f*data->winy*(1.0f + co[1]/co[3]);
643         }
644
645         /* screen space radius */
646         radius= sqrt(area/M_PI);
647
648         /* make smaller using fallof once over screen edge */
649         *viewport= 1.0f;
650
651         if(co[0]+radius < 0.0f)
652                 *viewport *= psys_render_viewport_falloff(vprate, -(co[0]+radius), data->winx);
653         else if(co[0]-radius > data->winx)
654                 *viewport *= psys_render_viewport_falloff(vprate, (co[0]-radius) - data->winx, data->winx);
655
656         if(co[1]+radius < 0.0f)
657                 *viewport *= psys_render_viewport_falloff(vprate, -(co[1]+radius), data->winy);
658         else if(co[1]-radius > data->winy)
659                 *viewport *= psys_render_viewport_falloff(vprate, (co[1]-radius) - data->winy, data->winy);
660         
661         return area;
662 }
663
664 void psys_render_set(Object *ob, ParticleSystem *psys, float viewmat[][4], float winmat[][4], int winx, int winy, int timeoffset)
665 {
666         ParticleRenderData*data;
667         ParticleSystemModifierData *psmd= psys_get_modifier(ob, psys);
668
669         if(!G.rendering)
670                 return;
671         if(psys->renderdata)
672                 return;
673
674         data= MEM_callocN(sizeof(ParticleRenderData), "ParticleRenderData");
675
676         data->child= psys->child;
677         data->totchild= psys->totchild;
678         data->pathcache= psys->pathcache;
679         data->pathcachebufs.first = psys->pathcachebufs.first;
680         data->pathcachebufs.last = psys->pathcachebufs.last;
681         data->totcached= psys->totcached;
682         data->childcache= psys->childcache;
683         data->childcachebufs.first = psys->childcachebufs.first;
684         data->childcachebufs.last = psys->childcachebufs.last;
685         data->totchildcache= psys->totchildcache;
686
687         if(psmd->dm)
688                 data->dm= CDDM_copy(psmd->dm);
689         data->totdmvert= psmd->totdmvert;
690         data->totdmedge= psmd->totdmedge;
691         data->totdmface= psmd->totdmface;
692
693         psys->child= NULL;
694         psys->pathcache= NULL;
695         psys->childcache= NULL;
696         psys->totchild= psys->totcached= psys->totchildcache= 0;
697         psys->pathcachebufs.first = psys->pathcachebufs.last = NULL;
698         psys->childcachebufs.first = psys->childcachebufs.last = NULL;
699
700         Mat4CpyMat4(data->winmat, winmat);
701         Mat4MulMat4(data->viewmat, ob->obmat, viewmat);
702         Mat4MulMat4(data->mat, data->viewmat, winmat);
703         data->winx= winx;
704         data->winy= winy;
705
706         data->timeoffset= timeoffset;
707
708         psys->renderdata= data;
709 }
710
711 void psys_render_restore(Object *ob, ParticleSystem *psys)
712 {
713         ParticleRenderData*data;
714         ParticleSystemModifierData *psmd= psys_get_modifier(ob, psys);
715
716         data= psys->renderdata;
717         if(!data)
718                 return;
719         
720         if(data->elems)
721                 MEM_freeN(data->elems);
722
723         if(psmd->dm) {
724                 psmd->dm->needsFree= 1;
725                 psmd->dm->release(psmd->dm);
726         }
727
728         psys_free_path_cache(psys, NULL);
729
730         if(psys->child){
731                 MEM_freeN(psys->child);
732                 psys->child= 0;
733                 psys->totchild= 0;
734         }
735
736         psys->child= data->child;
737         psys->totchild= data->totchild;
738         psys->pathcache= data->pathcache;
739         psys->pathcachebufs.first = data->pathcachebufs.first;
740         psys->pathcachebufs.last = data->pathcachebufs.last;
741         psys->totcached= data->totcached;
742         psys->childcache= data->childcache;
743         psys->childcachebufs.first = data->childcachebufs.first;
744         psys->childcachebufs.last = data->childcachebufs.last;
745         psys->totchildcache= data->totchildcache;
746
747         psmd->dm= data->dm;
748         psmd->totdmvert= data->totdmvert;
749         psmd->totdmedge= data->totdmedge;
750         psmd->totdmface= data->totdmface;
751         psmd->flag &= ~eParticleSystemFlag_psys_updated;
752
753         if(psmd->dm)
754                 psys_calc_dmcache(ob, psmd->dm, psys);
755
756         MEM_freeN(data);
757         psys->renderdata= NULL;
758 }
759
760 int psys_render_simplify_distribution(ParticleThreadContext *ctx, int tot)
761 {
762         DerivedMesh *dm= ctx->dm;
763         Mesh *me= (Mesh*)(ctx->sim.ob->data);
764         MFace *mf, *mface;
765         MVert *mvert;
766         ParticleRenderData *data;
767         ParticleRenderElem *elems, *elem;
768         ParticleSettings *part= ctx->sim.psys->part;
769         float *facearea, (*facecenter)[3], size[3], fac, powrate, scaleclamp;
770         float co1[3], co2[3], co3[3], co4[3], lambda, arearatio, t, area, viewport;
771         double vprate;
772         int *origindex, *facetotvert;
773         int a, b, totorigface, totface, newtot, skipped;
774
775         if(part->ren_as!=PART_DRAW_PATH || !(part->draw & PART_DRAW_REN_STRAND))
776                 return tot;
777         if(!ctx->sim.psys->renderdata)
778                 return tot;
779
780         data= ctx->sim.psys->renderdata;
781         if(data->timeoffset)
782                 return 0;
783         if(!(part->simplify_flag & PART_SIMPLIFY_ENABLE))
784                 return tot;
785
786         mvert= dm->getVertArray(dm);
787         mface= dm->getFaceArray(dm);
788         origindex= dm->getFaceDataArray(dm, CD_ORIGINDEX);
789         totface= dm->getNumFaces(dm);
790         totorigface= me->totface;
791
792         if(totface == 0 || totorigface == 0 || origindex == NULL)
793                 return tot;
794
795         facearea= MEM_callocN(sizeof(float)*totorigface, "SimplifyFaceArea");
796         facecenter= MEM_callocN(sizeof(float[3])*totorigface, "SimplifyFaceCenter");
797         facetotvert= MEM_callocN(sizeof(int)*totorigface, "SimplifyFaceArea");
798         elems= MEM_callocN(sizeof(ParticleRenderElem)*totorigface, "SimplifyFaceElem");
799
800         if(data->elems)
801                 MEM_freeN(data->elems);
802
803         data->dosimplify= 1;
804         data->elems= elems;
805         data->origindex= origindex;
806
807         /* compute number of children per original face */
808         for(a=0; a<tot; a++) {
809                 b= origindex[ctx->index[a]];
810                 if(b != -1)
811                         elems[b].totchild++;
812         }
813
814         /* compute areas and centers of original faces */
815         for(mf=mface, a=0; a<totface; a++, mf++) {
816                 b= origindex[a];
817
818                 if(b != -1) {
819                         VECCOPY(co1, mvert[mf->v1].co);
820                         VECCOPY(co2, mvert[mf->v2].co);
821                         VECCOPY(co3, mvert[mf->v3].co);
822
823                         VECADD(facecenter[b], facecenter[b], co1);
824                         VECADD(facecenter[b], facecenter[b], co2);
825                         VECADD(facecenter[b], facecenter[b], co3);
826
827                         if(mf->v4) {
828                                 VECCOPY(co4, mvert[mf->v4].co);
829                                 VECADD(facecenter[b], facecenter[b], co4);
830                                 facearea[b] += AreaQ3Dfl(co1, co2, co3, co4);
831                                 facetotvert[b] += 4;
832                         }
833                         else {
834                                 facearea[b] += AreaT3Dfl(co1, co2, co3);
835                                 facetotvert[b] += 3;
836                         }
837                 }
838         }
839
840         for(a=0; a<totorigface; a++)
841                 if(facetotvert[a] > 0)
842                         VecMulf(facecenter[a], 1.0f/facetotvert[a]);
843
844         /* for conversion from BU area / pixel area to reference screen size */
845         mesh_get_texspace(me, 0, 0, size);
846         fac= ((size[0] + size[1] + size[2])/3.0f)/part->simplify_refsize;
847         fac= fac*fac;
848
849         powrate= log(0.5f)/log(part->simplify_rate*0.5f);
850         if(part->simplify_flag & PART_SIMPLIFY_VIEWPORT)
851                 vprate= pow(1.0 - part->simplify_viewport, 5.0);
852         else
853                 vprate= 1.0;
854
855         /* set simplification parameters per original face */
856         for(a=0, elem=elems; a<totorigface; a++, elem++) {
857                 area = psys_render_projected_area(ctx->sim.psys, facecenter[a], facearea[a], vprate, &viewport);
858                 arearatio= fac*area/facearea[a];
859
860                 if((arearatio < 1.0f || viewport < 1.0f) && elem->totchild) {
861                         /* lambda is percentage of elements to keep */
862                         lambda= (arearatio < 1.0f)? pow(arearatio, powrate): 1.0f;
863                         lambda *= viewport;
864
865                         lambda= MAX2(lambda, 1.0f/elem->totchild);
866
867                         /* compute transition region */
868                         t= part->simplify_transition;
869                         elem->t= (lambda-t < 0.0f)? lambda: (lambda+t > 1.0f)? 1.0f-lambda: t;
870                         elem->reduce= 1;
871
872                         /* scale at end and beginning of the transition region */
873                         elem->scalemax= (lambda+t < 1.0f)? 1.0f/lambda: 1.0f/(1.0f - elem->t*elem->t/t);
874                         elem->scalemin= (lambda+t < 1.0f)? 0.0f: elem->scalemax*(1.0f-elem->t/t);
875
876                         elem->scalemin= sqrt(elem->scalemin);
877                         elem->scalemax= sqrt(elem->scalemax);
878
879                         /* clamp scaling */
880                         scaleclamp= MIN2(elem->totchild, 10.0f);
881                         elem->scalemin= MIN2(scaleclamp, elem->scalemin);
882                         elem->scalemax= MIN2(scaleclamp, elem->scalemax);
883
884                         /* extend lambda to include transition */
885                         lambda= lambda + elem->t;
886                         if(lambda > 1.0f)
887                                 lambda= 1.0f;
888                 }
889                 else {
890                         lambda= arearatio;
891
892                         elem->scalemax= 1.0f; //sqrt(lambda);
893                         elem->scalemin= 1.0f; //sqrt(lambda);
894                         elem->reduce= 0;
895                 }
896
897                 elem->lambda= lambda;
898                 elem->scalemin= sqrt(elem->scalemin);
899                 elem->scalemax= sqrt(elem->scalemax);
900                 elem->curchild= 0;
901         }
902
903         MEM_freeN(facearea);
904         MEM_freeN(facecenter);
905         MEM_freeN(facetotvert);
906
907         /* move indices and set random number skipping */
908         ctx->skip= MEM_callocN(sizeof(int)*tot, "SimplificationSkip");
909
910         skipped= 0;
911         for(a=0, newtot=0; a<tot; a++) {
912                 b= origindex[ctx->index[a]];
913                 if(b != -1) {
914                         if(elems[b].curchild++ < ceil(elems[b].lambda*elems[b].totchild)) {
915                                 ctx->index[newtot]= ctx->index[a];
916                                 ctx->skip[newtot]= skipped;
917                                 skipped= 0;
918                                 newtot++;
919                         }
920                         else skipped++;
921                 }
922                 else skipped++;
923         }
924
925         for(a=0, elem=elems; a<totorigface; a++, elem++)
926                 elem->curchild= 0;
927
928         return newtot;
929 }
930
931 int psys_render_simplify_params(ParticleSystem *psys, ChildParticle *cpa, float *params)
932 {
933         ParticleRenderData *data;
934         ParticleRenderElem *elem;
935         float x, w, scale, alpha, lambda, t, scalemin, scalemax;
936         int b;
937
938         if(!(psys->renderdata && (psys->part->simplify_flag & PART_SIMPLIFY_ENABLE)))
939                 return 0;
940         
941         data= psys->renderdata;
942         if(!data->dosimplify)
943                 return 0;
944         
945         b= data->origindex[cpa->num];
946         if(b == -1)
947                 return 0;
948
949         elem= &data->elems[b];
950
951         lambda= elem->lambda;
952         t= elem->t;
953         scalemin= elem->scalemin;
954         scalemax= elem->scalemax;
955
956         if(!elem->reduce) {
957                 scale= scalemin;
958                 alpha= 1.0f;
959         }
960         else {
961                 x= (elem->curchild+0.5f)/elem->totchild;
962                 if(x < lambda-t) {
963                         scale= scalemax;
964                         alpha= 1.0f;
965                 }
966                 else if(x >= lambda+t) {
967                         scale= scalemin;
968                         alpha= 0.0f;
969                 }
970                 else {
971                         w= (lambda+t - x)/(2.0f*t);
972                         scale= scalemin + (scalemax - scalemin)*w;
973                         alpha= w;
974                 }
975         }
976
977         params[0]= scale;
978         params[1]= alpha;
979
980         elem->curchild++;
981
982         return 1;
983 }
984
985 /************************************************/
986 /*                      Interpolation                                           */
987 /************************************************/
988 static float interpolate_particle_value(float v1, float v2, float v3, float v4, float *w, int four)
989 {
990         float value;
991
992         value= w[0]*v1 + w[1]*v2 + w[2]*v3;
993         if(four)
994                 value += w[3]*v4;
995         
996         return value;
997 }
998 static void weighted_particle_vector(float *v1, float *v2, float *v3, float *v4, float *weights, float *vec)
999 {
1000         vec[0]= weights[0]*v1[0] + weights[1]*v2[0] + weights[2]*v3[0] + weights[3]*v4[0];
1001         vec[1]= weights[0]*v1[1] + weights[1]*v2[1] + weights[2]*v3[1] + weights[3]*v4[1];
1002         vec[2]= weights[0]*v1[2] + weights[1]*v2[2] + weights[2]*v3[2] + weights[3]*v4[2];
1003 }
1004 void psys_interpolate_particle(short type, ParticleKey keys[4], float dt, ParticleKey *result, int velocity)
1005 {
1006         float t[4];
1007
1008         if(type<0) {
1009                 VecfCubicInterpol(keys[1].co, keys[1].vel, keys[2].co, keys[2].vel, dt, result->co, result->vel);
1010         }
1011         else {
1012                 key_curve_position_weights(dt, t, type);
1013
1014                 weighted_particle_vector(keys[0].co, keys[1].co, keys[2].co, keys[3].co, t, result->co);
1015
1016                 if(velocity){
1017                         float temp[3];
1018
1019                         if(dt>0.999f){
1020                                 key_curve_position_weights(dt-0.001f, t, type);
1021                                 weighted_particle_vector(keys[0].co, keys[1].co, keys[2].co, keys[3].co, t, temp);
1022                                 VECSUB(result->vel, result->co, temp);
1023                         }
1024                         else{
1025                                 key_curve_position_weights(dt+0.001f, t, type);
1026                                 weighted_particle_vector(keys[0].co, keys[1].co, keys[2].co, keys[3].co, t, temp);
1027                                 VECSUB(result->vel, temp, result->co);
1028                         }
1029                 }
1030         }
1031 }
1032
1033
1034
1035 typedef struct ParticleInterpolationData {
1036         HairKey *hkey[2];
1037
1038         DerivedMesh *dm;
1039         MVert *mvert[2];
1040
1041         int keyed;
1042         ParticleKey *kkey[2];
1043
1044         PointCache *cache;
1045
1046         PTCacheEditPoint *epoint;
1047         PTCacheEditKey *ekey[2];
1048
1049         float birthtime, dietime;
1050         int bspline;
1051 } ParticleInterpolationData;
1052 /* Assumes pointcache->mem_cache exists, so for disk cached particles call psys_make_temp_pointcache() before use */
1053 static void get_pointcache_keys_for_time(Object *ob, PointCache *cache, int index, float t, ParticleKey *key1, ParticleKey *key2)
1054 {
1055         static PTCacheMem *pm = NULL; /* not thread safe */
1056
1057         if(index < 0) { /* initialize */
1058                 pm = cache->mem_cache.first;
1059
1060                 if(pm)
1061                         pm = pm->next;
1062         }
1063         else {
1064                 if(pm) {
1065                         while(pm && pm->next && (float)pm->frame < t)
1066                                 pm = pm->next;
1067
1068                         BKE_ptcache_make_particle_key(key2, pm->index_array ? pm->index_array[index] : index, pm->data, (float)pm->frame);
1069                         BKE_ptcache_make_particle_key(key1, pm->prev->index_array ? pm->prev->index_array[index] : index, pm->prev->data, (float)pm->prev->frame);
1070                 }
1071                 else if(cache->mem_cache.first) {
1072                         PTCacheMem *pm2 = cache->mem_cache.first;
1073                         BKE_ptcache_make_particle_key(key2, pm2->index_array ? pm2->index_array[index] : index, pm2->data, (float)pm2->frame);
1074                         copy_particle_key(key1, key2, 1);
1075                 }
1076         }
1077 }
1078 static void init_particle_interpolation(Object *ob, ParticleSystem *psys, ParticleData *pa, ParticleInterpolationData *pind)
1079 {
1080
1081         if(pind->epoint) {
1082                 PTCacheEditPoint *point = pind->epoint;
1083
1084                 pind->ekey[0] = point->keys;
1085                 pind->ekey[1] = point->totkey > 1 ? point->keys + 1 : NULL;
1086
1087                 pind->birthtime = *(point->keys->time);
1088                 pind->dietime = *((point->keys + point->totkey - 1)->time);
1089         }
1090         else if(pind->keyed) {
1091                 ParticleKey *key = pa->keys;
1092                 pind->kkey[0] = key;
1093                 pind->kkey[1] = pa->totkey > 1 ? key + 1 : NULL;
1094
1095                 pind->birthtime = key->time;
1096                 pind->dietime = (key + pa->totkey - 1)->time;
1097         }
1098         else if(pind->cache) {
1099                 get_pointcache_keys_for_time(ob, pind->cache, -1, 0.0f, NULL, NULL);
1100
1101                 pind->birthtime = pa ? pa->time : pind->cache->startframe;
1102                 pind->dietime = pa ? pa->dietime : pind->cache->endframe;
1103         }
1104         else {
1105                 HairKey *key = pa->hair;
1106                 pind->hkey[0] = key;
1107                 pind->hkey[1] = key + 1;
1108
1109                 pind->birthtime = key->time;
1110                 pind->dietime = (key + pa->totkey - 1)->time;
1111
1112                 if(pind->dm) {
1113                         pind->mvert[0] = CDDM_get_vert(pind->dm, pa->hair_index);
1114                         pind->mvert[1] = pind->mvert[0] + 1;
1115                 }
1116         }
1117 }
1118 static void edit_to_particle(ParticleKey *key, PTCacheEditKey *ekey)
1119 {
1120         VECCOPY(key->co, ekey->co);
1121         if(ekey->vel) {
1122                 VECCOPY(key->vel, ekey->vel);
1123         }
1124         key->time = *(ekey->time);
1125 }
1126 static void hair_to_particle(ParticleKey *key, HairKey *hkey)
1127 {
1128         VECCOPY(key->co, hkey->co);
1129         key->time = hkey->time;
1130 }
1131
1132 static void mvert_to_particle(ParticleKey *key, MVert *mvert, HairKey *hkey)
1133 {
1134         VECCOPY(key->co, mvert->co);
1135         key->time = hkey->time;
1136 }
1137
1138 static void do_particle_interpolation(ParticleSystem *psys, int p, ParticleData *pa, float t, float frs_sec, ParticleInterpolationData *pind, ParticleKey *result)
1139 {
1140         PTCacheEditPoint *point = pind->epoint;
1141         ParticleKey keys[4];
1142         int point_vel = (point && point->keys->vel);
1143         float real_t, dfra, keytime;
1144
1145         /* interpret timing and find keys */
1146         if(point) {
1147                 if(result->time < 0.0f)
1148                         real_t = -result->time;
1149                 else
1150                         real_t = *(pind->ekey[0]->time) + t * (*(pind->ekey[0][point->totkey-1].time) - *(pind->ekey[0]->time));
1151
1152                 while(*(pind->ekey[1]->time) < real_t)
1153                         pind->ekey[1]++;
1154
1155                 pind->ekey[0] = pind->ekey[1] - 1;
1156         }
1157         else if(pind->keyed) {
1158                 /* we have only one key, so let's use that */
1159                 if(pind->kkey[1]==NULL) {
1160                         copy_particle_key(result, pind->kkey[0], 1);
1161                         return;
1162                 }
1163
1164                 if(result->time < 0.0f)
1165                         real_t = -result->time;
1166                 else
1167                         real_t = pind->kkey[0]->time + t * (pind->kkey[0][pa->totkey-1].time - pind->kkey[0]->time);
1168
1169                 if(psys->part->phystype==PART_PHYS_KEYED && psys->flag & PSYS_KEYED_TIMING) {
1170                         ParticleTarget *pt = psys->targets.first;
1171
1172                         pt=pt->next;
1173
1174                         while(pt && pa->time + pt->time < real_t)
1175                                 pt= pt->next;
1176
1177                         if(pt) {
1178                                 pt=pt->prev;
1179
1180                                 if(pa->time + pt->time + pt->duration > real_t)
1181                                         real_t = pa->time + pt->time;
1182                         }
1183                         else
1184                                 real_t = pa->time + ((ParticleTarget*)psys->targets.last)->time;
1185                 }
1186
1187                 CLAMP(real_t, pa->time, pa->dietime);
1188
1189                 while(pind->kkey[1]->time < real_t)
1190                         pind->kkey[1]++;
1191                 
1192                 pind->kkey[0] = pind->kkey[1] - 1;
1193         }
1194         else if(pind->cache) {
1195                 if(result->time < 0.0f) /* flag for time in frames */
1196                         real_t = -result->time;
1197                 else
1198                         real_t = pa->time + t * (pa->dietime - pa->time);
1199         }
1200         else {
1201                 if(result->time < 0.0f)
1202                         real_t = -result->time;
1203                 else
1204                         real_t = pind->hkey[0]->time + t * (pind->hkey[0][pa->totkey-1].time - pind->hkey[0]->time);
1205
1206                 while(pind->hkey[1]->time < real_t) {
1207                         pind->hkey[1]++;
1208                         pind->mvert[1]++;
1209                 }
1210
1211                 pind->hkey[0] = pind->hkey[1] - 1;
1212         }
1213
1214         /* set actual interpolation keys */
1215         if(point) {
1216                 edit_to_particle(keys + 1, pind->ekey[0]);
1217                 edit_to_particle(keys + 2, pind->ekey[1]);
1218         }
1219         else if(pind->dm) {
1220                 pind->mvert[0] = pind->mvert[1] - 1;
1221                 mvert_to_particle(keys + 1, pind->mvert[0], pind->hkey[0]);
1222                 mvert_to_particle(keys + 2, pind->mvert[1], pind->hkey[1]);
1223         }
1224         else if(pind->keyed) {
1225                 memcpy(keys + 1, pind->kkey[0], sizeof(ParticleKey));
1226                 memcpy(keys + 2, pind->kkey[1], sizeof(ParticleKey));
1227         }
1228         else if(pind->cache) {
1229                 get_pointcache_keys_for_time(NULL, pind->cache, p, real_t, keys+1, keys+2);
1230         }
1231         else {
1232                 hair_to_particle(keys + 1, pind->hkey[0]);
1233                 hair_to_particle(keys + 2, pind->hkey[1]);
1234         }
1235
1236         /* set secondary interpolation keys for hair */
1237         if(!pind->keyed && !pind->cache && !point_vel) {
1238                 if(point) {
1239                         if(pind->ekey[0] != point->keys)
1240                                 edit_to_particle(keys, pind->ekey[0] - 1);
1241                         else
1242                                 edit_to_particle(keys, pind->ekey[0]);
1243                 }
1244                 else if(pind->dm) {
1245                         if(pind->hkey[0] != pa->hair)
1246                                 mvert_to_particle(keys, pind->mvert[0] - 1, pind->hkey[0] - 1);
1247                         else
1248                                 mvert_to_particle(keys, pind->mvert[0], pind->hkey[0]);
1249                 }
1250                 else {
1251                         if(pind->hkey[0] != pa->hair)
1252                                 hair_to_particle(keys, pind->hkey[0] - 1);
1253                         else
1254                                 hair_to_particle(keys, pind->hkey[0]);
1255                 }
1256
1257                 if(point) {
1258                         if(pind->ekey[1] != point->keys + point->totkey - 1)
1259                                 edit_to_particle(keys + 3, pind->ekey[1] + 1);
1260                         else
1261                                 edit_to_particle(keys + 3, pind->ekey[1]);
1262                 }
1263                 else if(pind->dm) {
1264                         if(pind->hkey[1] != pa->hair + pa->totkey - 1)
1265                                 mvert_to_particle(keys + 3, pind->mvert[1] + 1, pind->hkey[1] + 1);
1266                         else
1267                                 mvert_to_particle(keys + 3, pind->mvert[1], pind->hkey[1]);
1268                 }
1269                 else {
1270                         if(pind->hkey[1] != pa->hair + pa->totkey - 1)
1271                                 hair_to_particle(keys + 3, pind->hkey[1] + 1);
1272                         else
1273                                 hair_to_particle(keys + 3, pind->hkey[1]);
1274                 }
1275         }
1276
1277         dfra = keys[2].time - keys[1].time;
1278         keytime = (real_t - keys[1].time) / dfra;
1279
1280         /* convert velocity to timestep size */
1281         if(pind->keyed || pind->cache || point_vel){
1282                 VecMulf(keys[1].vel, dfra / frs_sec);
1283                 VecMulf(keys[2].vel, dfra / frs_sec);
1284                 QuatInterpol(result->rot,keys[1].rot,keys[2].rot,keytime);
1285         }
1286
1287         /* now we should have in chronologiacl order k1<=k2<=t<=k3<=k4 with keytime between [0,1]->[k2,k3] (k1 & k4 used for cardinal & bspline interpolation)*/
1288         psys_interpolate_particle((pind->keyed || pind->cache || point_vel) ? -1 /* signal for cubic interpolation */
1289                 : (pind->bspline ? KEY_BSPLINE : KEY_CARDINAL)
1290                 ,keys, keytime, result, 1);
1291
1292         /* the velocity needs to be converted back from cubic interpolation */
1293         if(pind->keyed || pind->cache || point_vel)
1294                 VecMulf(result->vel, frs_sec / dfra);
1295 }
1296 /************************************************/
1297 /*                      Particles on a dm                                       */
1298 /************************************************/
1299 /* interpolate a location on a face based on face coordinates */
1300 void psys_interpolate_face(MVert *mvert, MFace *mface, MTFace *tface, float (*orcodata)[3], float *w, float *vec, float *nor, float *utan, float *vtan, float *orco,float *ornor){
1301         float *v1=0, *v2=0, *v3=0, *v4=0;
1302         float e1[3],e2[3],s1,s2,t1,t2;
1303         float *uv1, *uv2, *uv3, *uv4;
1304         float n1[3], n2[3], n3[3], n4[3];
1305         float tuv[4][2];
1306         float *o1, *o2, *o3, *o4;
1307
1308         v1= (mvert+mface->v1)->co;
1309         v2= (mvert+mface->v2)->co;
1310         v3= (mvert+mface->v3)->co;
1311         VECCOPY(n1,(mvert+mface->v1)->no);
1312         VECCOPY(n2,(mvert+mface->v2)->no);
1313         VECCOPY(n3,(mvert+mface->v3)->no);
1314         Normalize(n1);
1315         Normalize(n2);
1316         Normalize(n3);
1317
1318         if(mface->v4) {
1319                 v4= (mvert+mface->v4)->co;
1320                 VECCOPY(n4,(mvert+mface->v4)->no);
1321                 Normalize(n4);
1322                 
1323                 vec[0]= w[0]*v1[0] + w[1]*v2[0] + w[2]*v3[0] + w[3]*v4[0];
1324                 vec[1]= w[0]*v1[1] + w[1]*v2[1] + w[2]*v3[1] + w[3]*v4[1];
1325                 vec[2]= w[0]*v1[2] + w[1]*v2[2] + w[2]*v3[2] + w[3]*v4[2];
1326
1327                 if(nor){
1328                         if(mface->flag & ME_SMOOTH){
1329                                 nor[0]= w[0]*n1[0] + w[1]*n2[0] + w[2]*n3[0] + w[3]*n4[0];
1330                                 nor[1]= w[0]*n1[1] + w[1]*n2[1] + w[2]*n3[1] + w[3]*n4[1];
1331                                 nor[2]= w[0]*n1[2] + w[1]*n2[2] + w[2]*n3[2] + w[3]*n4[2];
1332                         }
1333                         else
1334                                 CalcNormFloat4(v1,v2,v3,v4,nor);
1335                 }
1336         }
1337         else {
1338                 vec[0]= w[0]*v1[0] + w[1]*v2[0] + w[2]*v3[0];
1339                 vec[1]= w[0]*v1[1] + w[1]*v2[1] + w[2]*v3[1];
1340                 vec[2]= w[0]*v1[2] + w[1]*v2[2] + w[2]*v3[2];
1341                 
1342                 if(nor){
1343                         if(mface->flag & ME_SMOOTH){
1344                                 nor[0]= w[0]*n1[0] + w[1]*n2[0] + w[2]*n3[0];
1345                                 nor[1]= w[0]*n1[1] + w[1]*n2[1] + w[2]*n3[1];
1346                                 nor[2]= w[0]*n1[2] + w[1]*n2[2] + w[2]*n3[2];
1347                         }
1348                         else
1349                                 CalcNormFloat(v1,v2,v3,nor);
1350                 }
1351         }
1352         
1353         /* calculate tangent vectors */
1354         if(utan && vtan){
1355                 if(tface){
1356                         uv1= tface->uv[0];
1357                         uv2= tface->uv[1];
1358                         uv3= tface->uv[2];
1359                         uv4= tface->uv[3];
1360                 }
1361                 else{
1362                         uv1= tuv[0]; uv2= tuv[1]; uv3= tuv[2]; uv4= tuv[3];
1363                         spheremap(v1[0], v1[1], v1[2], uv1, uv1+1);
1364                         spheremap(v2[0], v2[1], v2[2], uv2, uv2+1);
1365                         spheremap(v3[0], v3[1], v3[2], uv3, uv3+1);
1366                         if(v4)
1367                                 spheremap(v4[0], v4[1], v4[2], uv4, uv4+1);
1368                 }
1369
1370                 if(v4){
1371                         s1= uv3[0] - uv1[0];
1372                         s2= uv4[0] - uv1[0];
1373
1374                         t1= uv3[1] - uv1[1];
1375                         t2= uv4[1] - uv1[1];
1376
1377                         VecSubf(e1, v3, v1);
1378                         VecSubf(e2, v4, v1);
1379                 }
1380                 else{
1381                         s1= uv2[0] - uv1[0];
1382                         s2= uv3[0] - uv1[0];
1383
1384                         t1= uv2[1] - uv1[1];
1385                         t2= uv3[1] - uv1[1];
1386
1387                         VecSubf(e1, v2, v1);
1388                         VecSubf(e2, v3, v1);
1389                 }
1390
1391                 vtan[0] = (s1*e2[0] - s2*e1[0]);
1392                 vtan[1] = (s1*e2[1] - s2*e1[1]);
1393                 vtan[2] = (s1*e2[2] - s2*e1[2]);
1394
1395                 utan[0] = (t1*e2[0] - t2*e1[0]);
1396                 utan[1] = (t1*e2[1] - t2*e1[1]);
1397                 utan[2] = (t1*e2[2] - t2*e1[2]);
1398         }
1399
1400         if(orco) {
1401                 if(orcodata) {
1402                         o1= orcodata[mface->v1];
1403                         o2= orcodata[mface->v2];
1404                         o3= orcodata[mface->v3];
1405
1406                         if(mface->v4) {
1407                                 o4= orcodata[mface->v4];
1408                                 orco[0]= w[0]*o1[0] + w[1]*o2[0] + w[2]*o3[0] + w[3]*o4[0];
1409                                 orco[1]= w[0]*o1[1] + w[1]*o2[1] + w[2]*o3[1] + w[3]*o4[1];
1410                                 orco[2]= w[0]*o1[2] + w[1]*o2[2] + w[2]*o3[2] + w[3]*o4[2];
1411
1412                                 if(ornor)
1413                                         CalcNormFloat4(o1, o2, o3, o4, ornor);
1414                         }
1415                         else {
1416                                 orco[0]= w[0]*o1[0] + w[1]*o2[0] + w[2]*o3[0];
1417                                 orco[1]= w[0]*o1[1] + w[1]*o2[1] + w[2]*o3[1];
1418                                 orco[2]= w[0]*o1[2] + w[1]*o2[2] + w[2]*o3[2];
1419
1420                                 if(ornor)
1421                                         CalcNormFloat(o1, o2, o3, ornor);
1422                         }
1423                 }
1424                 else {
1425                         VECCOPY(orco, vec);
1426                         if(ornor)
1427                                 VECCOPY(ornor, nor);
1428                 }
1429         }
1430 }
1431 void psys_interpolate_uvs(MTFace *tface, int quad, float *w, float *uvco)
1432 {
1433         float v10= tface->uv[0][0];
1434         float v11= tface->uv[0][1];
1435         float v20= tface->uv[1][0];
1436         float v21= tface->uv[1][1];
1437         float v30= tface->uv[2][0];
1438         float v31= tface->uv[2][1];
1439         float v40,v41;
1440
1441         if(quad) {
1442                 v40= tface->uv[3][0];
1443                 v41= tface->uv[3][1];
1444
1445                 uvco[0]= w[0]*v10 + w[1]*v20 + w[2]*v30 + w[3]*v40;
1446                 uvco[1]= w[0]*v11 + w[1]*v21 + w[2]*v31 + w[3]*v41;
1447         }
1448         else {
1449                 uvco[0]= w[0]*v10 + w[1]*v20 + w[2]*v30;
1450                 uvco[1]= w[0]*v11 + w[1]*v21 + w[2]*v31;
1451         }
1452 }
1453
1454 void psys_interpolate_mcol(MCol *mcol, int quad, float *w, MCol *mc)
1455 {
1456         char *cp, *cp1, *cp2, *cp3, *cp4;
1457
1458         cp= (char *)mc;
1459         cp1= (char *)&mcol[0];
1460         cp2= (char *)&mcol[1];
1461         cp3= (char *)&mcol[2];
1462         
1463         if(quad) {
1464                 cp4= (char *)&mcol[3];
1465
1466                 cp[0]= (int)(w[0]*cp1[0] + w[1]*cp2[0] + w[2]*cp3[0] + w[3]*cp4[0]);
1467                 cp[1]= (int)(w[0]*cp1[1] + w[1]*cp2[1] + w[2]*cp3[1] + w[3]*cp4[1]);
1468                 cp[2]= (int)(w[0]*cp1[2] + w[1]*cp2[2] + w[2]*cp3[2] + w[3]*cp4[2]);
1469                 cp[3]= (int)(w[0]*cp1[3] + w[1]*cp2[3] + w[2]*cp3[3] + w[3]*cp4[3]);
1470         }
1471         else {
1472                 cp[0]= (int)(w[0]*cp1[0] + w[1]*cp2[0] + w[2]*cp3[0]);
1473                 cp[1]= (int)(w[0]*cp1[1] + w[1]*cp2[1] + w[2]*cp3[1]);
1474                 cp[2]= (int)(w[0]*cp1[2] + w[1]*cp2[2] + w[2]*cp3[2]);
1475                 cp[3]= (int)(w[0]*cp1[3] + w[1]*cp2[3] + w[2]*cp3[3]);
1476         }
1477 }
1478
1479 static float psys_interpolate_value_from_verts(DerivedMesh *dm, short from, int index, float *fw, float *values)
1480 {
1481         if(values==0 || index==-1)
1482                 return 0.0;
1483
1484         switch(from){
1485                 case PART_FROM_VERT:
1486                         return values[index];
1487                 case PART_FROM_FACE:
1488                 case PART_FROM_VOLUME:
1489                 {
1490                         MFace *mf=dm->getFaceData(dm,index,CD_MFACE);
1491                         return interpolate_particle_value(values[mf->v1],values[mf->v2],values[mf->v3],values[mf->v4],fw,mf->v4);
1492                 }
1493                         
1494         }
1495         return 0.0;
1496 }
1497
1498 /* conversion of pa->fw to origspace layer coordinates */
1499 static void psys_w_to_origspace(float *w, float *uv)
1500 {
1501         uv[0]= w[1] + w[2];
1502         uv[1]= w[2] + w[3];
1503 }
1504
1505 /* conversion of pa->fw to weights in face from origspace */
1506 static void psys_origspace_to_w(OrigSpaceFace *osface, int quad, float *w, float *neww)
1507 {
1508         float v[4][3], co[3];
1509
1510         v[0][0]= osface->uv[0][0]; v[0][1]= osface->uv[0][1]; v[0][2]= 0.0f;
1511         v[1][0]= osface->uv[1][0]; v[1][1]= osface->uv[1][1]; v[1][2]= 0.0f;
1512         v[2][0]= osface->uv[2][0]; v[2][1]= osface->uv[2][1]; v[2][2]= 0.0f;
1513
1514         psys_w_to_origspace(w, co);
1515         co[2]= 0.0f;
1516         
1517         if(quad) {
1518                 v[3][0]= osface->uv[3][0]; v[3][1]= osface->uv[3][1]; v[3][2]= 0.0f;
1519                 MeanValueWeights(v, 4, co, neww);
1520         }
1521         else {
1522                 MeanValueWeights(v, 3, co, neww);
1523                 neww[3]= 0.0f;
1524         }
1525 }
1526
1527 /* find the derived mesh face for a particle, set the mf passed. this is slow
1528  * and can be optimized but only for many lookups. returns the face index. */
1529 int psys_particle_dm_face_lookup(Object *ob, DerivedMesh *dm, int index, float *fw, struct LinkNode *node)
1530 {
1531         Mesh *me= (Mesh*)ob->data;
1532         MFace *mface;
1533         OrigSpaceFace *osface;
1534         int *origindex;
1535         int quad, findex, totface;
1536         float uv[2], (*faceuv)[2];
1537
1538         mface = dm->getFaceDataArray(dm, CD_MFACE);
1539         origindex = dm->getFaceDataArray(dm, CD_ORIGINDEX);
1540         osface = dm->getFaceDataArray(dm, CD_ORIGSPACE);
1541
1542         totface = dm->getNumFaces(dm);
1543         
1544         if(osface==NULL || origindex==NULL) {
1545                 /* Assume we dont need osface data */
1546                 if (index <totface) {
1547                         //printf("\tNO CD_ORIGSPACE, assuming not needed\n");
1548                         return index;
1549                 } else {
1550                         printf("\tNO CD_ORIGSPACE, error out of range\n");
1551                         return DMCACHE_NOTFOUND;
1552                 }
1553         }
1554         else if(index >= me->totface)
1555                 return DMCACHE_NOTFOUND; /* index not in the original mesh */
1556
1557         psys_w_to_origspace(fw, uv);
1558         
1559         if(node) { /* we have a linked list of faces that we use, faster! */
1560                 for(;node; node=node->next) {
1561                         findex= GET_INT_FROM_POINTER(node->link);
1562                         faceuv= osface[findex].uv;
1563                         quad= mface[findex].v4;
1564
1565                         /* check that this intersects - Its possible this misses :/ -
1566                          * could also check its not between */
1567                         if(quad) {
1568                                 if(IsectPQ2Df(uv, faceuv[0], faceuv[1], faceuv[2], faceuv[3]))
1569                                         return findex;
1570                         }
1571                         else if(IsectPT2Df(uv, faceuv[0], faceuv[1], faceuv[2]))
1572                                 return findex;
1573                 }
1574         }
1575         else { /* if we have no node, try every face */
1576                 for(findex=0; findex<totface; findex++) {
1577                         if(origindex[findex] == index) {
1578                                 faceuv= osface[findex].uv;
1579                                 quad= mface[findex].v4;
1580
1581                                 /* check that this intersects - Its possible this misses :/ -
1582                                  * could also check its not between */
1583                                 if(quad) {
1584                                         if(IsectPQ2Df(uv, faceuv[0], faceuv[1], faceuv[2], faceuv[3]))
1585                                                 return findex;
1586                                 }
1587                                 else if(IsectPT2Df(uv, faceuv[0], faceuv[1], faceuv[2]))
1588                                         return findex;
1589                         }
1590                 }
1591         }
1592
1593         return DMCACHE_NOTFOUND;
1594 }
1595
1596 static int psys_map_index_on_dm(DerivedMesh *dm, int from, int index, int index_dmcache, float *fw, float foffset, int *mapindex, float *mapfw)
1597 {
1598         if(index < 0)
1599                 return 0;
1600
1601         if (dm->deformedOnly || index_dmcache == DMCACHE_ISCHILD) {
1602                 /* for meshes that are either only defined or for child particles, the
1603                  * index and fw do not require any mapping, so we can directly use it */
1604                 if(from == PART_FROM_VERT) {
1605                         if(index >= dm->getNumVerts(dm))
1606                                 return 0;
1607
1608                         *mapindex = index;
1609                 }
1610                 else  { /* FROM_FACE/FROM_VOLUME */
1611                         if(index >= dm->getNumFaces(dm))
1612                                 return 0;
1613
1614                         *mapindex = index;
1615                         QUATCOPY(mapfw, fw);
1616                 }
1617         } else {
1618                 /* for other meshes that have been modified, we try to map the particle
1619                  * to their new location, which means a different index, and for faces
1620                  * also a new face interpolation weights */
1621                 if(from == PART_FROM_VERT) {
1622                         if (index_dmcache == DMCACHE_NOTFOUND || index_dmcache > dm->getNumVerts(dm))
1623                                 return 0;
1624
1625                         *mapindex = index_dmcache;
1626                 }
1627                 else  { /* FROM_FACE/FROM_VOLUME */
1628                         /* find a face on the derived mesh that uses this face */
1629                         MFace *mface;
1630                         OrigSpaceFace *osface;
1631                         int i;
1632
1633                         i = index_dmcache;
1634
1635                         if(i== DMCACHE_NOTFOUND || i >= dm->getNumFaces(dm))
1636                                 return 0;
1637
1638                         *mapindex = i;
1639
1640                         /* modify the original weights to become
1641                          * weights for the derived mesh face */
1642                         osface= dm->getFaceDataArray(dm, CD_ORIGSPACE);
1643                         mface= dm->getFaceData(dm, i, CD_MFACE);
1644
1645                         if(osface == NULL)
1646                                 mapfw[0]= mapfw[1]= mapfw[2]= mapfw[3]= 0.0f;
1647                         else
1648                                 psys_origspace_to_w(&osface[i], mface->v4, fw, mapfw);
1649                 }
1650         }
1651
1652         return 1;
1653 }
1654
1655 /* interprets particle data to get a point on a mesh in object space */
1656 void psys_particle_on_dm(DerivedMesh *dm, int from, int index, int index_dmcache, float *fw, float foffset, float *vec, float *nor, float *utan, float *vtan, float *orco, float *ornor)
1657 {
1658         float tmpnor[3], mapfw[4];
1659         float (*orcodata)[3];
1660         int mapindex;
1661
1662         if(!psys_map_index_on_dm(dm, from, index, index_dmcache, fw, foffset, &mapindex, mapfw)) {
1663                 if(vec) { vec[0]=vec[1]=vec[2]=0.0; }
1664                 if(nor) { nor[0]=nor[1]=0.0; nor[2]=1.0; }
1665                 if(orco) { orco[0]=orco[1]=orco[2]=0.0; }
1666                 if(ornor) { ornor[0]=ornor[1]=0.0; ornor[2]=1.0; }
1667                 if(utan) { utan[0]=utan[1]=utan[2]=0.0; }
1668                 if(vtan) { vtan[0]=vtan[1]=vtan[2]=0.0; }
1669
1670                 return;
1671         }
1672
1673         orcodata= dm->getVertDataArray(dm, CD_ORCO);
1674
1675         if(from == PART_FROM_VERT) {
1676                 dm->getVertCo(dm,mapindex,vec);
1677
1678                 if(nor) {
1679                         dm->getVertNo(dm,mapindex,nor);
1680                         Normalize(nor);
1681                 }
1682
1683                 if(orco)
1684                         VECCOPY(orco, orcodata[mapindex])
1685
1686                 if(ornor) {
1687                         dm->getVertNo(dm,mapindex,nor);
1688                         Normalize(nor);
1689                 }
1690
1691                 if(utan && vtan) {
1692                         utan[0]= utan[1]= utan[2]= 0.0f;
1693                         vtan[0]= vtan[1]= vtan[2]= 0.0f;
1694                 }
1695         }
1696         else { /* PART_FROM_FACE / PART_FROM_VOLUME */
1697                 MFace *mface;
1698                 MTFace *mtface;
1699                 MVert *mvert;
1700
1701                 mface=dm->getFaceData(dm,mapindex,CD_MFACE);
1702                 mvert=dm->getVertDataArray(dm,CD_MVERT);
1703                 mtface=CustomData_get_layer(&dm->faceData,CD_MTFACE);
1704
1705                 if(mtface)
1706                         mtface += mapindex;
1707
1708                 if(from==PART_FROM_VOLUME) {
1709                         psys_interpolate_face(mvert,mface,mtface,orcodata,mapfw,vec,tmpnor,utan,vtan,orco,ornor);
1710                         if(nor)
1711                                 VECCOPY(nor,tmpnor);
1712
1713                         Normalize(tmpnor);
1714                         VecMulf(tmpnor,-foffset);
1715                         VECADD(vec,vec,tmpnor);
1716                 }
1717                 else
1718                         psys_interpolate_face(mvert,mface,mtface,orcodata,mapfw,vec,nor,utan,vtan,orco,ornor);
1719         }
1720 }
1721
1722 float psys_particle_value_from_verts(DerivedMesh *dm, short from, ParticleData *pa, float *values)
1723 {
1724         float mapfw[4];
1725         int mapindex;
1726
1727         if(!psys_map_index_on_dm(dm, from, pa->num, pa->num_dmcache, pa->fuv, pa->foffset, &mapindex, mapfw))
1728                 return 0.0f;
1729         
1730         return psys_interpolate_value_from_verts(dm, from, mapindex, mapfw, values);
1731 }
1732
1733 ParticleSystemModifierData *psys_get_modifier(Object *ob, ParticleSystem *psys)
1734 {
1735         ModifierData *md;
1736         ParticleSystemModifierData *psmd;
1737
1738         for(md=ob->modifiers.first; md; md=md->next){
1739                 if(md->type==eModifierType_ParticleSystem){
1740                         psmd= (ParticleSystemModifierData*) md;
1741                         if(psmd->psys==psys){
1742                                 return psmd;
1743                         }
1744                 }
1745         }
1746         return NULL;
1747 }
1748 /************************************************/
1749 /*                      Particles on a shape                            */
1750 /************************************************/
1751 /* ready for future use */
1752 static void psys_particle_on_shape(int distr, int index, float *fuv, float *vec, float *nor, float *utan, float *vtan, float *orco, float *ornor)
1753 {
1754         /* TODO */
1755         float zerovec[3]={0.0f,0.0f,0.0f};
1756         if(vec){
1757                 VECCOPY(vec,zerovec);
1758         }
1759         if(nor){
1760                 VECCOPY(nor,zerovec);
1761         }
1762         if(utan){
1763                 VECCOPY(utan,zerovec);
1764         }
1765         if(vtan){
1766                 VECCOPY(vtan,zerovec);
1767         }
1768         if(orco){
1769                 VECCOPY(orco,zerovec);
1770         }
1771         if(ornor){
1772                 VECCOPY(ornor,zerovec);
1773         }
1774 }
1775 /************************************************/
1776 /*                      Particles on emitter                            */
1777 /************************************************/
1778 void psys_particle_on_emitter(ParticleSystemModifierData *psmd, int from, int index, int index_dmcache, float *fuv, float foffset, float *vec, float *nor, float *utan, float *vtan, float *orco, float *ornor){
1779         if(psmd){
1780                 if(psmd->psys->part->distr==PART_DISTR_GRID && psmd->psys->part->from != PART_FROM_VERT){
1781                         if(vec){
1782                                 VECCOPY(vec,fuv);
1783                         }
1784                         return;
1785                 }
1786                 /* we cant use the num_dmcache */
1787                 psys_particle_on_dm(psmd->dm,from,index,index_dmcache,fuv,foffset,vec,nor,utan,vtan,orco,ornor);
1788         }
1789         else
1790                 psys_particle_on_shape(from,index,fuv,vec,nor,utan,vtan,orco,ornor);
1791
1792 }
1793 /************************************************/
1794 /*                      Path Cache                                                      */
1795 /************************************************/
1796 static float vert_weight(MDeformVert *dvert, int group)
1797 {
1798         MDeformWeight *dw;
1799         int i;
1800         
1801         if(dvert) {
1802                 dw= dvert->dw;
1803                 for(i= dvert->totweight; i>0; i--, dw++) {
1804                         if(dw->def_nr == group) return dw->weight;
1805                         if(i==1) break; /*otherwise dw will point to somewhere it shouldn't*/
1806                 }
1807         }
1808         return 0.0;
1809 }
1810
1811 static void do_prekink(ParticleKey *state, ParticleKey *par, float *par_rot, float time, float freq, float shape, float amplitude, short type, short axis, float obmat[][4])
1812 {
1813         float vec[3]={0.0,0.0,0.0}, q1[4]={1,0,0,0},q2[4];
1814         float t;
1815
1816         CLAMP(time,0.0,1.0);
1817
1818         if(shape!=0.0f && type!=PART_KINK_BRAID) {
1819                 if(shape<0.0f)
1820                         time= (float)pow(time, 1.0+shape);
1821                 else
1822                         time= (float)pow(time, 1.0/(1.0-shape));
1823         }
1824
1825         t=time;
1826
1827         t*=(float)M_PI*freq;
1828
1829         if(par==0) return;
1830
1831         switch(type){
1832                 case PART_KINK_CURL:
1833                         vec[axis]=1.0;
1834                         if(par_rot)
1835                                 QUATCOPY(q2,par_rot)
1836                         else
1837                                 vectoquat(par->vel,axis,(axis+1)%3, q2);
1838                         QuatMulVecf(q2,vec);
1839                         VecMulf(vec,amplitude);
1840                         VECADD(state->co,state->co,vec);
1841
1842                         VECSUB(vec,state->co,par->co);
1843
1844                         if(t!=0.0)
1845                                 VecRotToQuat(par->vel,t,q1);
1846                         
1847                         QuatMulVecf(q1,vec);
1848                         
1849                         VECADD(state->co,par->co,vec);
1850                         break;
1851                 case PART_KINK_RADIAL:
1852                         VECSUB(vec,state->co,par->co);
1853
1854                         Normalize(vec);
1855                         VecMulf(vec,amplitude*(float)sin(t));
1856
1857                         VECADD(state->co,state->co,vec);
1858                         break;
1859                 case PART_KINK_WAVE:
1860                         vec[axis]=1.0;
1861                         if(obmat)
1862                                 Mat4Mul3Vecfl(obmat,vec);
1863
1864                         if(par_rot)
1865                                 QuatMulVecf(par_rot,vec);
1866
1867                         Projf(q1,vec,par->vel);
1868                         
1869                         VECSUB(vec,vec,q1);
1870                         Normalize(vec);
1871
1872                         VecMulf(vec,amplitude*(float)sin(t));
1873
1874                         VECADD(state->co,state->co,vec);
1875                         break;
1876                 case PART_KINK_BRAID:
1877                         if(par){
1878                                 float y_vec[3]={0.0,1.0,0.0};
1879                                 float z_vec[3]={0.0,0.0,1.0};
1880                                 float vec_from_par[3], vec_one[3], radius, state_co[3];
1881                                 float inp_y,inp_z,length;
1882                                 
1883                                 if(par_rot)
1884                                         QUATCOPY(q2,par_rot)
1885                                 else
1886                                         vectoquat(par->vel,axis,(axis+1)%3,q2);
1887                                 QuatMulVecf(q2,y_vec);
1888                                 QuatMulVecf(q2,z_vec);
1889                                 
1890                                 VECSUB(vec_from_par,state->co,par->co);
1891                                 VECCOPY(vec_one,vec_from_par);
1892                                 radius=Normalize(vec_one);
1893
1894                                 inp_y=Inpf(y_vec,vec_one);
1895                                 inp_z=Inpf(z_vec,vec_one);
1896
1897                                 if(inp_y>0.5){
1898                                         VECCOPY(state_co,y_vec);
1899
1900                                         VecMulf(y_vec,amplitude*(float)cos(t));
1901                                         VecMulf(z_vec,amplitude/2.0f*(float)sin(2.0f*t));
1902                                 }
1903                                 else if(inp_z>0.0){
1904                                         VECCOPY(state_co,z_vec);
1905                                         VecMulf(state_co,(float)sin(M_PI/3.0f));
1906                                         VECADDFAC(state_co,state_co,y_vec,-0.5f);
1907
1908                                         VecMulf(y_vec,-amplitude*(float)cos(t + M_PI/3.0f));
1909                                         VecMulf(z_vec,amplitude/2.0f*(float)cos(2.0f*t + M_PI/6.0f));
1910                                 }
1911                                 else{
1912                                         VECCOPY(state_co,z_vec);
1913                                         VecMulf(state_co,-(float)sin(M_PI/3.0f));
1914                                         VECADDFAC(state_co,state_co,y_vec,-0.5f);
1915
1916                                         VecMulf(y_vec,amplitude*(float)-sin(t+M_PI/6.0f));
1917                                         VecMulf(z_vec,amplitude/2.0f*(float)-sin(2.0f*t+M_PI/3.0f));
1918                                 }
1919
1920                                 VecMulf(state_co,amplitude);
1921                                 VECADD(state_co,state_co,par->co);
1922                                 VECSUB(vec_from_par,state->co,state_co);
1923
1924                                 length=Normalize(vec_from_par);
1925                                 VecMulf(vec_from_par,MIN2(length,amplitude/2.0f));
1926
1927                                 VECADD(state_co,par->co,y_vec);
1928                                 VECADD(state_co,state_co,z_vec);
1929                                 VECADD(state_co,state_co,vec_from_par);
1930
1931                                 shape=(2.0f*(float)M_PI)*(1.0f+shape);
1932
1933                                 if(t<shape){
1934                                         shape=t/shape;
1935                                         shape=(float)sqrt((double)shape);
1936                                         VecLerpf(state->co,state->co,state_co,shape);
1937                                 }
1938                                 else{
1939                                         VECCOPY(state->co,state_co);
1940                                 }
1941                         }
1942                         break;
1943         }
1944 }
1945
1946 static void do_clump(ParticleKey *state, ParticleKey *par, float time, float clumpfac, float clumppow, float pa_clump)
1947 {
1948         if(par && clumpfac!=0.0){
1949                 float clump, cpow;
1950
1951                 if(clumppow<0.0)
1952                         cpow=1.0f+clumppow;
1953                 else
1954                         cpow=1.0f+9.0f*clumppow;
1955
1956                 if(clumpfac<0.0) /* clump roots instead of tips */
1957                         clump = -clumpfac*pa_clump*(float)pow(1.0-(double)time,(double)cpow);
1958                 else
1959                         clump = clumpfac*pa_clump*(float)pow((double)time,(double)cpow);
1960                 VecLerpf(state->co,state->co,par->co,clump);
1961         }
1962 }
1963 void precalc_guides(ParticleSimulationData *sim, ListBase *effectors)
1964 {
1965         EffectedPoint point;
1966         ParticleKey state;
1967         EffectorData efd;
1968         EffectorCache *eff;
1969         ParticleSystem *psys = sim->psys;
1970         EffectorWeights *weights = sim->psys->part->effector_weights;
1971         GuideEffectorData *data;
1972         PARTICLE_P;
1973
1974         if(!effectors)
1975                 return;
1976
1977         LOOP_PARTICLES {
1978                 psys_particle_on_emitter(sim->psmd,sim->psys->part->from,pa->num,pa->num_dmcache,pa->fuv,pa->foffset,state.co,0,0,0,0,0);
1979                 pd_point_from_particle(sim, pa, &state, &point);
1980
1981                 for(eff = effectors->first; eff; eff=eff->next) {
1982                         if(eff->pd->forcefield != PFIELD_GUIDE)
1983                                 continue;
1984
1985                         if(!eff->guide_data)
1986                                 eff->guide_data = MEM_callocN(sizeof(GuideEffectorData)*psys->totpart, "GuideEffectorData");
1987
1988                         data = eff->guide_data + p;
1989
1990                         VECSUB(efd.vec_to_point, state.co, eff->guide_loc);
1991                         VECCOPY(efd.nor, eff->guide_dir);
1992                         efd.distance = VecLength(efd.vec_to_point);
1993
1994                         VECCOPY(data->vec_to_point, efd.vec_to_point);
1995                         data->strength = effector_falloff(eff, &efd, &point, weights);
1996                 }
1997         }
1998 }
1999 int do_guides(ListBase *effectors, ParticleKey *state, int index, float time)
2000 {
2001         EffectorCache *eff;
2002         PartDeflect *pd;
2003         Curve *cu;
2004         ParticleKey key, par;
2005         GuideEffectorData *data;
2006
2007         float effect[3] = {0.0f, 0.0f, 0.0f}, veffect[3] = {0.0f, 0.0f, 0.0f};
2008         float guidevec[4], guidedir[3], rot2[4], temp[3];
2009         float guidetime, radius, angle, totstrength = 0.0f;
2010         float vec_to_point[3];
2011
2012         if(effectors) for(eff = effectors->first; eff; eff=eff->next) {
2013                 pd = eff->pd;
2014
2015                 if(pd->forcefield != PFIELD_GUIDE)
2016                         continue;
2017
2018                 data = eff->guide_data + index;
2019
2020                 if(data->strength <= 0.0f)
2021                         continue;
2022
2023                 guidetime = time / (1.0 - pd->free_end);
2024
2025                 if(guidetime>1.0f)
2026                         continue;
2027
2028                 cu = (Curve*)eff->ob->data;
2029
2030                 if(pd->flag & PFIELD_GUIDE_PATH_ADD) {
2031                         if(where_on_path(eff->ob, data->strength * guidetime, guidevec, guidedir, NULL, &radius)==0)
2032                                 return 0;
2033                 }
2034                 else {
2035                         if(where_on_path(eff->ob, guidetime, guidevec, guidedir, NULL, &radius)==0)
2036                                 return 0;
2037                 }
2038
2039                 Mat4MulVecfl(eff->ob->obmat, guidevec);
2040                 Mat4Mul3Vecfl(eff->ob->obmat, guidedir);
2041
2042                 Normalize(guidedir);
2043
2044                 VECCOPY(vec_to_point, data->vec_to_point);
2045
2046                 if(guidetime != 0.0){
2047                         /* curve direction */
2048                         Crossf(temp, eff->guide_dir, guidedir);
2049                         angle = Inpf(eff->guide_dir, guidedir)/(VecLength(eff->guide_dir));
2050                         angle = saacos(angle);
2051                         VecRotToQuat(temp, angle, rot2);
2052                         QuatMulVecf(rot2, vec_to_point);
2053
2054                         /* curve tilt */
2055                         VecRotToQuat(guidedir, guidevec[3] - eff->guide_loc[3], rot2);
2056                         QuatMulVecf(rot2, vec_to_point);
2057                 }
2058
2059                 /* curve taper */
2060                 if(cu->taperobj)
2061                         VecMulf(vec_to_point, calc_taper(eff->scene, cu->taperobj, (int)(data->strength*guidetime*100.0), 100));
2062
2063                 else{ /* curve size*/
2064                         if(cu->flag & CU_PATH_RADIUS) {
2065                                 VecMulf(vec_to_point, radius);
2066                         }
2067                 }
2068                 par.co[0] = par.co[1] = par.co[2] = 0.0f;
2069                 VECCOPY(key.co, vec_to_point);
2070                 do_prekink(&key, &par, 0, guidetime, pd->kink_freq, pd->kink_shape, pd->kink_amp, pd->kink, pd->kink_axis, 0);
2071                 do_clump(&key, &par, guidetime, pd->clump_fac, pd->clump_pow, 1.0f);
2072                 VECCOPY(vec_to_point, key.co);
2073
2074                 VECADD(vec_to_point, vec_to_point, guidevec);
2075                 //VECSUB(pa_loc,pa_loc,pa_zero);
2076                 VECADDFAC(effect, effect, vec_to_point, data->strength);
2077                 VECADDFAC(veffect, veffect, guidedir, data->strength);
2078                 totstrength += data->strength;
2079         }
2080
2081         if(totstrength != 0.0){
2082                 if(totstrength > 1.0)
2083                         VecMulf(effect, 1.0f / totstrength);
2084                 CLAMP(totstrength, 0.0, 1.0);
2085                 //VECADD(effect,effect,pa_zero);
2086                 VecLerpf(state->co, state->co, effect, totstrength);
2087
2088                 Normalize(veffect);
2089                 VecMulf(veffect, VecLength(state->vel));
2090                 VECCOPY(state->vel, veffect);
2091                 return 1;
2092         }
2093         return 0;
2094 }
2095 static void do_rough(float *loc, float mat[4][4], float t, float fac, float size, float thres, ParticleKey *state)
2096 {
2097         float rough[3];
2098         float rco[3];
2099
2100         if(thres!=0.0)
2101                 if((float)fabs((float)(-1.5+loc[0]+loc[1]+loc[2]))<1.5f*thres) return;
2102
2103         VECCOPY(rco,loc);
2104         VecMulf(rco,t);
2105         rough[0]=-1.0f+2.0f*BLI_gTurbulence(size, rco[0], rco[1], rco[2], 2,0,2);
2106         rough[1]=-1.0f+2.0f*BLI_gTurbulence(size, rco[1], rco[2], rco[0], 2,0,2);
2107         rough[2]=-1.0f+2.0f*BLI_gTurbulence(size, rco[2], rco[0], rco[1], 2,0,2);
2108
2109         VECADDFAC(state->co,state->co,mat[0],fac*rough[0]);
2110         VECADDFAC(state->co,state->co,mat[1],fac*rough[1]);
2111         VECADDFAC(state->co,state->co,mat[2],fac*rough[2]);
2112 }
2113 static void do_rough_end(float *loc, float mat[4][4], float t, float fac, float shape, ParticleKey *state)
2114 {
2115         float rough[2];
2116         float roughfac;
2117
2118         roughfac=fac*(float)pow((double)t,shape);
2119         Vec2Copyf(rough,loc);
2120         rough[0]=-1.0f+2.0f*rough[0];
2121         rough[1]=-1.0f+2.0f*rough[1];
2122         Vec2Mulf(rough,roughfac);
2123
2124         VECADDFAC(state->co,state->co,mat[0],rough[0]);
2125         VECADDFAC(state->co,state->co,mat[1],rough[1]);
2126 }
2127 static void do_path_effectors(ParticleSimulationData *sim, int i, ParticleCacheKey *ca, int k, int steps, float *rootco, float effector, float dfra, float cfra, float *length, float *vec)
2128 {
2129         float force[3] = {0.0f,0.0f,0.0f};
2130         ParticleKey eff_key;
2131         EffectedPoint epoint;
2132
2133         /* Don't apply effectors for dynamic hair, otherwise the effectors don't get applied twice. */
2134         if(sim->psys->flag & PSYS_HAIR_DYNAMICS)
2135                 return;
2136
2137         VECCOPY(eff_key.co,(ca-1)->co);
2138         VECCOPY(eff_key.vel,(ca-1)->vel);
2139         QUATCOPY(eff_key.rot,(ca-1)->rot);
2140
2141         pd_point_from_particle(sim, sim->psys->particles+i, &eff_key, &epoint);
2142         pdDoEffectors(sim->psys->effectors, sim->colliders, sim->psys->part->effector_weights, &epoint, force, NULL);
2143
2144         VecMulf(force, effector*pow((float)k / (float)steps, 100.0f * sim->psys->part->eff_hair) / (float)steps);
2145
2146         VecAddf(force, force, vec);
2147
2148         Normalize(force);
2149
2150         VECADDFAC(ca->co, (ca-1)->co, force, *length);
2151
2152         if(k < steps) {
2153                 VecSubf(vec, (ca+1)->co, ca->co);
2154                 *length = VecLength(vec);
2155         }
2156 }
2157 static int check_path_length(int k, ParticleCacheKey *keys, ParticleCacheKey *state, float max_length, float *cur_length, float length, float *dvec)
2158 {
2159         if(*cur_length + length > max_length){
2160                 VecMulf(dvec, (max_length - *cur_length) / length);
2161                 VECADD(state->co, (state - 1)->co, dvec);
2162                 keys->steps = k;
2163                 /* something over the maximum step value */
2164                 return k=100000;
2165         }
2166         else {
2167                 *cur_length+=length;
2168                 return k;
2169         }
2170 }
2171 static void offset_child(ChildParticle *cpa, ParticleKey *par, ParticleKey *child, float flat, float radius)
2172 {
2173         VECCOPY(child->co,cpa->fuv);
2174         VecMulf(child->co,radius);
2175
2176         child->co[0]*=flat;
2177
2178         VECCOPY(child->vel,par->vel);
2179
2180         QuatMulVecf(par->rot,child->co);
2181
2182         QUATCOPY(child->rot,par->rot);
2183
2184         VECADD(child->co,child->co,par->co);
2185 }
2186 float *psys_cache_vgroup(DerivedMesh *dm, ParticleSystem *psys, int vgroup)
2187 {
2188         float *vg=0;
2189
2190         if(vgroup < 0) {
2191                 /* hair dynamics pinning vgroup */
2192
2193         }
2194         else if(psys->vgroup[vgroup]){
2195                 MDeformVert *dvert = dm->getVertDataArray(dm, CD_MDEFORMVERT);
2196                 if(dvert){
2197                         int totvert=dm->getNumVerts(dm), i;
2198                         vg=MEM_callocN(sizeof(float)*totvert, "vg_cache");
2199                         if(psys->vg_neg&(1<<vgroup)){
2200                                 for(i=0; i<totvert; i++)
2201                                         vg[i]=1.0f-vert_weight(dvert+i,psys->vgroup[vgroup]-1);
2202                         }
2203                         else{
2204                                 for(i=0; i<totvert; i++)
2205                                         vg[i]=vert_weight(dvert+i,psys->vgroup[vgroup]-1);
2206                         }
2207                 }
2208         }
2209         return vg;
2210 }
2211 void psys_find_parents(ParticleSimulationData *sim)
2212 {
2213         ParticleSettings *part=sim->psys->part;
2214         KDTree *tree;
2215         ChildParticle *cpa;
2216         int p, totparent,totchild=sim->psys->totchild;
2217         float co[3], orco[3];
2218         int from=PART_FROM_FACE;
2219         totparent=(int)(totchild*part->parents*0.3);
2220
2221         if(G.rendering && part->child_nbr && part->ren_child_nbr)
2222                 totparent*=(float)part->child_nbr/(float)part->ren_child_nbr;
2223
2224         tree=BLI_kdtree_new(totparent);
2225
2226         for(p=0,cpa=sim->psys->child; p<totparent; p++,cpa++){
2227                 psys_particle_on_emitter(sim->psmd,from,cpa->num,DMCACHE_ISCHILD,cpa->fuv,cpa->foffset,co,0,0,0,orco,0);
2228                 BLI_kdtree_insert(tree, p, orco, NULL);
2229         }
2230
2231         BLI_kdtree_balance(tree);
2232
2233         for(; p<totchild; p++,cpa++){
2234                 psys_particle_on_emitter(sim->psmd,from,cpa->num,DMCACHE_ISCHILD,cpa->fuv,cpa->foffset,co,0,0,0,orco,0);
2235                 cpa->parent=BLI_kdtree_find_nearest(tree, orco, NULL, NULL);
2236         }
2237
2238         BLI_kdtree_free(tree);
2239 }
2240
2241 static void get_strand_normal(Material *ma, float *surfnor, float surfdist, float *nor)
2242 {
2243         float cross[3], nstrand[3], vnor[3], blend;
2244
2245         if(!((ma->mode & MA_STR_SURFDIFF) || (ma->strand_surfnor > 0.0f)))
2246                 return;
2247
2248         if(ma->mode & MA_STR_SURFDIFF) {
2249                 Crossf(cross, surfnor, nor);
2250                 Crossf(nstrand, nor, cross);
2251
2252                 blend= INPR(nstrand, surfnor);
2253                 CLAMP(blend, 0.0f, 1.0f);
2254
2255                 VecLerpf(vnor, nstrand, surfnor, blend);
2256                 Normalize(vnor);
2257         }
2258         else
2259                 VECCOPY(vnor, nor)
2260         
2261         if(ma->strand_surfnor > 0.0f) {
2262                 if(ma->strand_surfnor > surfdist) {
2263                         blend= (ma->strand_surfnor - surfdist)/ma->strand_surfnor;
2264                         VecLerpf(vnor, vnor, surfnor, blend);
2265                         Normalize(vnor);
2266                 }
2267         }
2268
2269         VECCOPY(nor, vnor);
2270 }
2271
2272 static int psys_threads_init_path(ParticleThread *threads, Scene *scene, float cfra, int editupdate)
2273 {
2274         ParticleThreadContext *ctx= threads[0].ctx;
2275 /*      Object *ob= ctx->sim.ob; */
2276         ParticleSystem *psys= ctx->sim.psys;
2277         ParticleSettings *part = psys->part;
2278         ParticleEditSettings *pset = &scene->toolsettings->particle;
2279         int totparent=0, between=0;
2280         int steps = (int)pow(2.0, (double)part->draw_step);
2281         int totchild = psys->totchild;
2282         int i, seed, totthread= threads[0].tot;
2283
2284         /*---start figuring out what is actually wanted---*/
2285         if(psys_in_edit_mode(scene, psys)) {
2286                 ParticleEditSettings *pset = &scene->toolsettings->particle;
2287
2288                 if(psys->renderdata==0 && (psys->edit==NULL || pset->flag & PE_DRAW_PART)==0)
2289                         totchild=0;
2290
2291                 steps = (int)pow(2.0, (double)pset->draw_step);
2292         }
2293
2294         if(totchild && part->from!=PART_FROM_PARTICLE && part->childtype==PART_CHILD_FACES){
2295                 totparent=(int)(totchild*part->parents*0.3);
2296                 
2297                 if(G.rendering && part->child_nbr && part->ren_child_nbr)
2298                         totparent*=(float)part->child_nbr/(float)part->ren_child_nbr;
2299
2300                 /* part->parents could still be 0 so we can't test with totparent */
2301                 between=1;
2302         }
2303
2304         if(psys->renderdata)
2305                 steps=(int)pow(2.0,(double)part->ren_step);
2306         else{
2307                 totchild=(int)((float)totchild*(float)part->disp/100.0f);
2308                 totparent=MIN2(totparent,totchild);
2309         }
2310
2311         if(totchild==0) return 0;
2312
2313         /* init random number generator */
2314         if(ctx->sim.psys->part->flag & PART_ANIM_BRANCHING)
2315                 seed= 31415926 + ctx->sim.psys->seed + (int)cfra;
2316         else
2317                 seed= 31415926 + ctx->sim.psys->seed;
2318         
2319         if(part->flag & PART_BRANCHING || ctx->editupdate || totchild < 10000)
2320                 totthread= 1;
2321         
2322         for(i=0; i<totthread; i++) {
2323                 threads[i].rng_path= rng_new(seed);
2324                 threads[i].tot= totthread;
2325         }
2326
2327         /* fill context values */
2328         ctx->between= between;
2329         ctx->steps= steps;
2330         ctx->totchild= totchild;
2331         ctx->totparent= totparent;
2332         ctx->parent_pass= 0;
2333         ctx->cfra= cfra;
2334
2335         psys->lattice = psys_get_lattice(&ctx->sim);
2336
2337         /* cache all relevant vertex groups if they exist */
2338         if(part->from!=PART_FROM_PARTICLE){
2339                 ctx->vg_length = psys_cache_vgroup(ctx->dm,psys,PSYS_VG_LENGTH);
2340                 ctx->vg_clump = psys_cache_vgroup(ctx->dm,psys,PSYS_VG_CLUMP);
2341                 ctx->vg_kink = psys_cache_vgroup(ctx->dm,psys,PSYS_VG_KINK);
2342                 ctx->vg_rough1 = psys_cache_vgroup(ctx->dm,psys,PSYS_VG_ROUGH1);
2343                 ctx->vg_rough2 = psys_cache_vgroup(ctx->dm,psys,PSYS_VG_ROUGH2);
2344                 ctx->vg_roughe = psys_cache_vgroup(ctx->dm,psys,PSYS_VG_ROUGHE);
2345                 if(psys->part->flag & PART_CHILD_EFFECT)
2346                         ctx->vg_effector = psys_cache_vgroup(ctx->dm,psys,PSYS_VG_EFFECTOR);
2347         }
2348
2349         /* set correct ipo timing */
2350 #if 0 // XXX old animation system
2351         if(part->flag&PART_ABS_TIME && part->ipo){
2352                 calc_ipo(part->ipo, cfra);
2353                 execute_ipo((ID *)part, part->ipo);
2354         }
2355 #endif // XXX old animation system
2356
2357         return 1;
2358 }
2359
2360 /* note: this function must be thread safe, except for branching! */
2361 static void psys_thread_create_path(ParticleThread *thread, struct ChildParticle *cpa, ParticleCacheKey *keys, int i)
2362 {
2363         ParticleThreadContext *ctx= thread->ctx;
2364         Object *ob= ctx->sim.ob;
2365         ParticleSystem *psys = ctx->sim.psys;
2366         ParticleSettings *part = psys->part;
2367         ParticleCacheKey **cache= psys->childcache;
2368         ParticleCacheKey **pcache= psys_in_edit_mode(ctx->sim.scene, psys) ? psys->edit->pathcache : psys->pathcache;
2369         ParticleCacheKey *state, *par = NULL, *key[4];
2370         ParticleData *pa=NULL;
2371         ParticleTexture ptex;
2372         float *cpa_fuv=0, *par_rot=0;
2373         float co[3], orco[3], ornor[3], hairmat[4][4], t, cpa_1st[3], dvec[3];
2374         float branch_begin, branch_end, branch_prob, rough_rand;
2375         float length, max_length = 1.0f, cur_length = 0.0f;
2376         float eff_length, eff_vec[3];
2377         int k, cpa_num;
2378         short cpa_from;
2379
2380         if(!pcache)
2381                 return;
2382
2383         if(part->flag & PART_BRANCHING) {
2384                 branch_begin=rng_getFloat(thread->rng_path);
2385                 branch_end=branch_begin+(1.0f-branch_begin)*rng_getFloat(thread->rng_path);
2386                 branch_prob=rng_getFloat(thread->rng_path);
2387                 rough_rand=rng_getFloat(thread->rng_path);
2388         }
2389         else {
2390                 branch_begin= 0.0f;
2391                 branch_end= 0.0f;
2392                 branch_prob= 0.0f;
2393                 rough_rand= 0.0f;
2394         }
2395
2396         if(i<psys->totpart){
2397                 branch_begin=0.0f;
2398                 branch_end=1.0f;
2399                 branch_prob=0.0f;
2400         }
2401
2402         if(ctx->between){
2403                 int w, needupdate;
2404                 float foffset;
2405
2406                 if(ctx->editupdate && !(part->flag & PART_BRANCHING)) {
2407                         needupdate= 0;
2408                         w= 0;
2409                         while(w<4 && cpa->pa[w]>=0) {
2410                                 if(psys->edit->points[cpa->pa[w]].flag & PEP_EDIT_RECALC) {
2411                                         needupdate= 1;
2412                                         break;
2413                                 }
2414                                 w++;
2415                         }
2416
2417                         if(!needupdate)
2418                                 return;
2419                         else
2420                                 memset(keys, 0, sizeof(*keys)*(ctx->steps+1));
2421                 }
2422
2423                 /* get parent paths */
2424                 w= 0;
2425                 while(w<4 && cpa->pa[w]>=0){
2426                         key[w] = pcache[cpa->pa[w]];
2427                         w++;
2428                 }
2429
2430                 /* get the original coordinates (orco) for texture usage */
2431                 cpa_num = cpa->num;
2432                 
2433                 foffset= cpa->foffset;
2434                 cpa_fuv = cpa->fuv;
2435                 cpa_from = PART_FROM_FACE;
2436
2437                 psys_particle_on_emitter(ctx->sim.psmd,cpa_from,cpa_num,DMCACHE_ISCHILD,cpa->fuv,foffset,co,ornor,0,0,orco,0);
2438
2439                 if(part->path_start==0.0f) {
2440                         /* we need to save the actual root position of the child for positioning it accurately to the surface of the emitter */
2441                         VECCOPY(cpa_1st,co);
2442                         Mat4MulVecfl(ob->obmat,cpa_1st);
2443                 }
2444
2445                 pa = psys->particles + cpa->parent;
2446
2447                 psys_mat_hair_to_global(ob, ctx->sim.psmd->dm, psys->part->from, pa, hairmat);
2448
2449                 pa=0;
2450         }
2451         else{
2452                 if(ctx->editupdate && !(part->flag & PART_BRANCHING)) {
2453                         if(!(psys->edit->points[cpa->parent].flag & PEP_EDIT_RECALC))
2454                                 return;
2455
2456                         memset(keys, 0, sizeof(*keys)*(ctx->steps+1));
2457                 }
2458
2459                 /* get the parent path */
2460                 key[0]=pcache[cpa->parent];
2461
2462                 /* get the original coordinates (orco) for texture usage */
2463                 pa=psys->particles+cpa->parent;
2464
2465                 cpa_from=part->from;
2466                 cpa_num=pa->num;
2467                 cpa_fuv=pa->fuv;
2468
2469                 psys_particle_on_emitter(ctx->sim.psmd,cpa_from,cpa_num,DMCACHE_ISCHILD,cpa_fuv,pa->foffset,co,ornor,0,0,orco,0);
2470
2471                 psys_mat_hair_to_global(ob, ctx->sim.psmd->dm, psys->part->from, pa, hairmat);
2472         }
2473
2474         keys->steps = ctx->steps;
2475
2476         /* correct child ipo timing */
2477 #if 0 // XXX old animation system
2478         if((part->flag&PART_ABS_TIME)==0 && part->ipo){
2479                 float dsta=part->end-part->sta;
2480                 calc_ipo(part->ipo, 100.0f*(ctx->cfra-(part->sta+dsta*cpa->rand[1]))/(part->lifetime*(1.0f - part->randlife*cpa->rand[0])));
2481                 execute_ipo((ID *)part, part->ipo);
2482         }
2483 #endif // XXX old animation system
2484
2485         /* get different child parameters from textures & vgroups */
2486         get_child_modifier_parameters(part, ctx, cpa, cpa_from, cpa_num, cpa_fuv, orco, &ptex);
2487
2488         if(ptex.exist < PSYS_FRAND(i + 24)) {
2489                 keys->steps = -1;
2490                 return;
2491         }
2492
2493         /* create the child path */
2494         for(k=0,state=keys; k<=ctx->steps; k++,state++){
2495                 if(ctx->between){
2496                         int w=0;
2497
2498                         state->co[0] = state->co[1] = state->co[2] = 0.0f;
2499                         state->vel[0] = state->vel[1] = state->vel[2] = 0.0f;
2500                         state->rot[0] = state->rot[1] = state->rot[2] = state->rot[3] = 0.0f;
2501
2502                         //QUATCOPY(state->rot,key[0]->rot);
2503
2504                         /* child position is the weighted sum of parent positions */
2505                         while(w<4 && cpa->pa[w]>=0){
2506                                 state->co[0] += cpa->w[w] * key[w]->co[0];
2507                                 state->co[1] += cpa->w[w] * key[w]->co[1];
2508                                 state->co[2] += cpa->w[w] * key[w]->co[2];
2509
2510                                 state->vel[0] += cpa->w[w] * key[w]->vel[0];
2511                                 state->vel[1] += cpa->w[w] * key[w]->vel[1];
2512                                 state->vel[2] += cpa->w[w] * key[w]->vel[2];
2513                                 key[w]++;
2514                                 w++;
2515                         }
2516                         if(part->path_start==0.0f) {
2517                                 if(k==0){
2518                                         /* calculate the offset between actual child root position and first position interpolated from parents */
2519                                         VECSUB(cpa_1st,cpa_1st,state->co);
2520                                 }
2521                                 /* apply offset for correct positioning */
2522                                 VECADD(state->co,state->co,cpa_1st);
2523                         }
2524                 }
2525                 else{
2526                         /* offset the child from the parent position */
2527                         offset_child(cpa, (ParticleKey*)key[0], (ParticleKey*)state, part->childflat, part->childrad);
2528
2529                         key[0]++;
2530                 }
2531         }
2532
2533         /* apply effectors */
2534         if(part->flag & PART_CHILD_EFFECT) {
2535                 for(k=0,state=keys; k<=ctx->steps; k++,state++) {
2536                         if(k) {
2537                                 do_path_effectors(&ctx->sim, cpa->pa[0], state, k, ctx->steps, keys->co, ptex.effector, 0.0f, ctx->cfra, &eff_length, eff_vec);
2538                         }
2539                         else {
2540                                 VecSubf(eff_vec,(state+1)->co,state->co);
2541                                 eff_length= VecLength(eff_vec);
2542                         }
2543                 }
2544         }
2545
2546         for(k=0,state=keys; k<=ctx->steps; k++,state++){
2547                 t=(float)k/(float)ctx->steps;
2548
2549                 if(ctx->totparent){
2550                         if(i>=ctx->totparent) {
2551                                 /* this is now threadsafe, virtual parents are calculated before rest of children */
2552                                 par = cache[cpa->parent] + k;
2553                         }
2554                         else
2555                                 par=0;
2556                 }
2557                 else if(cpa->parent>=0){
2558                         par=pcache[cpa->parent]+k;
2559                         par_rot = par->rot;
2560                 }
2561
2562                 /* apply different deformations to the child path */
2563                 do_child_modifiers(&ctx->sim, &ptex, (ParticleKey *)par, par_rot, cpa, orco, hairmat, (ParticleKey *)state, t);
2564
2565                 /* TODO: better branching */
2566                 //if(part->flag & PART_BRANCHING && ctx->between == 0 && part->flag & PART_ANIM_BRANCHING)
2567                 //      rough_t = t * rough_rand;
2568                 //else
2569                 //      rough_t = t;
2570
2571                 /* TODO: better branching */
2572                 //if(part->flag & PART_BRANCHING && ctx->between==0){
2573                 //      if(branch_prob > part->branch_thres){
2574                 //              branchfac=0.0f;
2575                 //      }
2576                 //      else{
2577                 //              if(part->flag & PART_SYMM_BRANCHING){
2578                 //                      if(t < branch_begin || t > branch_end)
2579                 //                              branchfac=0.0f;
2580                 //                      else{
2581                 //                              if((t-branch_begin)/(branch_end-branch_begin)<0.5)
2582                 //                                      branchfac=2.0f*(t-branch_begin)/(branch_end-branch_begin);
2583                 //                              else
2584                 //                                      branchfac=2.0f*(branch_end-t)/(branch_end-branch_begin);
2585
2586                 //                              CLAMP(branchfac,0.0f,1.0f);
2587                 //                      }
2588                 //              }
2589                 //              else{
2590                 //                      if(t < branch_begin){
2591                 //                              branchfac=0.0f;
2592                 //                      }
2593                 //                      else{
2594                 //                              branchfac=(t-branch_begin)/((1.0f-branch_begin)*0.5f);
2595                 //                              CLAMP(branchfac,0.0f,1.0f);
2596                 //                      }
2597                 //              }
2598                 //      }
2599
2600                 //      if(i<psys->totpart)
2601                 //              VecLerpf(state->co, (pcache[i] + k)->co, state->co, branchfac);
2602                 //      else
2603                 //              /* this is not threadsafe, but should only happen for
2604                 //               * branching particles particles, which are not threaded */
2605                 //              VecLerpf(state->co, (cache[i - psys->totpart] + k)->co, state->co, branchfac);
2606                 //}
2607
2608                 /* we have to correct velocity because of kink & clump */
2609                 if(k>1){
2610                         VECSUB((state-1)->vel,state->co,(state-2)->co);
2611                         VecMulf((state-1)->vel,0.5);
2612
2613                         if(ctx->ma && (part->draw & PART_DRAW_MAT_COL))
2614                                 get_strand_normal(ctx->ma, ornor, cur_length, (state-1)->vel);
2615                 }
2616
2617                 /* check if path needs to be cut before actual end of data points */
2618                 if(k){
2619                         VECSUB(dvec,state->co,(state-1)->co);
2620                         length=1.0f/(float)ctx->steps;
2621                         k=check_path_length(k,keys,state,max_length,&cur_length,length,dvec);
2622                 }
2623                 else{
2624                         /* initialize length calculation */
2625                         max_length= ptex.length;
2626                         cur_length= 0.0f;
2627                 }
2628
2629                 if(ctx->ma && (part->draw & PART_DRAW_MAT_COL)) {
2630                         VECCOPY(state->col, &ctx->ma->r)
2631                         get_strand_normal(ctx->ma, ornor, cur_length, state->vel);
2632                 }
2633         }
2634 }
2635
2636 static void *exec_child_path_cache(void *data)
2637 {
2638         ParticleThread *thread= (ParticleThread*)data;
2639         ParticleThreadContext *ctx= thread->ctx;
2640         ParticleSystem *psys= ctx->sim.psys;
2641         ParticleCacheKey **cache= psys->childcache;
2642         ChildParticle *cpa;
2643         int i, totchild= ctx->totchild, first= 0;
2644
2645         if(thread->tot > 1){
2646                 first= ctx->parent_pass? 0 : ctx->totparent;
2647                 totchild= ctx->parent_pass? ctx->totparent : ctx->totchild;
2648         }
2649         
2650         cpa= psys->child + first + thread->num;
2651         for(i=first+thread->num; i<totchild; i+=thread->tot, cpa+=thread->tot)
2652                 psys_thread_create_path(thread, cpa, cache[i], i);
2653
2654         return 0;
2655 }
2656
2657 void psys_cache_child_paths(ParticleSimulationData *sim, float cfra, int editupdate)
2658 {
2659         ParticleSettings *part = sim->psys->part;
2660         ParticleThread *pthreads;
2661         ParticleThreadContext *ctx;
2662         ParticleCacheKey **cache;
2663         ListBase threads;
2664         int i, totchild, totparent, totthread;
2665
2666         if(sim->psys->flag & PSYS_GLOBAL_HAIR)
2667                 return;
2668
2669         pthreads= psys_threads_create(sim);
2670
2671         if(!psys_threads_init_path(pthreads, sim->scene, cfra, editupdate)) {
2672                 psys_threads_free(pthreads);
2673                 return;
2674         }
2675
2676         ctx= pthreads[0].ctx;
2677         totchild= ctx->totchild;
2678         totparent= ctx->totparent;
2679
2680         if(editupdate && sim->psys->childcache && !(part->flag & PART_BRANCHING) && totchild == sim->psys->totchildcache) {
2681                 cache = sim->psys->childcache;
2682         }
2683         else {
2684                 /* clear out old and create new empty path cache */
2685                 free_child_path_cache(sim->psys);
2686                 sim->psys->childcache= psys_alloc_path_cache_buffers(&sim->psys->childcachebufs, totchild, ctx->steps+1);
2687                 sim->psys->totchildcache = totchild;
2688         }
2689
2690         totthread= pthreads[0].tot;
2691
2692         if(totthread > 1) {
2693
2694                 /* make virtual child parents thread safe by calculating them first */
2695                 if(totparent) {
2696                         BLI_init_threads(&threads, exec_child_path_cache, totthread);
2697                         
2698                         for(i=0; i<totthread; i++) {
2699                                 pthreads[i].ctx->parent_pass = 1;
2700                                 BLI_insert_thread(&threads, &pthreads[i]);
2701                         }
2702
2703                         BLI_end_threads(&threads);
2704
2705                         for(i=0; i<totthread; i++)
2706                                 pthreads[i].ctx->parent_pass = 0;
2707                 }
2708
2709                 BLI_init_threads(&threads, exec_child_path_cache, totthread);
2710
2711                 for(i=0; i<totthread; i++)
2712                         BLI_insert_thread(&threads, &pthreads[i]);
2713
2714                 BLI_end_threads(&threads);
2715         }
2716         else
2717                 exec_child_path_cache(&pthreads[0]);
2718
2719         psys_threads_free(pthreads);
2720 }
2721 /* Calculates paths ready for drawing/rendering.                                                                        */
2722 /* -Usefull for making use of opengl vertex arrays for super fast strand drawing.       */
2723 /* -Makes child strands possible and creates them too into the cache.                           */
2724 /* -Cached path data is also used to determine cut position for the editmode tool.      */
2725 void psys_cache_paths(ParticleSimulationData *sim, float cfra)
2726 {
2727         PARTICLE_PSMD;
2728         ParticleEditSettings *pset = &sim->scene->toolsettings->particle;
2729         ParticleSystem *psys = sim->psys;
2730         ParticleSettings *part = psys->part;
2731         ParticleCacheKey *ca, **cache= psys->pathcache;
2732
2733         DerivedMesh *hair_dm = psys->hair_out_dm;
2734         
2735         ParticleKey result;
2736         
2737         Material *ma;
2738         ParticleInterpolationData pind;
2739
2740         PARTICLE_P;
2741         
2742         float birthtime = 0.0, dietime = 0.0;
2743         float t, time = 0.0, dfra = 1.0, frs_sec = sim->scene->r.frs_sec;
2744         float col[4] = {0.5f, 0.5f, 0.5f, 1.0f};
2745         float prev_tangent[3], hairmat[4][4];
2746         float rotmat[3][3];
2747         int k;
2748         int steps = (int)pow(2.0, (double)(psys->renderdata ? part->ren_step : part->draw_step));
2749         int totpart = psys->totpart;
2750         float length, vec[3];
2751         float *vg_effector= NULL, effector=0.0f;
2752         float *vg_length= NULL, pa_length=1.0f;
2753         int keyed, baked;
2754
2755         /* we don't have anything valid to create paths from so let's quit here */
2756         if((psys->flag & PSYS_HAIR_DONE || psys->flag & PSYS_KEYED || psys->pointcache->flag & PTCACHE_BAKED)==0)
2757                 return;
2758
2759         if(psys_in_edit_mode(sim->scene, psys))
2760                 if(psys->renderdata==0 && (psys->edit==NULL || pset->flag & PE_DRAW_PART)==0)
2761                         return;
2762         
2763         BLI_srandom(psys->seed);
2764
2765         keyed = psys->flag & PSYS_KEYED;
2766         baked = !hair_dm && psys->pointcache->flag & PTCACHE_BAKED;
2767
2768         /* clear out old and create new empty path cache */
2769         psys_free_path_cache(psys, psys->edit);
2770         cache= psys->pathcache= psys_alloc_path_cache_buffers(&psys->pathcachebufs, totpart, steps+1);
2771
2772         psys->lattice = psys_get_lattice(sim);
2773         ma= give_current_material(sim->ob, psys->part->omat);
2774         if(ma && (psys->part->draw & PART_DRAW_MAT_COL))
2775                 VECCOPY(col, &ma->r)
2776
2777         if(psys->part->from!=PART_FROM_PARTICLE && !(psys->flag & PSYS_GLOBAL_HAIR)) {
2778                 if(!(psys->part->flag & PART_CHILD_EFFECT))
2779                         vg_effector = psys_cache_vgroup(psmd->dm, psys, PSYS_VG_EFFECTOR);
2780                 
2781                 if(!psys->totchild)
2782                         vg_length = psys_cache_vgroup(psmd->dm, psys, PSYS_VG_LENGTH);
2783         }
2784
2785         /*---first main loop: create all actual particles' paths---*/
2786         LOOP_SHOWN_PARTICLES {
2787                 if(!psys->totchild) {
2788                         BLI_srandom(psys->seed + p);
2789                         pa_length = 1.0f - part->randlength * BLI_frand();
2790                         if(vg_length)
2791                                 pa_length *= psys_particle_value_from_verts(psmd->dm,part->from,pa,vg_length);
2792                 }
2793
2794                 pind.keyed = keyed;
2795                 pind.cache = baked ? psys->pointcache : NULL;
2796                 pind.epoint = NULL;
2797                 pind.bspline = (psys->part->flag & PART_HAIR_BSPLINE);
2798                 pind.dm = hair_dm;
2799
2800                 memset(cache[p], 0, sizeof(*cache[p])*(steps+1));
2801
2802                 cache[p]->steps = steps;
2803
2804                 /*--get the first data points--*/
2805                 init_particle_interpolation(sim->ob, sim->psys, pa, &pind);
2806
2807                 /* hairmat is needed for for non-hair particle too so we get proper rotations */
2808                 psys_mat_hair_to_global(sim->ob, psmd->dm, psys->part->from, pa, hairmat);
2809                 VECCOPY(rotmat[0], hairmat[2]);
2810                 VECCOPY(rotmat[1], hairmat[1]);
2811                 VECCOPY(rotmat[2], hairmat[0]);
2812
2813                 if(part->draw & PART_ABS_PATH_TIME) {
2814                         birthtime = MAX2(pind.birthtime, part->path_start);
2815                         dietime = MIN2(pind.dietime, part->path_end);
2816                 }
2817                 else {
2818                         float tb = pind.birthtime;
2819                         birthtime = tb + part->path_start * (pind.dietime - tb);
2820                         dietime = tb + part->path_end * (pind.dietime - tb);
2821                 }
2822
2823                 if(birthtime >= dietime) {
2824                         cache[p]->steps = -1;
2825                         continue;
2826                 }
2827
2828                 dietime = birthtime + pa_length * (dietime - birthtime);
2829
2830                 /*--interpolate actual path from data points--*/
2831                 for(k=0, ca=cache[p]; k<=steps; k++, ca++){
2832                         time = (float)k / (float)steps;
2833
2834                         t = birthtime + time * (dietime - birthtime);
2835
2836                         result.time = -t;
2837
2838                         do_particle_interpolation(psys, p, pa, t, frs_sec, &pind, &result);
2839
2840                         /* dynamic hair is in object space */
2841                         /* keyed and baked are allready in global space */
2842                         if(hair_dm)
2843                                 Mat4MulVecfl(sim->ob->obmat, result.co);
2844                         else if(!keyed && !baked && !(psys->flag & PSYS_GLOBAL_HAIR))
2845                                 Mat4MulVecfl(hairmat, result.co);
2846
2847                         VECCOPY(ca->co, result.co);
2848                         VECCOPY(ca->col, col);
2849                 }
2850                 
2851                 /*--modify paths and calculate rotation & velocity--*/
2852
2853                 VecSubf(vec,(cache[p]+1)->co,cache[p]->co);
2854                 length = VecLength(vec);
2855
2856                 effector= 1.0f;
2857                 if(vg_effector)
2858                         effector*= psys_particle_value_from_verts(psmd->dm,psys->part->from,pa,vg_effector);
2859
2860                 for(k=0, ca=cache[p]; k<=steps; k++, ca++) {
2861                         if(!(psys->flag & PSYS_GLOBAL_HAIR)) {
2862                         /* apply effectors */
2863                                 if(!(psys->part->flag & PART_CHILD_EFFECT) && k)
2864                                         do_path_effectors(sim, p, ca, k, steps, cache[p]->co, effector, dfra, cfra, &length, vec);
2865
2866                                 /* apply guide curves to path data */
2867                                 if(sim->psys->effectors && (psys->part->flag & PART_CHILD_EFFECT)==0)
2868                                         /* ca is safe to cast, since only co and vel are used */
2869                                         do_guides(sim->psys->effectors, (ParticleKey*)ca, p, (float)k/(float)steps);
2870
2871                                 /* apply lattice */
2872                                 if(psys->lattice)
2873                                         calc_latt_deform(psys->lattice, ca->co, 1.0f);
2874
2875                                 /* figure out rotation */
2876                                 
2877                                 if(k) {
2878                                         float cosangle, angle, tangent[3], normal[3], q[4];
2879
2880                                         if(k == 1) {
2881                                                 /* calculate initial tangent for incremental rotations */
2882                                                 VECSUB(tangent, ca->co, (ca - 1)->co);
2883                                                 VECCOPY(prev_tangent, tangent);
2884                                                 Normalize(prev_tangent);
2885
2886                                                 /* First rotation is based on emitting face orientation.                */
2887                                                 /* This is way better than having flipping rotations resulting  */
2888                                                 /* from using a global axis as a rotation pole (vec_to_quat()). */
2889                                                 /* It's not an ideal solution though since it disregards the    */
2890                                                 /* initial tangent, but taking that in to account will allow    */
2891                                                 /* the possibility of flipping again. -jahka                                    */
2892                                                 Mat3ToQuat_is_ok(rotmat, (ca-1)->rot);
2893                                         }
2894                                         else {
2895                                                 VECSUB(tangent, ca->co, (ca - 1)->co);
2896                                                 Normalize(tangent);
2897
2898                                                 cosangle= Inpf(tangent, prev_tangent);
2899
2900                                                 /* note we do the comparison on cosangle instead of
2901                                                 * angle, since floating point accuracy makes it give
2902                                                 * different results across platforms */
2903                                                 if(cosangle > 0.999999f) {
2904                                                         QUATCOPY((ca - 1)->rot, (ca - 2)->rot);
2905                                                 }
2906                                                 else {
2907                                                         angle= saacos(cosangle);
2908                                                         Crossf(normal, prev_tangent, tangent);
2909                                                         VecRotToQuat(normal, angle, q);
2910                                                         QuatMul((ca - 1)->rot, q, (ca - 2)->rot);
2911                                                 }
2912
2913                                                 VECCOPY(prev_tangent, tangent);
2914                                         }
2915
2916                                         if(k == steps)
2917                                                 QUATCOPY(ca->rot, (ca - 1)->rot);
2918                                 }
2919
2920                         }
2921                         
2922                         /* set velocity */
2923
2924                         if(k){
2925                                 VECSUB(ca->vel, ca->co, (ca-1)->co);
2926
2927                                 if(k==1) {
2928                                         VECCOPY((ca-1)->vel, ca->vel);
2929                                 }
2930
2931                         }
2932                 }
2933         }
2934
2935         psys->totcached = totpart;
2936
2937         if(psys && psys->lattice){
2938                 end_latt_deform(psys->lattice);
2939                 psys->lattice= NULL;
2940         }
2941
2942         if(vg_effector)
2943                 MEM_freeN(vg_effector);
2944
2945         if(vg_length)
2946                 MEM_freeN(vg_length);
2947 }
2948 void psys_cache_edit_paths(Scene *scene, Object *ob, PTCacheEdit *edit, float cfra)
2949 {
2950         ParticleCacheKey *ca, **cache= edit->pathcache;
2951         ParticleEditSettings *pset = &scene->toolsettings->particle;
2952         
2953         PTCacheEditPoint *point = edit->points;
2954         PTCacheEditKey *ekey = NULL;
2955
2956         ParticleSystem *psys = edit->psys;
2957         ParticleSystemModifierData *psmd = psys_get_modifier(ob, psys);
2958         ParticleData *pa = psys ? psys->particles : NULL;
2959
2960         ParticleInterpolationData pind;
2961         ParticleKey result;
2962         
2963         float birthtime = 0.0, dietime = 0.0;
2964         float t, time = 0.0, keytime = 0.0, frs_sec;
2965         float hairmat[4][4], rotmat[3][3], prev_tangent[3];
2966         int k,i;
2967         int steps = (int)pow(2.0, (double)pset->draw_step);
2968         int totpart = edit->totpoint;
2969         float sel_col[3];
2970         float nosel_col[3];
2971
2972         steps = MAX2(steps, 4);
2973
2974         if(!cache || edit->totpoint != edit->totcached) {
2975                 /* clear out old and create new empty path cache */
2976                 psys_free_path_cache(edit->psys, edit);
2977                 cache= edit->pathcache= psys_alloc_path_cache_buffers(&edit->pathcachebufs, totpart, steps+1);
2978         }
2979
2980         frs_sec = (psys || edit->pid.flag & PTCACHE_VEL_PER_SEC) ? 25.0f : 1.0f;
2981
2982         sel_col[0] = (float)edit->sel_col[0] / 255.0f;
2983         sel_col[1] = (float)edit->sel_col[1] / 255.0f;
2984         sel_col[2] = (float)edit->sel_col[2] / 255.0f;
2985         nosel_col[0] = (float)edit->nosel_col[0] / 255.0f;
2986         nosel_col[1] = (float)edit->nosel_col[1] / 255.0f;
2987         nosel_col[2] = (float)edit->nosel_col[2] / 255.0f;
2988
2989         /*---first main loop: create all actual particles' paths---*/
2990         for(i=0; i<totpart; i++, pa+=pa?1:0, point++){
2991                 if(edit->totcached && !(point->flag & PEP_EDIT_RECALC))
2992                         continue;
2993
2994                 ekey = point->keys;
2995
2996                 pind.keyed = 0;
2997                 pind.cache = NULL;
2998                 pind.epoint = point;
2999                 pind.bspline = psys ? (psys->part->flag & PART_HAIR_BSPLINE) : 0;
3000                 pind.dm = NULL;
3001
3002                 memset(cache[i], 0, sizeof(*cache[i])*(steps+1));
3003
3004                 cache[i]->steps = steps;
3005
3006                 /*--get the first data points--*/
3007                 init_particle_interpolation(ob, psys, pa, &pind);
3008
3009                 if(psys) {
3010                         psys_mat_hair_to_global(ob, psmd->dm, psys->part->from, pa, hairmat);
3011                         VECCOPY(rotmat[0], hairmat[2]);
3012                         VECCOPY(rotmat[1], hairmat[1]);
3013                         VECCOPY(rotmat[2], hairmat[0]);
3014                 }
3015
3016                 birthtime = pind.birthtime;
3017                 dietime = pind.dietime;
3018
3019                 if(birthtime >= dietime) {
3020                         cache[i]->steps = -1;
3021                         continue;
3022                 }
3023
3024                 /*--interpolate actual path from data points--*/
3025                 for(k=0, ca=cache[i]; k<=steps; k++, ca++){
3026                         time = (float)k / (float)steps;
3027
3028                         t = birthtime + time * (dietime - birthtime);
3029
3030                         result.time = -t;
3031
3032                         do_particle_interpolation(psys, i, pa, t, frs_sec, &pind, &result);
3033
3034                          /* non-hair points are allready in global space */
3035                         if(psys && !(psys->flag & PSYS_GLOBAL_HAIR)) {
3036                                 Mat4MulVecfl(hairmat, result.co);
3037
3038                                 /* create rotations for proper creation of children */
3039                                 if(k) {
3040                                         float cosangle, angle, tangent[3], normal[3], q[4];
3041
3042                                         if(k == 1) {
3043                                                 /* calculate initial tangent for incremental rotations */
3044                                                 VECSUB(tangent, ca->co, (ca - 1)->co);
3045                                                 VECCOPY(prev_tangent, tangent);
3046                                                 Normalize(prev_tangent);
3047
3048                                                 /* First rotation is based on emitting face orientation.                */
3049                                                 /* This is way better than having flipping rotations resulting  */
3050                                                 /* from using a global axis as a rotation pole (vec_to_quat()). */
3051                                                 /* It's not an ideal solution though since it disregards the    */
3052                                                 /* initial tangent, but taking that in to account will allow    */
3053                                                 /* the possibility of flipping again. -jahka                                    */
3054                                                 Mat3ToQuat_is_ok(rotmat, (ca-1)->rot);
3055                                         }
3056                                         else {
3057                                                 VECSUB(tangent, ca->co, (ca - 1)->co);
3058                                                 Normalize(tangent);
3059
3060                                                 cosangle= Inpf(tangent, prev_tangent);
3061
3062                                                 /* note we do the comparison on cosangle instead of
3063                                                 * angle, since floating point accuracy makes it give
3064                                                 * different results across platforms */
3065                                                 if