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