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