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