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