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