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