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