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