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