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