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