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