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