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