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