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