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