Cleanup: remove redundant doxygen \file argument
[blender.git] / source / blender / blenkernel / intern / particle_system.c
1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public License
4  * as published by the Free Software Foundation; either version 2
5  * of the License, or (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software Foundation,
14  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
15  *
16  * The Original Code is Copyright (C) 2007 by Janne Karhu.
17  * All rights reserved.
18  * Adaptive time step
19  * Classical SPH
20  * Copyright 2011-2012 AutoCRC
21  */
22
23 /** \file \ingroup bke
24  */
25
26
27 #include <stddef.h>
28
29 #include <stdlib.h>
30 #include <math.h>
31 #include <string.h>
32
33 #include "MEM_guardedalloc.h"
34
35 #include "DNA_anim_types.h"
36 #include "DNA_boid_types.h"
37 #include "DNA_particle_types.h"
38 #include "DNA_mesh_types.h"
39 #include "DNA_meshdata_types.h"
40 #include "DNA_modifier_types.h"
41 #include "DNA_object_force_types.h"
42 #include "DNA_object_types.h"
43 #include "DNA_curve_types.h"
44 #include "DNA_scene_types.h"
45 #include "DNA_texture_types.h"
46 #include "DNA_listBase.h"
47
48 #include "BLI_utildefines.h"
49 #include "BLI_edgehash.h"
50 #include "BLI_rand.h"
51 #include "BLI_math.h"
52 #include "BLI_blenlib.h"
53 #include "BLI_kdtree.h"
54 #include "BLI_kdopbvh.h"
55 #include "BLI_task.h"
56 #include "BLI_threads.h"
57 #include "BLI_linklist.h"
58
59 #include "BKE_animsys.h"
60 #include "BKE_boids.h"
61 #include "BKE_collision.h"
62 #include "BKE_colortools.h"
63 #include "BKE_effect.h"
64 #include "BKE_library.h"
65 #include "BKE_library_query.h"
66 #include "BKE_particle.h"
67
68 #include "BKE_collection.h"
69 #include "BKE_object.h"
70 #include "BKE_material.h"
71 #include "BKE_cloth.h"
72 #include "BKE_lattice.h"
73 #include "BKE_pointcache.h"
74 #include "BKE_mesh.h"
75 #include "BKE_modifier.h"
76 #include "BKE_scene.h"
77 #include "BKE_bvhutils.h"
78
79 #include "DEG_depsgraph.h"
80 #include "DEG_depsgraph_physics.h"
81 #include "DEG_depsgraph_query.h"
82
83 #include "PIL_time.h"
84
85 #include "RE_shader_ext.h"
86
87 /* fluid sim particle import */
88 #ifdef WITH_MOD_FLUID
89 #include "DNA_object_fluidsim_types.h"
90 #include "LBM_fluidsim.h"
91 #include <zlib.h>
92 #include <string.h>
93
94 #endif // WITH_MOD_FLUID
95
96 static ThreadRWMutex psys_bvhtree_rwlock = BLI_RWLOCK_INITIALIZER;
97
98 /************************************************/
99 /*                      Reacting to system events                       */
100 /************************************************/
101
102 static int particles_are_dynamic(ParticleSystem *psys)
103 {
104         if (psys->pointcache->flag & PTCACHE_BAKED)
105                 return 0;
106
107         if (psys->part->type == PART_HAIR)
108                 return psys->flag & PSYS_HAIR_DYNAMICS;
109         else
110                 return ELEM(psys->part->phystype, PART_PHYS_NEWTON, PART_PHYS_BOIDS, PART_PHYS_FLUID);
111 }
112
113 float psys_get_current_display_percentage(ParticleSystem *psys, const bool use_render_params)
114 {
115         ParticleSettings *part=psys->part;
116
117         if ((use_render_params && !particles_are_dynamic(psys)) ||  /* non-dynamic particles can be rendered fully */
118             (part->child_nbr && part->childtype)  ||    /* display percentage applies to children */
119             (psys->pointcache->flag & PTCACHE_BAKING))  /* baking is always done with full amount */
120         {
121                 return 1.0f;
122         }
123
124         return psys->part->disp/100.0f;
125 }
126
127 static int tot_particles(ParticleSystem *psys, PTCacheID *pid)
128 {
129         if (pid && psys->pointcache->flag & PTCACHE_EXTERNAL)
130                 return pid->cache->totpoint;
131         else if (psys->part->distr == PART_DISTR_GRID && psys->part->from != PART_FROM_VERT)
132                 return psys->part->grid_res * psys->part->grid_res * psys->part->grid_res - psys->totunexist;
133         else
134                 return psys->part->totpart - psys->totunexist;
135 }
136
137 void psys_reset(ParticleSystem *psys, int mode)
138 {
139         PARTICLE_P;
140
141         if (ELEM(mode, PSYS_RESET_ALL, PSYS_RESET_DEPSGRAPH)) {
142                 if (mode == PSYS_RESET_ALL || !(psys->flag & PSYS_EDITED)) {
143                         /* don't free if not absolutely necessary */
144                         if (psys->totpart != tot_particles(psys, NULL)) {
145                                 psys_free_particles(psys);
146                                 psys->totpart= 0;
147                         }
148
149                         psys->totkeyed= 0;
150                         psys->flag &= ~(PSYS_HAIR_DONE|PSYS_KEYED);
151
152                         if (psys->edit && psys->free_edit) {
153                                 psys->free_edit(psys->edit);
154                                 psys->edit = NULL;
155                                 psys->free_edit = NULL;
156                         }
157                 }
158         }
159         else if (mode == PSYS_RESET_CACHE_MISS) {
160                 /* set all particles to be skipped */
161                 LOOP_PARTICLES {
162                         pa->flag |= PARS_NO_DISP;
163                 }
164         }
165
166         /* reset children */
167         if (psys->child) {
168                 MEM_freeN(psys->child);
169                 psys->child= NULL;
170         }
171
172         psys->totchild= 0;
173
174         /* reset path cache */
175         psys_free_path_cache(psys, psys->edit);
176
177         /* reset point cache */
178         BKE_ptcache_invalidate(psys->pointcache);
179
180         if (psys->fluid_springs) {
181                 MEM_freeN(psys->fluid_springs);
182                 psys->fluid_springs = NULL;
183         }
184
185         psys->tot_fluidsprings = psys->alloc_fluidsprings = 0;
186 }
187
188 static void realloc_particles(ParticleSimulationData *sim, int new_totpart)
189 {
190         ParticleSystem *psys = sim->psys;
191         ParticleSettings *part = psys->part;
192         ParticleData *newpars = NULL;
193         BoidParticle *newboids = NULL;
194         PARTICLE_P;
195         int totpart, totsaved = 0;
196
197         if (new_totpart<0) {
198                 if ((part->distr == PART_DISTR_GRID) && (part->from != PART_FROM_VERT)) {
199                         totpart= part->grid_res;
200                         totpart*=totpart*totpart;
201                 }
202                 else
203                         totpart=part->totpart;
204         }
205         else
206                 totpart=new_totpart;
207
208         if (totpart != psys->totpart) {
209                 if (psys->edit && psys->free_edit) {
210                         psys->free_edit(psys->edit);
211                         psys->edit = NULL;
212                         psys->free_edit = NULL;
213                 }
214
215                 if (totpart) {
216                         newpars= MEM_callocN(totpart*sizeof(ParticleData), "particles");
217                         if (newpars == NULL)
218                                 return;
219
220                         if (psys->part->phystype == PART_PHYS_BOIDS) {
221                                 newboids= MEM_callocN(totpart*sizeof(BoidParticle), "boid particles");
222
223                                 if (newboids == NULL) {
224                                         /* allocation error! */
225                                         if (newpars)
226                                                 MEM_freeN(newpars);
227                                         return;
228                                 }
229                         }
230                 }
231
232                 if (psys->particles) {
233                         totsaved=MIN2(psys->totpart,totpart);
234                         /*save old pars*/
235                         if (totsaved) {
236                                 memcpy(newpars,psys->particles,totsaved*sizeof(ParticleData));
237
238                                 if (psys->particles->boid)
239                                         memcpy(newboids, psys->particles->boid, totsaved*sizeof(BoidParticle));
240                         }
241
242                         if (psys->particles->keys)
243                                 MEM_freeN(psys->particles->keys);
244
245                         if (psys->particles->boid)
246                                 MEM_freeN(psys->particles->boid);
247
248                         for (p=0, pa=newpars; p<totsaved; p++, pa++) {
249                                 if (pa->keys) {
250                                         pa->keys= NULL;
251                                         pa->totkey= 0;
252                                 }
253                         }
254
255                         for (p=totsaved, pa=psys->particles+totsaved; p<psys->totpart; p++, pa++)
256                                 if (pa->hair) MEM_freeN(pa->hair);
257
258                         MEM_freeN(psys->particles);
259                         psys_free_pdd(psys);
260                 }
261
262                 psys->particles=newpars;
263                 psys->totpart=totpart;
264
265                 if (newboids) {
266                         LOOP_PARTICLES {
267                                 pa->boid = newboids++;
268                         }
269                 }
270         }
271
272         if (psys->child) {
273                 MEM_freeN(psys->child);
274                 psys->child=NULL;
275                 psys->totchild=0;
276         }
277 }
278
279 int psys_get_child_number(Scene *scene, ParticleSystem *psys, const bool use_render_params)
280 {
281         int nbr;
282
283         if (!psys->part->childtype)
284                 return 0;
285
286         if (use_render_params)
287                 nbr= psys->part->ren_child_nbr;
288         else
289                 nbr= psys->part->child_nbr;
290
291         return get_render_child_particle_number(&scene->r, nbr, use_render_params);
292 }
293
294 int psys_get_tot_child(Scene *scene, ParticleSystem *psys, const bool use_render_params)
295 {
296         return psys->totpart*psys_get_child_number(scene, psys, use_render_params);
297 }
298
299 /************************************************/
300 /*                      Distribution                                            */
301 /************************************************/
302
303 void psys_calc_dmcache(Object *ob, Mesh *mesh_final, Mesh *mesh_original, ParticleSystem *psys)
304 {
305         /* use for building derived mesh mapping info:
306          *
307          * node: the allocated links - total derived mesh element count
308          * nodearray: the array of nodes aligned with the base mesh's elements, so
309          *            each original elements can reference its derived elements
310          */
311         Mesh *me= (Mesh*)ob->data;
312         bool use_modifier_stack= psys->part->use_modifier_stack;
313         PARTICLE_P;
314
315         /* CACHE LOCATIONS */
316         if (!mesh_final->runtime.deformed_only) {
317                 /* Will use later to speed up subsurf/evaluated mesh. */
318                 LinkNode *node, *nodedmelem, **nodearray;
319                 int totdmelem, totelem, i, *origindex, *origindex_poly = NULL;
320
321                 if (psys->part->from == PART_FROM_VERT) {
322                         totdmelem = mesh_final->totvert;
323
324                         if (use_modifier_stack) {
325                                 totelem= totdmelem;
326                                 origindex= NULL;
327                         }
328                         else {
329                                 totelem= me->totvert;
330                                 origindex = CustomData_get_layer(&mesh_final->vdata, CD_ORIGINDEX);
331                         }
332                 }
333                 else { /* FROM_FACE/FROM_VOLUME */
334                         totdmelem= mesh_final->totface;
335
336                         if (use_modifier_stack) {
337                                 totelem= totdmelem;
338                                 origindex= NULL;
339                                 origindex_poly= NULL;
340                         }
341                         else {
342                                 totelem = mesh_original->totface;
343                                 origindex = CustomData_get_layer(&mesh_final->fdata, CD_ORIGINDEX);
344
345                                 /* for face lookups we need the poly origindex too */
346                                 origindex_poly = CustomData_get_layer(&mesh_final->pdata, CD_ORIGINDEX);
347                                 if (origindex_poly == NULL) {
348                                         origindex= NULL;
349                                 }
350                         }
351                 }
352
353                 nodedmelem= MEM_callocN(sizeof(LinkNode)*totdmelem, "psys node elems");
354                 nodearray= MEM_callocN(sizeof(LinkNode *)*totelem, "psys node array");
355
356                 for (i=0, node=nodedmelem; i<totdmelem; i++, node++) {
357                         int origindex_final;
358                         node->link = POINTER_FROM_INT(i);
359
360                         /* may be vertex or face origindex */
361                         if (use_modifier_stack) {
362                                 origindex_final = i;
363                         }
364                         else {
365                                 origindex_final = origindex ? origindex[i] : ORIGINDEX_NONE;
366
367                                 /* if we have a poly source, do an index lookup */
368                                 if (origindex_poly && origindex_final != ORIGINDEX_NONE) {
369                                         origindex_final = origindex_poly[origindex_final];
370                                 }
371                         }
372
373                         if (origindex_final != ORIGINDEX_NONE && origindex_final < totelem) {
374                                 if (nodearray[origindex_final]) {
375                                         /* prepend */
376                                         node->next = nodearray[origindex_final];
377                                         nodearray[origindex_final] = node;
378                                 }
379                                 else {
380                                         nodearray[origindex_final] = node;
381                                 }
382                         }
383                 }
384
385                 /* cache the verts/faces! */
386                 LOOP_PARTICLES {
387                         if (pa->num < 0) {
388                                 pa->num_dmcache = DMCACHE_NOTFOUND;
389                                 continue;
390                         }
391
392                         if (use_modifier_stack) {
393                                 if (pa->num < totelem)
394                                         pa->num_dmcache = DMCACHE_ISCHILD;
395                                 else
396                                         pa->num_dmcache = DMCACHE_NOTFOUND;
397                         }
398                         else {
399                                 if (psys->part->from == PART_FROM_VERT) {
400                                         if (pa->num < totelem && nodearray[pa->num])
401                                                 pa->num_dmcache= POINTER_AS_INT(nodearray[pa->num]->link);
402                                         else
403                                                 pa->num_dmcache = DMCACHE_NOTFOUND;
404                                 }
405                                 else { /* FROM_FACE/FROM_VOLUME */
406                                         pa->num_dmcache = psys_particle_dm_face_lookup(mesh_final, mesh_original, pa->num, pa->fuv, nodearray);
407                                 }
408                         }
409                 }
410
411                 MEM_freeN(nodearray);
412                 MEM_freeN(nodedmelem);
413         }
414         else {
415                 /* TODO PARTICLE, make the following line unnecessary, each function
416                  * should know to use the num or num_dmcache, set the num_dmcache to
417                  * an invalid value, just in case */
418
419                 LOOP_PARTICLES {
420                         pa->num_dmcache = DMCACHE_NOTFOUND;
421                 }
422         }
423 }
424
425 /* threaded child particle distribution and path caching */
426 void psys_thread_context_init(ParticleThreadContext *ctx, ParticleSimulationData *sim)
427 {
428         memset(ctx, 0, sizeof(ParticleThreadContext));
429         ctx->sim = *sim;
430         ctx->mesh = ctx->sim.psmd->mesh_final;
431         ctx->ma = give_current_material(sim->ob, sim->psys->part->omat);
432 }
433
434 #define MAX_PARTICLES_PER_TASK 256 /* XXX arbitrary - maybe use at least number of points instead for better balancing? */
435
436 BLI_INLINE int ceil_ii(int a, int b)
437 {
438         return (a + b - 1) / b;
439 }
440
441 void psys_tasks_create(ParticleThreadContext *ctx, int startpart, int endpart, ParticleTask **r_tasks, int *r_numtasks)
442 {
443         ParticleTask *tasks;
444         int numtasks = ceil_ii((endpart - startpart), MAX_PARTICLES_PER_TASK);
445         float particles_per_task = (float)(endpart - startpart) / (float)numtasks, p, pnext;
446         int i;
447
448         tasks = MEM_callocN(sizeof(ParticleTask) * numtasks, "ParticleThread");
449         *r_numtasks = numtasks;
450         *r_tasks = tasks;
451
452         p = (float)startpart;
453         for (i = 0; i < numtasks; i++, p = pnext) {
454                 pnext = p + particles_per_task;
455
456                 tasks[i].ctx = ctx;
457                 tasks[i].begin = (int)p;
458                 tasks[i].end = min_ii((int)pnext, endpart);
459         }
460 }
461
462 void psys_tasks_free(ParticleTask *tasks, int numtasks)
463 {
464         int i;
465
466         /* threads */
467         for (i = 0; i < numtasks; ++i) {
468                 if (tasks[i].rng)
469                         BLI_rng_free(tasks[i].rng);
470                 if (tasks[i].rng_path)
471                         BLI_rng_free(tasks[i].rng_path);
472         }
473
474         MEM_freeN(tasks);
475 }
476
477 void psys_thread_context_free(ParticleThreadContext *ctx)
478 {
479         /* path caching */
480         if (ctx->vg_length)
481                 MEM_freeN(ctx->vg_length);
482         if (ctx->vg_clump)
483                 MEM_freeN(ctx->vg_clump);
484         if (ctx->vg_kink)
485                 MEM_freeN(ctx->vg_kink);
486         if (ctx->vg_rough1)
487                 MEM_freeN(ctx->vg_rough1);
488         if (ctx->vg_rough2)
489                 MEM_freeN(ctx->vg_rough2);
490         if (ctx->vg_roughe)
491                 MEM_freeN(ctx->vg_roughe);
492         if (ctx->vg_twist)
493                 MEM_freeN(ctx->vg_twist);
494
495         if (ctx->sim.psys->lattice_deform_data) {
496                 end_latt_deform(ctx->sim.psys->lattice_deform_data);
497                 ctx->sim.psys->lattice_deform_data = NULL;
498         }
499
500         /* distribution */
501         if (ctx->jit) MEM_freeN(ctx->jit);
502         if (ctx->jitoff) MEM_freeN(ctx->jitoff);
503         if (ctx->weight) MEM_freeN(ctx->weight);
504         if (ctx->index) MEM_freeN(ctx->index);
505         if (ctx->seams) MEM_freeN(ctx->seams);
506         //if (ctx->vertpart) MEM_freeN(ctx->vertpart);
507         BLI_kdtree_free(ctx->tree);
508
509         if (ctx->clumpcurve != NULL) {
510                 curvemapping_free(ctx->clumpcurve);
511         }
512         if (ctx->roughcurve != NULL) {
513                 curvemapping_free(ctx->roughcurve);
514         }
515         if (ctx->twistcurve != NULL) {
516                 curvemapping_free(ctx->twistcurve);
517         }
518 }
519
520 static void initialize_particle_texture(ParticleSimulationData *sim, ParticleData *pa, int p)
521 {
522         ParticleSystem *psys = sim->psys;
523         ParticleSettings *part = psys->part;
524         ParticleTexture ptex;
525
526         psys_get_texture(sim, pa, &ptex, PAMAP_INIT, 0.f);
527
528         switch (part->type) {
529                 case PART_EMITTER:
530                         if (ptex.exist < psys_frand(psys, p + 125)) {
531                                 pa->flag |= PARS_UNEXIST;
532                         }
533                         pa->time = part->sta + (part->end - part->sta)*ptex.time;
534                         break;
535                 case PART_HAIR:
536                         if (ptex.exist < psys_frand(psys, p + 125)) {
537                                 pa->flag |= PARS_UNEXIST;
538                         }
539                         pa->time = 0.f;
540                         break;
541                 case PART_FLUID:
542                         break;
543         }
544 }
545
546 /* set particle parameters that don't change during particle's life */
547 void initialize_particle(ParticleSimulationData *sim, ParticleData *pa)
548 {
549         ParticleSettings *part = sim->psys->part;
550         float birth_time = (float)(pa - sim->psys->particles) / (float)sim->psys->totpart;
551
552         pa->flag &= ~PARS_UNEXIST;
553         pa->time = part->sta + (part->end - part->sta) * birth_time;
554
555         pa->hair_index = 0;
556         /* we can't reset to -1 anymore since we've figured out correct index in distribute_particles */
557         /* usage other than straight after distribute has to handle this index by itself - jahka*/
558         //pa->num_dmcache = DMCACHE_NOTFOUND; /* assume we don't have a derived mesh face */
559 }
560
561 static void initialize_all_particles(ParticleSimulationData *sim)
562 {
563         ParticleSystem *psys = sim->psys;
564         ParticleSettings *part = psys->part;
565         /* Grid distributionsets UNEXIST flag, need to take care of
566          * it here because later this flag is being reset.
567          *
568          * We can't do it for any distribution, because it'll then
569          * conflict with texture influence, which does not free
570          * unexisting particles and only sets flag.
571          *
572          * It's not so bad, because only grid distribution sets
573          * UNEXIST flag.
574          */
575         const bool emit_from_volume_grid = (part->distr == PART_DISTR_GRID) &&
576                                            (!ELEM(part->from, PART_FROM_VERT, PART_FROM_CHILD));
577         PARTICLE_P;
578         LOOP_PARTICLES {
579                 if (!(emit_from_volume_grid && (pa->flag & PARS_UNEXIST) != 0)) {
580                         initialize_particle(sim, pa);
581                 }
582         }
583 }
584
585 static void free_unexisting_particles(ParticleSimulationData *sim)
586 {
587         ParticleSystem *psys = sim->psys;
588         PARTICLE_P;
589
590         psys->totunexist = 0;
591
592         LOOP_PARTICLES {
593                 if (pa->flag & PARS_UNEXIST) {
594                         psys->totunexist++;
595                 }
596         }
597
598         if (psys->totpart && psys->totunexist == psys->totpart) {
599                 if (psys->particles->boid)
600                         MEM_freeN(psys->particles->boid);
601
602                 MEM_freeN(psys->particles);
603                 psys->particles = NULL;
604                 psys->totpart = psys->totunexist = 0;
605         }
606
607         if (psys->totunexist) {
608                 int newtotpart = psys->totpart - psys->totunexist;
609                 ParticleData *npa, *newpars;
610
611                 npa = newpars = MEM_callocN(newtotpart * sizeof(ParticleData), "particles");
612
613                 for (p=0, pa=psys->particles; p<newtotpart; p++, pa++, npa++) {
614                         while (pa->flag & PARS_UNEXIST)
615                                 pa++;
616
617                         memcpy(npa, pa, sizeof(ParticleData));
618                 }
619
620                 if (psys->particles->boid)
621                         MEM_freeN(psys->particles->boid);
622                 MEM_freeN(psys->particles);
623                 psys->particles = newpars;
624                 psys->totpart -= psys->totunexist;
625
626                 if (psys->particles->boid) {
627                         BoidParticle *newboids = MEM_callocN(psys->totpart * sizeof(BoidParticle), "boid particles");
628
629                         LOOP_PARTICLES {
630                                 pa->boid = newboids++;
631                         }
632
633                 }
634         }
635 }
636
637 static void get_angular_velocity_vector(short avemode, ParticleKey *state, float vec[3])
638 {
639         switch (avemode) {
640                 case PART_AVE_VELOCITY:
641                         copy_v3_v3(vec, state->vel);
642                         break;
643                 case PART_AVE_HORIZONTAL:
644                 {
645                         float zvec[3];
646                         zvec[0] = zvec[1] = 0;
647                         zvec[2] = 1.f;
648                         cross_v3_v3v3(vec, state->vel, zvec);
649                         break;
650                 }
651                 case PART_AVE_VERTICAL:
652                 {
653                         float zvec[3], temp[3];
654                         zvec[0] = zvec[1] = 0;
655                         zvec[2] = 1.f;
656                         cross_v3_v3v3(temp, state->vel, zvec);
657                         cross_v3_v3v3(vec, temp, state->vel);
658                         break;
659                 }
660                 case PART_AVE_GLOBAL_X:
661                         vec[0] = 1.f;
662                         vec[1] = vec[2] = 0;
663                         break;
664                 case PART_AVE_GLOBAL_Y:
665                         vec[1] = 1.f;
666                         vec[0] = vec[2] = 0;
667                         break;
668                 case PART_AVE_GLOBAL_Z:
669                         vec[2] = 1.f;
670                         vec[0] = vec[1] = 0;
671                         break;
672         }
673 }
674
675 void psys_get_birth_coords(ParticleSimulationData *sim, ParticleData *pa, ParticleKey *state, float dtime, float cfra)
676 {
677         Object *ob = sim->ob;
678         ParticleSystem *psys = sim->psys;
679         ParticleSettings *part = psys->part;
680         ParticleTexture ptex;
681         float fac, phasefac, nor[3] = {0,0,0},loc[3],vel[3] = {0.0,0.0,0.0},rot[4],q2[4];
682         float r_vel[3],r_ave[3],r_rot[4],vec[3],p_vel[3] = {0.0,0.0,0.0};
683         float x_vec[3] = {1.0,0.0,0.0}, utan[3] = {0.0,1.0,0.0}, vtan[3] = {0.0,0.0,1.0}, rot_vec[3] = {0.0,0.0,0.0};
684         float q_phase[4];
685
686         const bool use_boids = ((part->phystype == PART_PHYS_BOIDS) &&
687                                 (pa->boid != NULL));
688         const bool use_tangents = ((use_boids == false) &&
689                                    ((part->tanfac != 0.0f) || (part->rotmode == PART_ROT_NOR_TAN)));
690
691         int p = pa - psys->particles;
692
693         /* get birth location from object               */
694         if (use_tangents)
695                 psys_particle_on_emitter(sim->psmd, part->from,pa->num, pa->num_dmcache, pa->fuv,pa->foffset,loc,nor,utan,vtan,0);
696         else
697                 psys_particle_on_emitter(sim->psmd, part->from,pa->num, pa->num_dmcache, pa->fuv,pa->foffset,loc,nor,0,0,0);
698
699         /* get possible textural influence */
700         psys_get_texture(sim, pa, &ptex, PAMAP_IVEL, cfra);
701
702         /* particles live in global space so    */
703         /* let's convert:                                               */
704         /* -location                                                    */
705         mul_m4_v3(ob->obmat, loc);
706
707         /* -normal                                                              */
708         mul_mat3_m4_v3(ob->obmat, nor);
709         normalize_v3(nor);
710
711         /* -tangent                                                             */
712         if (use_tangents) {
713                 //float phase=vg_rot?2.0f*(psys_particle_value_from_verts(sim->psmd->dm,part->from,pa,vg_rot)-0.5f):0.0f;
714                 float phase=0.0f;
715                 mul_v3_fl(vtan,-cosf((float)M_PI*(part->tanphase+phase)));
716                 fac= -sinf((float)M_PI*(part->tanphase+phase));
717                 madd_v3_v3fl(vtan, utan, fac);
718
719                 mul_mat3_m4_v3(ob->obmat,vtan);
720
721                 copy_v3_v3(utan, nor);
722                 mul_v3_fl(utan,dot_v3v3(vtan,nor));
723                 sub_v3_v3(vtan, utan);
724
725                 normalize_v3(vtan);
726         }
727
728
729         /* -velocity (boids need this even if there's no random velocity) */
730         if (part->randfac != 0.0f || (part->phystype==PART_PHYS_BOIDS && pa->boid)) {
731                 r_vel[0] = 2.0f * (psys_frand(psys, p + 10) - 0.5f);
732                 r_vel[1] = 2.0f * (psys_frand(psys, p + 11) - 0.5f);
733                 r_vel[2] = 2.0f * (psys_frand(psys, p + 12) - 0.5f);
734
735                 mul_mat3_m4_v3(ob->obmat, r_vel);
736                 normalize_v3(r_vel);
737         }
738
739         /* -angular velocity                                    */
740         if (part->avemode==PART_AVE_RAND) {
741                 r_ave[0] = 2.0f * (psys_frand(psys, p + 13) - 0.5f);
742                 r_ave[1] = 2.0f * (psys_frand(psys, p + 14) - 0.5f);
743                 r_ave[2] = 2.0f * (psys_frand(psys, p + 15) - 0.5f);
744
745                 mul_mat3_m4_v3(ob->obmat,r_ave);
746                 normalize_v3(r_ave);
747         }
748
749         /* -rotation                                                    */
750         if (part->randrotfac != 0.0f) {
751                 r_rot[0] = 2.0f * (psys_frand(psys, p + 16) - 0.5f);
752                 r_rot[1] = 2.0f * (psys_frand(psys, p + 17) - 0.5f);
753                 r_rot[2] = 2.0f * (psys_frand(psys, p + 18) - 0.5f);
754                 r_rot[3] = 2.0f * (psys_frand(psys, p + 19) - 0.5f);
755                 normalize_qt(r_rot);
756
757                 mat4_to_quat(rot,ob->obmat);
758                 mul_qt_qtqt(r_rot,r_rot,rot);
759         }
760
761         if (use_boids) {
762                 float dvec[3], q[4], mat[3][3];
763
764                 copy_v3_v3(state->co,loc);
765
766                 /* boids don't get any initial velocity  */
767                 zero_v3(state->vel);
768
769                 /* boids store direction in ave */
770                 if (fabsf(nor[2])==1.0f) {
771                         sub_v3_v3v3(state->ave, loc, ob->obmat[3]);
772                         normalize_v3(state->ave);
773                 }
774                 else {
775                         copy_v3_v3(state->ave, nor);
776                 }
777
778                 /* calculate rotation matrix */
779                 project_v3_v3v3(dvec, r_vel, state->ave);
780                 sub_v3_v3v3(mat[0], state->ave, dvec);
781                 normalize_v3(mat[0]);
782                 negate_v3_v3(mat[2], r_vel);
783                 normalize_v3(mat[2]);
784                 cross_v3_v3v3(mat[1], mat[2], mat[0]);
785
786                 /* apply rotation */
787                 mat3_to_quat_is_ok( q,mat);
788                 copy_qt_qt(state->rot, q);
789         }
790         else {
791                 /* conversion done so now we apply new: */
792                 /* -velocity from:                                              */
793
794                 /*              *reactions                                              */
795                 if (dtime > 0.f) {
796                         sub_v3_v3v3(vel, pa->state.vel, pa->prev_state.vel);
797                 }
798
799                 /*              *emitter velocity                               */
800                 if (dtime != 0.f && part->obfac != 0.f) {
801                         sub_v3_v3v3(vel, loc, state->co);
802                         mul_v3_fl(vel, part->obfac/dtime);
803                 }
804
805                 /*              *emitter normal                                 */
806                 if (part->normfac != 0.f)
807                         madd_v3_v3fl(vel, nor, part->normfac);
808
809                 /*              *emitter tangent                                */
810                 if (sim->psmd && part->tanfac != 0.f)
811                         madd_v3_v3fl(vel, vtan, part->tanfac);
812
813                 /*              *emitter object orientation             */
814                 if (part->ob_vel[0] != 0.f) {
815                         normalize_v3_v3(vec, ob->obmat[0]);
816                         madd_v3_v3fl(vel, vec, part->ob_vel[0]);
817                 }
818                 if (part->ob_vel[1] != 0.f) {
819                         normalize_v3_v3(vec, ob->obmat[1]);
820                         madd_v3_v3fl(vel, vec, part->ob_vel[1]);
821                 }
822                 if (part->ob_vel[2] != 0.f) {
823                         normalize_v3_v3(vec, ob->obmat[2]);
824                         madd_v3_v3fl(vel, vec, part->ob_vel[2]);
825                 }
826
827                 /*              *texture                                                */
828                 /* TODO */
829
830                 /*              *random                                                 */
831                 if (part->randfac != 0.f)
832                         madd_v3_v3fl(vel, r_vel, part->randfac);
833
834                 /*              *particle                                               */
835                 if (part->partfac != 0.f)
836                         madd_v3_v3fl(vel, p_vel, part->partfac);
837
838                 mul_v3_v3fl(state->vel, vel, ptex.ivel);
839
840                 /* -location from emitter                               */
841                 copy_v3_v3(state->co,loc);
842
843                 /* -rotation                                                    */
844                 unit_qt(state->rot);
845
846                 if (part->rotmode) {
847                         bool use_global_space;
848
849                         /* create vector into which rotation is aligned */
850                         switch (part->rotmode) {
851                                 case PART_ROT_NOR:
852                                 case PART_ROT_NOR_TAN:
853                                         copy_v3_v3(rot_vec, nor);
854                                         use_global_space = false;
855                                         break;
856                                 case PART_ROT_VEL:
857                                         copy_v3_v3(rot_vec, vel);
858                                         use_global_space = true;
859                                         break;
860                                 case PART_ROT_GLOB_X:
861                                 case PART_ROT_GLOB_Y:
862                                 case PART_ROT_GLOB_Z:
863                                         rot_vec[part->rotmode - PART_ROT_GLOB_X] = 1.0f;
864                                         use_global_space = true;
865                                         break;
866                                 case PART_ROT_OB_X:
867                                 case PART_ROT_OB_Y:
868                                 case PART_ROT_OB_Z:
869                                         copy_v3_v3(rot_vec, ob->obmat[part->rotmode - PART_ROT_OB_X]);
870                                         use_global_space = false;
871                                         break;
872                                 default:
873                                         use_global_space = true;
874                                         break;
875                         }
876
877                         /* create rotation quat */
878
879
880                         if (use_global_space) {
881                                 negate_v3(rot_vec);
882                                 vec_to_quat(q2, rot_vec, OB_POSX, OB_POSZ);
883
884                                 /* randomize rotation quat */
885                                 if (part->randrotfac != 0.0f) {
886                                         interp_qt_qtqt(rot, q2, r_rot, part->randrotfac);
887                                 }
888                                 else {
889                                         copy_qt_qt(rot, q2);
890                                 }
891                         }
892                         else {
893                                 /* calculate rotation in local-space */
894                                 float q_obmat[4];
895                                 float q_imat[4];
896
897                                 mat4_to_quat(q_obmat, ob->obmat);
898                                 invert_qt_qt_normalized(q_imat, q_obmat);
899
900
901                                 if (part->rotmode != PART_ROT_NOR_TAN) {
902                                         float rot_vec_local[3];
903
904                                         /* rot_vec */
905                                         negate_v3(rot_vec);
906                                         copy_v3_v3(rot_vec_local, rot_vec);
907                                         mul_qt_v3(q_imat, rot_vec_local);
908                                         normalize_v3(rot_vec_local);
909
910                                         vec_to_quat(q2, rot_vec_local, OB_POSX, OB_POSZ);
911                                 }
912                                 else {
913                                         /* (part->rotmode == PART_ROT_NOR_TAN) */
914                                         float tmat[3][3];
915
916                                         /* note: utan_local is not taken from 'utan', we calculate from rot_vec/vtan */
917                                         /* note: it looks like rotation phase may be applied twice (once with vtan, again below)
918                                          * however this isn't the case - campbell */
919                                         float *rot_vec_local = tmat[0];
920                                         float *vtan_local    = tmat[1];
921                                         float *utan_local    = tmat[2];
922
923                                         /* use tangents */
924                                         BLI_assert(use_tangents == true);
925
926                                         /* rot_vec */
927                                         copy_v3_v3(rot_vec_local, rot_vec);
928                                         mul_qt_v3(q_imat, rot_vec_local);
929
930                                         /* vtan_local */
931                                         copy_v3_v3(vtan_local, vtan);  /* flips, cant use */
932                                         mul_qt_v3(q_imat, vtan_local);
933
934                                         /* ensure orthogonal matrix (rot_vec aligned) */
935                                         cross_v3_v3v3(utan_local, vtan_local, rot_vec_local);
936                                         cross_v3_v3v3(vtan_local, utan_local, rot_vec_local);
937
938                                         /* note: no need to normalize */
939                                         mat3_to_quat(q2, tmat);
940                                 }
941
942                                 /* randomize rotation quat */
943                                 if (part->randrotfac != 0.0f) {
944                                         mul_qt_qtqt(r_rot, r_rot, q_imat);
945                                         interp_qt_qtqt(rot, q2, r_rot, part->randrotfac);
946                                 }
947                                 else {
948                                         copy_qt_qt(rot, q2);
949                                 }
950
951                                 mul_qt_qtqt(rot, q_obmat, rot);
952                         }
953
954                         /* rotation phase */
955                         phasefac = part->phasefac;
956                         if (part->randphasefac != 0.0f)
957                                 phasefac += part->randphasefac * psys_frand(psys, p + 20);
958                         axis_angle_to_quat( q_phase,x_vec, phasefac*(float)M_PI);
959
960                         /* combine base rotation & phase */
961                         mul_qt_qtqt(state->rot, rot, q_phase);
962                 }
963
964                 /* -angular velocity                                    */
965
966                 zero_v3(state->ave);
967
968                 if (part->avemode) {
969                         if (part->avemode == PART_AVE_RAND)
970                                 copy_v3_v3(state->ave, r_ave);
971                         else
972                                 get_angular_velocity_vector(part->avemode, state, state->ave);
973
974                         normalize_v3(state->ave);
975                         mul_v3_fl(state->ave, part->avefac);
976                 }
977         }
978 }
979
980 /* recursively evaluate emitter parent anim at cfra */
981 static void evaluate_emitter_anim(struct Depsgraph *depsgraph, Scene *scene, Object *ob, float cfra)
982 {
983         if (ob->parent)
984                 evaluate_emitter_anim(depsgraph, scene, ob->parent, cfra);
985
986         BKE_object_where_is_calc_time(depsgraph, scene, ob, cfra);
987 }
988
989 /* sets particle to the emitter surface with initial velocity & rotation */
990 void reset_particle(ParticleSimulationData *sim, ParticleData *pa, float dtime, float cfra)
991 {
992         ParticleSystem *psys = sim->psys;
993         ParticleSettings *part;
994         ParticleTexture ptex;
995         int p = pa - psys->particles;
996         part=psys->part;
997
998         /* get precise emitter matrix if particle is born */
999         if (part->type != PART_HAIR && dtime > 0.f && pa->time < cfra && pa->time >= sim->psys->cfra) {
1000                 evaluate_emitter_anim(sim->depsgraph, sim->scene, sim->ob, pa->time);
1001
1002                 psys->flag |= PSYS_OB_ANIM_RESTORE;
1003         }
1004
1005         psys_get_birth_coords(sim, pa, &pa->state, dtime, cfra);
1006
1007         /* Initialize particle settings which depends on texture.
1008          *
1009          * We could only do it now because we'll need to know coordinate
1010          * before sampling the texture.
1011          */
1012         initialize_particle_texture(sim, pa, p);
1013
1014         if (part->phystype==PART_PHYS_BOIDS && pa->boid) {
1015                 BoidParticle *bpa = pa->boid;
1016
1017                 /* and gravity in r_ve */
1018                 bpa->gravity[0] = bpa->gravity[1] = 0.0f;
1019                 bpa->gravity[2] = -1.0f;
1020                 if ((sim->scene->physics_settings.flag & PHYS_GLOBAL_GRAVITY) &&
1021                     (sim->scene->physics_settings.gravity[2] != 0.0f))
1022                 {
1023                         bpa->gravity[2] = sim->scene->physics_settings.gravity[2];
1024                 }
1025
1026                 bpa->data.health = part->boids->health;
1027                 bpa->data.mode = eBoidMode_InAir;
1028                 bpa->data.state_id = ((BoidState*)part->boids->states.first)->id;
1029                 bpa->data.acc[0]=bpa->data.acc[1]=bpa->data.acc[2]=0.0f;
1030         }
1031
1032         if (part->type == PART_HAIR) {
1033                 pa->lifetime = 100.0f;
1034         }
1035         else {
1036                 /* initialize the lifetime, in case the texture coordinates
1037                  * are from Particles/Strands, which would cause undefined values
1038                  */
1039                 pa->lifetime = part->lifetime * (1.0f - part->randlife * psys_frand(psys, p + 21));
1040                 pa->dietime = pa->time + pa->lifetime;
1041
1042                 /* get possible textural influence */
1043                 psys_get_texture(sim, pa, &ptex, PAMAP_LIFE, cfra);
1044
1045                 pa->lifetime = part->lifetime * ptex.life;
1046
1047                 if (part->randlife != 0.0f)
1048                         pa->lifetime *= 1.0f - part->randlife * psys_frand(psys, p + 21);
1049         }
1050
1051         pa->dietime = pa->time + pa->lifetime;
1052
1053         if ((sim->psys->pointcache) &&
1054             (sim->psys->pointcache->flag & PTCACHE_BAKED) &&
1055             (sim->psys->pointcache->mem_cache.first))
1056         {
1057                 float dietime = psys_get_dietime_from_cache(sim->psys->pointcache, p);
1058                 pa->dietime = MIN2(pa->dietime, dietime);
1059         }
1060
1061         if (pa->time > cfra)
1062                 pa->alive = PARS_UNBORN;
1063         else if (pa->dietime <= cfra)
1064                 pa->alive = PARS_DEAD;
1065         else
1066                 pa->alive = PARS_ALIVE;
1067
1068         pa->state.time = cfra;
1069 }
1070 static void reset_all_particles(ParticleSimulationData *sim, float dtime, float cfra, int from)
1071 {
1072         ParticleData *pa;
1073         int p, totpart=sim->psys->totpart;
1074
1075         for (p=from, pa=sim->psys->particles+from; p<totpart; p++, pa++)
1076                 reset_particle(sim, pa, dtime, cfra);
1077 }
1078 /************************************************/
1079 /*                      Particle targets                                        */
1080 /************************************************/
1081 ParticleSystem *psys_get_target_system(Object *ob, ParticleTarget *pt)
1082 {
1083         ParticleSystem *psys = NULL;
1084
1085         if (pt->ob == NULL || pt->ob == ob)
1086                 psys = BLI_findlink(&ob->particlesystem, pt->psys-1);
1087         else
1088                 psys = BLI_findlink(&pt->ob->particlesystem, pt->psys-1);
1089
1090         if (psys)
1091                 pt->flag |= PTARGET_VALID;
1092         else
1093                 pt->flag &= ~PTARGET_VALID;
1094
1095         return psys;
1096 }
1097 /************************************************/
1098 /*                      Keyed particles                                         */
1099 /************************************************/
1100 /* Counts valid keyed targets */
1101 void psys_count_keyed_targets(ParticleSimulationData *sim)
1102 {
1103         ParticleSystem *psys = sim->psys, *kpsys;
1104         ParticleTarget *pt = psys->targets.first;
1105         int keys_valid = 1;
1106         psys->totkeyed = 0;
1107
1108         for (; pt; pt=pt->next) {
1109                 kpsys = psys_get_target_system(sim->ob, pt);
1110
1111                 if (kpsys && kpsys->totpart) {
1112                         psys->totkeyed += keys_valid;
1113                         if (psys->flag & PSYS_KEYED_TIMING && pt->duration != 0.0f)
1114                                 psys->totkeyed += 1;
1115                 }
1116                 else {
1117                         keys_valid = 0;
1118                 }
1119         }
1120
1121         psys->totkeyed *= psys->flag & PSYS_KEYED_TIMING ? 1 : psys->part->keyed_loops;
1122 }
1123
1124 static void set_keyed_keys(ParticleSimulationData *sim)
1125 {
1126         ParticleSystem *psys = sim->psys;
1127         ParticleSimulationData ksim= {0};
1128         ParticleTarget *pt;
1129         PARTICLE_P;
1130         ParticleKey *key;
1131         int totpart = psys->totpart, k, totkeys = psys->totkeyed;
1132         int keyed_flag = 0;
1133
1134         ksim.depsgraph = sim->depsgraph;
1135         ksim.scene = sim->scene;
1136
1137         /* no proper targets so let's clear and bail out */
1138         if (psys->totkeyed==0) {
1139                 free_keyed_keys(psys);
1140                 psys->flag &= ~PSYS_KEYED;
1141                 return;
1142         }
1143
1144         if (totpart && psys->particles->totkey != totkeys) {
1145                 free_keyed_keys(psys);
1146
1147                 key = MEM_callocN(totpart*totkeys*sizeof(ParticleKey), "Keyed keys");
1148
1149                 LOOP_PARTICLES {
1150                         pa->keys = key;
1151                         pa->totkey = totkeys;
1152                         key += totkeys;
1153                 }
1154         }
1155
1156         psys->flag &= ~PSYS_KEYED;
1157
1158
1159         pt = psys->targets.first;
1160         for (k=0; k<totkeys; k++) {
1161                 ksim.ob = pt->ob ? pt->ob : sim->ob;
1162                 ksim.psys = BLI_findlink(&ksim.ob->particlesystem, pt->psys - 1);
1163                 keyed_flag = (ksim.psys->flag & PSYS_KEYED);
1164                 ksim.psys->flag &= ~PSYS_KEYED;
1165
1166                 LOOP_PARTICLES {
1167                         key = pa->keys + k;
1168                         key->time = -1.0; /* use current time */
1169
1170                         psys_get_particle_state(&ksim, p%ksim.psys->totpart, key, 1);
1171
1172                         if (psys->flag & PSYS_KEYED_TIMING) {
1173                                 key->time = pa->time + pt->time;
1174                                 if (pt->duration != 0.0f && k+1 < totkeys) {
1175                                         copy_particle_key(key+1, key, 1);
1176                                         (key+1)->time = pa->time + pt->time + pt->duration;
1177                                 }
1178                         }
1179                         else if (totkeys > 1)
1180                                 key->time = pa->time + (float)k / (float)(totkeys - 1) * pa->lifetime;
1181                         else
1182                                 key->time = pa->time;
1183                 }
1184
1185                 if (psys->flag & PSYS_KEYED_TIMING && pt->duration != 0.0f)
1186                         k++;
1187
1188                 ksim.psys->flag |= keyed_flag;
1189
1190                 pt = (pt->next && pt->next->flag & PTARGET_VALID) ? pt->next : psys->targets.first;
1191         }
1192
1193         psys->flag |= PSYS_KEYED;
1194 }
1195
1196 /************************************************/
1197 /*                      Point Cache                                                     */
1198 /************************************************/
1199 void psys_make_temp_pointcache(Object *ob, ParticleSystem *psys)
1200 {
1201         PointCache *cache = psys->pointcache;
1202
1203         if (cache->flag & PTCACHE_DISK_CACHE && BLI_listbase_is_empty(&cache->mem_cache)) {
1204                 PTCacheID pid;
1205                 BKE_ptcache_id_from_particles(&pid, ob, psys);
1206                 cache->flag &= ~PTCACHE_DISK_CACHE;
1207                 BKE_ptcache_disk_to_mem(&pid);
1208                 cache->flag |= PTCACHE_DISK_CACHE;
1209         }
1210 }
1211 static void psys_clear_temp_pointcache(ParticleSystem *psys)
1212 {
1213         if (psys->pointcache->flag & PTCACHE_DISK_CACHE)
1214                 BKE_ptcache_free_mem(&psys->pointcache->mem_cache);
1215 }
1216 void psys_get_pointcache_start_end(Scene *scene, ParticleSystem *psys, int *sfra, int *efra)
1217 {
1218         ParticleSettings *part = psys->part;
1219
1220         *sfra = max_ii(1, (int)part->sta);
1221         *efra = min_ii((int)(part->end + part->lifetime + 1.0f), max_ii(scene->r.pefra, scene->r.efra));
1222 }
1223
1224 /************************************************/
1225 /*                      Effectors                                                       */
1226 /************************************************/
1227 static void psys_update_particle_bvhtree(ParticleSystem *psys, float cfra)
1228 {
1229         if (psys) {
1230                 PARTICLE_P;
1231                 int totpart = 0;
1232                 bool need_rebuild;
1233
1234                 BLI_rw_mutex_lock(&psys_bvhtree_rwlock, THREAD_LOCK_READ);
1235                 need_rebuild = !psys->bvhtree || psys->bvhtree_frame != cfra;
1236                 BLI_rw_mutex_unlock(&psys_bvhtree_rwlock);
1237
1238                 if (need_rebuild) {
1239                         LOOP_SHOWN_PARTICLES {
1240                                 totpart++;
1241                         }
1242
1243                         BLI_rw_mutex_lock(&psys_bvhtree_rwlock, THREAD_LOCK_WRITE);
1244
1245                         BLI_bvhtree_free(psys->bvhtree);
1246                         psys->bvhtree = BLI_bvhtree_new(totpart, 0.0, 4, 6);
1247
1248                         LOOP_SHOWN_PARTICLES {
1249                                 if (pa->alive == PARS_ALIVE) {
1250                                         if (pa->state.time == cfra)
1251                                                 BLI_bvhtree_insert(psys->bvhtree, p, pa->prev_state.co, 1);
1252                                         else
1253                                                 BLI_bvhtree_insert(psys->bvhtree, p, pa->state.co, 1);
1254                                 }
1255                         }
1256                         BLI_bvhtree_balance(psys->bvhtree);
1257
1258                         psys->bvhtree_frame = cfra;
1259
1260                         BLI_rw_mutex_unlock(&psys_bvhtree_rwlock);
1261                 }
1262         }
1263 }
1264 void psys_update_particle_tree(ParticleSystem *psys, float cfra)
1265 {
1266         if (psys) {
1267                 PARTICLE_P;
1268                 int totpart = 0;
1269
1270                 if (!psys->tree || psys->tree_frame != cfra) {
1271                         LOOP_SHOWN_PARTICLES {
1272                                 totpart++;
1273                         }
1274
1275                         BLI_kdtree_free(psys->tree);
1276                         psys->tree = BLI_kdtree_new(psys->totpart);
1277
1278                         LOOP_SHOWN_PARTICLES {
1279                                 if (pa->alive == PARS_ALIVE) {
1280                                         if (pa->state.time == cfra)
1281                                                 BLI_kdtree_insert(psys->tree, p, pa->prev_state.co);
1282                                         else
1283                                                 BLI_kdtree_insert(psys->tree, p, pa->state.co);
1284                                 }
1285                         }
1286                         BLI_kdtree_balance(psys->tree);
1287
1288                         psys->tree_frame = cfra;
1289                 }
1290         }
1291 }
1292
1293 static void psys_update_effectors(ParticleSimulationData *sim)
1294 {
1295         BKE_effectors_free(sim->psys->effectors);
1296         sim->psys->effectors = BKE_effectors_create(sim->depsgraph,
1297                                                     sim->ob, sim->psys,
1298                                                     sim->psys->part->effector_weights);
1299         precalc_guides(sim, sim->psys->effectors);
1300 }
1301
1302 static void integrate_particle(ParticleSettings *part, ParticleData *pa, float dtime, float *external_acceleration,
1303                                void (*force_func)(void *forcedata, ParticleKey *state, float *force, float *impulse),
1304                                void *forcedata)
1305 {
1306 #define ZERO_F43 {{0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 0.0f}}
1307
1308         ParticleKey states[5];
1309         float force[3], acceleration[3], impulse[3], dx[4][3] = ZERO_F43, dv[4][3] = ZERO_F43, oldpos[3];
1310         float pa_mass= (part->flag & PART_SIZEMASS ? part->mass * pa->size : part->mass);
1311         int i, steps=1;
1312         int integrator = part->integrator;
1313
1314 #undef ZERO_F43
1315
1316         copy_v3_v3(oldpos, pa->state.co);
1317
1318         /* Verlet integration behaves strangely with moving emitters, so do first step with euler. */
1319         if (pa->prev_state.time < 0.f && integrator == PART_INT_VERLET)
1320                 integrator = PART_INT_EULER;
1321
1322         switch (integrator) {
1323                 case PART_INT_EULER:
1324                         steps=1;
1325                         break;
1326                 case PART_INT_MIDPOINT:
1327                         steps=2;
1328                         break;
1329                 case PART_INT_RK4:
1330                         steps=4;
1331                         break;
1332                 case PART_INT_VERLET:
1333                         steps=1;
1334                         break;
1335         }
1336
1337         for (i=0; i<steps; i++) {
1338                 copy_particle_key(states + i, &pa->state, 1);
1339         }
1340
1341         states->time = 0.f;
1342
1343         for (i=0; i<steps; i++) {
1344                 zero_v3(force);
1345                 zero_v3(impulse);
1346
1347                 force_func(forcedata, states+i, force, impulse);
1348
1349                 /* force to acceleration*/
1350                 mul_v3_v3fl(acceleration, force, 1.0f/pa_mass);
1351
1352                 if (external_acceleration)
1353                         add_v3_v3(acceleration, external_acceleration);
1354
1355                 /* calculate next state */
1356                 add_v3_v3(states[i].vel, impulse);
1357
1358                 switch (integrator) {
1359                         case PART_INT_EULER:
1360                                 madd_v3_v3v3fl(pa->state.co, states->co, states->vel, dtime);
1361                                 madd_v3_v3v3fl(pa->state.vel, states->vel, acceleration, dtime);
1362                                 break;
1363                         case PART_INT_MIDPOINT:
1364                                 if (i==0) {
1365                                         madd_v3_v3v3fl(states[1].co, states->co, states->vel, dtime*0.5f);
1366                                         madd_v3_v3v3fl(states[1].vel, states->vel, acceleration, dtime*0.5f);
1367                                         states[1].time = dtime*0.5f;
1368                                         /*fra=sim->psys->cfra+0.5f*dfra;*/
1369                                 }
1370                                 else {
1371                                         madd_v3_v3v3fl(pa->state.co, states->co, states[1].vel, dtime);
1372                                         madd_v3_v3v3fl(pa->state.vel, states->vel, acceleration, dtime);
1373                                 }
1374                                 break;
1375                         case PART_INT_RK4:
1376                                 switch (i) {
1377                                         case 0:
1378                                                 copy_v3_v3(dx[0], states->vel);
1379                                                 mul_v3_fl(dx[0], dtime);
1380                                                 copy_v3_v3(dv[0], acceleration);
1381                                                 mul_v3_fl(dv[0], dtime);
1382
1383                                                 madd_v3_v3v3fl(states[1].co, states->co, dx[0], 0.5f);
1384                                                 madd_v3_v3v3fl(states[1].vel, states->vel, dv[0], 0.5f);
1385                                                 states[1].time = dtime*0.5f;
1386                                                 /*fra=sim->psys->cfra+0.5f*dfra;*/
1387                                                 break;
1388                                         case 1:
1389                                                 madd_v3_v3v3fl(dx[1], states->vel, dv[0], 0.5f);
1390                                                 mul_v3_fl(dx[1], dtime);
1391                                                 copy_v3_v3(dv[1], acceleration);
1392                                                 mul_v3_fl(dv[1], dtime);
1393
1394                                                 madd_v3_v3v3fl(states[2].co, states->co, dx[1], 0.5f);
1395                                                 madd_v3_v3v3fl(states[2].vel, states->vel, dv[1], 0.5f);
1396                                                 states[2].time = dtime*0.5f;
1397                                                 break;
1398                                         case 2:
1399                                                 madd_v3_v3v3fl(dx[2], states->vel, dv[1], 0.5f);
1400                                                 mul_v3_fl(dx[2], dtime);
1401                                                 copy_v3_v3(dv[2], acceleration);
1402                                                 mul_v3_fl(dv[2], dtime);
1403
1404                                                 add_v3_v3v3(states[3].co, states->co, dx[2]);
1405                                                 add_v3_v3v3(states[3].vel, states->vel, dv[2]);
1406                                                 states[3].time = dtime;
1407                                                 /*fra=cfra;*/
1408                                                 break;
1409                                         case 3:
1410                                                 add_v3_v3v3(dx[3], states->vel, dv[2]);
1411                                                 mul_v3_fl(dx[3], dtime);
1412                                                 copy_v3_v3(dv[3], acceleration);
1413                                                 mul_v3_fl(dv[3], dtime);
1414
1415                                                 madd_v3_v3v3fl(pa->state.co, states->co, dx[0], 1.0f/6.0f);
1416                                                 madd_v3_v3fl(pa->state.co, dx[1], 1.0f/3.0f);
1417                                                 madd_v3_v3fl(pa->state.co, dx[2], 1.0f/3.0f);
1418                                                 madd_v3_v3fl(pa->state.co, dx[3], 1.0f/6.0f);
1419
1420                                                 madd_v3_v3v3fl(pa->state.vel, states->vel, dv[0], 1.0f/6.0f);
1421                                                 madd_v3_v3fl(pa->state.vel, dv[1], 1.0f/3.0f);
1422                                                 madd_v3_v3fl(pa->state.vel, dv[2], 1.0f/3.0f);
1423                                                 madd_v3_v3fl(pa->state.vel, dv[3], 1.0f/6.0f);
1424                                 }
1425                                 break;
1426                         case PART_INT_VERLET:   /* Verlet integration */
1427                                 madd_v3_v3v3fl(pa->state.vel, pa->prev_state.vel, acceleration, dtime);
1428                                 madd_v3_v3v3fl(pa->state.co, pa->prev_state.co, pa->state.vel, dtime);
1429
1430                                 sub_v3_v3v3(pa->state.vel, pa->state.co, oldpos);
1431                                 mul_v3_fl(pa->state.vel, 1.0f/dtime);
1432                                 break;
1433                 }
1434         }
1435 }
1436
1437 /*********************************************************************************************************
1438  *                    SPH fluid physics
1439  *
1440  * In theory, there could be unlimited implementation of SPH simulators
1441  *
1442  * This code uses in some parts adapted algorithms from the pseudo code as outlined in the Research paper:
1443  *
1444  * Titled: Particle-based Viscoelastic Fluid Simulation.
1445  * Authors: Simon Clavet, Philippe Beaudoin and Pierre Poulin
1446  * Website: http://www.iro.umontreal.ca/labs/infographie/papers/Clavet-2005-PVFS/
1447  *
1448  * Presented at Siggraph, (2005)
1449  *
1450  * ********************************************************************************************************/
1451 #define PSYS_FLUID_SPRINGS_INITIAL_SIZE 256
1452 static ParticleSpring *sph_spring_add(ParticleSystem *psys, ParticleSpring *spring)
1453 {
1454         /* Are more refs required? */
1455         if (psys->alloc_fluidsprings == 0 || psys->fluid_springs == NULL) {
1456                 psys->alloc_fluidsprings = PSYS_FLUID_SPRINGS_INITIAL_SIZE;
1457                 psys->fluid_springs = (ParticleSpring*)MEM_callocN(psys->alloc_fluidsprings * sizeof(ParticleSpring), "Particle Fluid Springs");
1458         }
1459         else if (psys->tot_fluidsprings == psys->alloc_fluidsprings) {
1460                 /* Double the number of refs allocated */
1461                 psys->alloc_fluidsprings *= 2;
1462                 psys->fluid_springs = (ParticleSpring*)MEM_reallocN(psys->fluid_springs, psys->alloc_fluidsprings * sizeof(ParticleSpring));
1463         }
1464
1465         memcpy(psys->fluid_springs + psys->tot_fluidsprings, spring, sizeof(ParticleSpring));
1466         psys->tot_fluidsprings++;
1467
1468         return psys->fluid_springs + psys->tot_fluidsprings - 1;
1469 }
1470 static void sph_spring_delete(ParticleSystem *psys, int j)
1471 {
1472         if (j != psys->tot_fluidsprings - 1)
1473                 psys->fluid_springs[j] = psys->fluid_springs[psys->tot_fluidsprings - 1];
1474
1475         psys->tot_fluidsprings--;
1476
1477         if (psys->tot_fluidsprings < psys->alloc_fluidsprings/2 && psys->alloc_fluidsprings > PSYS_FLUID_SPRINGS_INITIAL_SIZE) {
1478                 psys->alloc_fluidsprings /= 2;
1479                 psys->fluid_springs = (ParticleSpring*)MEM_reallocN(psys->fluid_springs,  psys->alloc_fluidsprings * sizeof(ParticleSpring));
1480         }
1481 }
1482 static void sph_springs_modify(ParticleSystem *psys, float dtime)
1483 {
1484         SPHFluidSettings *fluid = psys->part->fluid;
1485         ParticleData *pa1, *pa2;
1486         ParticleSpring *spring = psys->fluid_springs;
1487
1488         float h, d, Rij[3], rij, Lij;
1489         int i;
1490
1491         float yield_ratio = fluid->yield_ratio;
1492         float plasticity = fluid->plasticity_constant;
1493         /* scale things according to dtime */
1494         float timefix = 25.f * dtime;
1495
1496         if ((fluid->flag & SPH_VISCOELASTIC_SPRINGS)==0 || fluid->spring_k == 0.f)
1497                 return;
1498
1499         /* Loop through the springs */
1500         for (i=0; i<psys->tot_fluidsprings; i++, spring++) {
1501                 pa1 = psys->particles + spring->particle_index[0];
1502                 pa2 = psys->particles + spring->particle_index[1];
1503
1504                 sub_v3_v3v3(Rij, pa2->prev_state.co, pa1->prev_state.co);
1505                 rij = normalize_v3(Rij);
1506
1507                 /* adjust rest length */
1508                 Lij = spring->rest_length;
1509                 d = yield_ratio * timefix * Lij;
1510
1511                 if (rij > Lij + d) // Stretch
1512                         spring->rest_length += plasticity * (rij - Lij - d) * timefix;
1513                 else if (rij < Lij - d) // Compress
1514                         spring->rest_length -= plasticity * (Lij - d - rij) * timefix;
1515
1516                 h = 4.f*pa1->size;
1517
1518                 if (spring->rest_length > h)
1519                         spring->delete_flag = 1;
1520         }
1521
1522         /* Loop through springs backwaqrds - for efficient delete function */
1523         for (i=psys->tot_fluidsprings-1; i >= 0; i--) {
1524                 if (psys->fluid_springs[i].delete_flag)
1525                         sph_spring_delete(psys, i);
1526         }
1527 }
1528 static EdgeHash *sph_springhash_build(ParticleSystem *psys)
1529 {
1530         EdgeHash *springhash = NULL;
1531         ParticleSpring *spring;
1532         int i = 0;
1533
1534         springhash = BLI_edgehash_new_ex(__func__, psys->tot_fluidsprings);
1535
1536         for (i=0, spring=psys->fluid_springs; i<psys->tot_fluidsprings; i++, spring++)
1537                 BLI_edgehash_insert(springhash, spring->particle_index[0], spring->particle_index[1], POINTER_FROM_INT(i+1));
1538
1539         return springhash;
1540 }
1541
1542 #define SPH_NEIGHBORS 512
1543 typedef struct SPHNeighbor {
1544         ParticleSystem *psys;
1545         int index;
1546 } SPHNeighbor;
1547
1548 typedef struct SPHRangeData {
1549         SPHNeighbor neighbors[SPH_NEIGHBORS];
1550         int tot_neighbors;
1551
1552         float* data;
1553
1554         ParticleSystem *npsys;
1555         ParticleData *pa;
1556
1557         float h;
1558         float mass;
1559         float massfac;
1560         int use_size;
1561 } SPHRangeData;
1562
1563 static void sph_evaluate_func(BVHTree *tree, ParticleSystem **psys, float co[3], SPHRangeData *pfr, float interaction_radius, BVHTree_RangeQuery callback)
1564 {
1565         int i;
1566
1567         pfr->tot_neighbors = 0;
1568
1569         for (i=0; i < 10 && psys[i]; i++) {
1570                 pfr->npsys    = psys[i];
1571                 pfr->massfac  = psys[i]->part->mass / pfr->mass;
1572                 pfr->use_size = psys[i]->part->flag & PART_SIZEMASS;
1573
1574                 if (tree) {
1575                         BLI_bvhtree_range_query(tree, co, interaction_radius, callback, pfr);
1576                         break;
1577                 }
1578                 else {
1579                         BLI_rw_mutex_lock(&psys_bvhtree_rwlock, THREAD_LOCK_READ);
1580
1581                         BLI_bvhtree_range_query(psys[i]->bvhtree, co, interaction_radius, callback, pfr);
1582
1583                         BLI_rw_mutex_unlock(&psys_bvhtree_rwlock);
1584                 }
1585         }
1586 }
1587 static void sph_density_accum_cb(void *userdata, int index, const float co[3], float squared_dist)
1588 {
1589         SPHRangeData *pfr = (SPHRangeData *)userdata;
1590         ParticleData *npa = pfr->npsys->particles + index;
1591         float q;
1592         float dist;
1593
1594         UNUSED_VARS(co);
1595
1596         if (npa == pfr->pa || squared_dist < FLT_EPSILON)
1597                 return;
1598
1599         /* Ugh! One particle has too many neighbors! If some aren't taken into
1600          * account, the forces will be biased by the tree search order. This
1601          * effectively adds energy to the system, and results in a churning motion.
1602          * But, we have to stop somewhere, and it's not the end of the world.
1603          * - jahka and z0r
1604          */
1605         if (pfr->tot_neighbors >= SPH_NEIGHBORS)
1606                 return;
1607
1608         pfr->neighbors[pfr->tot_neighbors].index = index;
1609         pfr->neighbors[pfr->tot_neighbors].psys = pfr->npsys;
1610         pfr->tot_neighbors++;
1611
1612         dist = sqrtf(squared_dist);
1613         q = (1.f - dist/pfr->h) * pfr->massfac;
1614
1615         if (pfr->use_size)
1616                 q *= npa->size;
1617
1618         pfr->data[0] += q*q;
1619         pfr->data[1] += q*q*q;
1620 }
1621
1622 /*
1623  * Find the Courant number for an SPH particle (used for adaptive time step).
1624  */
1625 static void sph_particle_courant(SPHData *sphdata, SPHRangeData *pfr)
1626 {
1627         ParticleData *pa, *npa;
1628         int i;
1629         float flow[3], offset[3], dist;
1630
1631         zero_v3(flow);
1632
1633         dist = 0.0f;
1634         if (pfr->tot_neighbors > 0) {
1635                 pa = pfr->pa;
1636                 for (i=0; i < pfr->tot_neighbors; i++) {
1637                         npa = pfr->neighbors[i].psys->particles + pfr->neighbors[i].index;
1638                         sub_v3_v3v3(offset, pa->prev_state.co, npa->prev_state.co);
1639                         dist += len_v3(offset);
1640                         add_v3_v3(flow, npa->prev_state.vel);
1641                 }
1642                 dist += sphdata->psys[0]->part->fluid->radius; // TODO: remove this? - z0r
1643                 sphdata->element_size = dist / pfr->tot_neighbors;
1644                 mul_v3_v3fl(sphdata->flow, flow, 1.0f / pfr->tot_neighbors);
1645         }
1646         else {
1647                 sphdata->element_size = FLT_MAX;
1648                 copy_v3_v3(sphdata->flow, flow);
1649         }
1650 }
1651 static void sph_force_cb(void *sphdata_v, ParticleKey *state, float *force, float *UNUSED(impulse))
1652 {
1653         SPHData *sphdata = (SPHData *)sphdata_v;
1654         ParticleSystem **psys = sphdata->psys;
1655         ParticleData *pa = sphdata->pa;
1656         SPHFluidSettings *fluid = psys[0]->part->fluid;
1657         ParticleSpring *spring = NULL;
1658         SPHRangeData pfr;
1659         SPHNeighbor *pfn;
1660         float *gravity = sphdata->gravity;
1661         EdgeHash *springhash = sphdata->eh;
1662
1663         float q, u, rij, dv[3];
1664         float pressure, near_pressure;
1665
1666         float visc = fluid->viscosity_omega;
1667         float stiff_visc = fluid->viscosity_beta * (fluid->flag & SPH_FAC_VISCOSITY ? fluid->viscosity_omega : 1.f);
1668
1669         float inv_mass = 1.0f / sphdata->mass;
1670         float spring_constant = fluid->spring_k;
1671
1672         /* 4.0 seems to be a pretty good value */
1673         float interaction_radius = fluid->radius * (fluid->flag & SPH_FAC_RADIUS ? 4.0f * pa->size : 1.0f);
1674         float h = interaction_radius * sphdata->hfac;
1675         /* 4.77 is an experimentally determined density factor */
1676         float rest_density = fluid->rest_density * (fluid->flag & SPH_FAC_DENSITY ? 4.77f : 1.f);
1677         float rest_length = fluid->rest_length * (fluid->flag & SPH_FAC_REST_LENGTH ? 2.588f * pa->size : 1.f);
1678
1679         float stiffness = fluid->stiffness_k;
1680         float stiffness_near_fac = fluid->stiffness_knear * (fluid->flag & SPH_FAC_REPULSION ? fluid->stiffness_k : 1.f);
1681
1682         ParticleData *npa;
1683         float vec[3];
1684         float vel[3];
1685         float co[3];
1686         float data[2];
1687         float density, near_density;
1688
1689         int i, spring_index, index = pa - psys[0]->particles;
1690
1691         data[0] = data[1] = 0;
1692         pfr.data = data;
1693         pfr.h = h;
1694         pfr.pa = pa;
1695         pfr.mass = sphdata->mass;
1696
1697         sph_evaluate_func( NULL, psys, state->co, &pfr, interaction_radius, sph_density_accum_cb);
1698
1699         density = data[0];
1700         near_density = data[1];
1701
1702         pressure =  stiffness * (density - rest_density);
1703         near_pressure = stiffness_near_fac * near_density;
1704
1705         pfn = pfr.neighbors;
1706         for (i=0; i<pfr.tot_neighbors; i++, pfn++) {
1707                 npa = pfn->psys->particles + pfn->index;
1708
1709                 madd_v3_v3v3fl(co, npa->prev_state.co, npa->prev_state.vel, state->time);
1710
1711                 sub_v3_v3v3(vec, co, state->co);
1712                 rij = normalize_v3(vec);
1713
1714                 q = (1.f - rij/h) * pfn->psys->part->mass * inv_mass;
1715
1716                 if (pfn->psys->part->flag & PART_SIZEMASS)
1717                         q *= npa->size;
1718
1719                 copy_v3_v3(vel, npa->prev_state.vel);
1720
1721                 /* Double Density Relaxation */
1722                 madd_v3_v3fl(force, vec, -(pressure + near_pressure*q)*q);
1723
1724                 /* Viscosity */
1725                 if (visc > 0.f  || stiff_visc > 0.f) {
1726                         sub_v3_v3v3(dv, vel, state->vel);
1727                         u = dot_v3v3(vec, dv);
1728
1729                         if (u < 0.f && visc > 0.f)
1730                                 madd_v3_v3fl(force, vec, 0.5f * q * visc * u );
1731
1732                         if (u > 0.f && stiff_visc > 0.f)
1733                                 madd_v3_v3fl(force, vec, 0.5f * q * stiff_visc * u );
1734                 }
1735
1736                 if (spring_constant > 0.f) {
1737                         /* Viscoelastic spring force */
1738                         if (pfn->psys == psys[0] && fluid->flag & SPH_VISCOELASTIC_SPRINGS && springhash) {
1739                                 /* BLI_edgehash_lookup appears to be thread-safe. - z0r */
1740                                 spring_index = POINTER_AS_INT(BLI_edgehash_lookup(springhash, index, pfn->index));
1741
1742                                 if (spring_index) {
1743                                         spring = psys[0]->fluid_springs + spring_index - 1;
1744
1745                                         madd_v3_v3fl(force, vec, -10.f * spring_constant * (1.f - rij/h) * (spring->rest_length - rij));
1746                                 }
1747                                 else if (fluid->spring_frames == 0 || (pa->prev_state.time-pa->time) <= fluid->spring_frames) {
1748                                         ParticleSpring temp_spring;
1749                                         temp_spring.particle_index[0] = index;
1750                                         temp_spring.particle_index[1] = pfn->index;
1751                                         temp_spring.rest_length = (fluid->flag & SPH_CURRENT_REST_LENGTH) ? rij : rest_length;
1752                                         temp_spring.delete_flag = 0;
1753
1754                                         /* sph_spring_add is not thread-safe. - z0r */
1755                                         sph_spring_add(psys[0], &temp_spring);
1756                                 }
1757                         }
1758                         else {/* PART_SPRING_HOOKES - Hooke's spring force */
1759                                 madd_v3_v3fl(force, vec, -10.f * spring_constant * (1.f - rij/h) * (rest_length - rij));
1760                         }
1761                 }
1762         }
1763
1764         /* Artificial buoyancy force in negative gravity direction  */
1765         if (fluid->buoyancy > 0.f && gravity)
1766                 madd_v3_v3fl(force, gravity, fluid->buoyancy * (density-rest_density));
1767
1768         if (sphdata->pass == 0 && psys[0]->part->time_flag & PART_TIME_AUTOSF)
1769                 sph_particle_courant(sphdata, &pfr);
1770         sphdata->pass++;
1771 }
1772
1773 static void sphclassical_density_accum_cb(void *userdata, int index, const float co[3], float UNUSED(squared_dist))
1774 {
1775         SPHRangeData *pfr = (SPHRangeData *)userdata;
1776         ParticleData *npa = pfr->npsys->particles + index;
1777         float q;
1778         float qfac = 21.0f / (256.f * (float)M_PI);
1779         float rij, rij_h;
1780         float vec[3];
1781
1782         /* Exclude particles that are more than 2h away. Can't use squared_dist here
1783          * because it is not accurate enough. Use current state, i.e. the output of
1784          * basic_integrate() - z0r */
1785         sub_v3_v3v3(vec, npa->state.co, co);
1786         rij = len_v3(vec);
1787         rij_h = rij / pfr->h;
1788         if (rij_h > 2.0f)
1789                 return;
1790
1791         /* Smoothing factor. Utilise the Wendland kernel. gnuplot:
1792          *     q1(x) = (2.0 - x)**4 * ( 1.0 + 2.0 * x)
1793          *     plot [0:2] q1(x) */
1794         q  = qfac / pow3f(pfr->h) * pow4f(2.0f - rij_h) * ( 1.0f + 2.0f * rij_h);
1795         q *= pfr->npsys->part->mass;
1796
1797         if (pfr->use_size)
1798                 q *= pfr->pa->size;
1799
1800         pfr->data[0] += q;
1801         pfr->data[1] += q / npa->sphdensity;
1802 }
1803
1804 static void sphclassical_neighbour_accum_cb(void *userdata, int index, const float co[3], float UNUSED(squared_dist))
1805 {
1806         SPHRangeData *pfr = (SPHRangeData *)userdata;
1807         ParticleData *npa = pfr->npsys->particles + index;
1808         float rij, rij_h;
1809         float vec[3];
1810
1811         if (pfr->tot_neighbors >= SPH_NEIGHBORS)
1812                 return;
1813
1814         /* Exclude particles that are more than 2h away. Can't use squared_dist here
1815          * because it is not accurate enough. Use current state, i.e. the output of
1816          * basic_integrate() - z0r */
1817         sub_v3_v3v3(vec, npa->state.co, co);
1818         rij = len_v3(vec);
1819         rij_h = rij / pfr->h;
1820         if (rij_h > 2.0f)
1821                 return;
1822
1823         pfr->neighbors[pfr->tot_neighbors].index = index;
1824         pfr->neighbors[pfr->tot_neighbors].psys = pfr->npsys;
1825         pfr->tot_neighbors++;
1826 }
1827 static void sphclassical_force_cb(void *sphdata_v, ParticleKey *state, float *force, float *UNUSED(impulse))
1828 {
1829         SPHData *sphdata = (SPHData *)sphdata_v;
1830         ParticleSystem **psys = sphdata->psys;
1831         ParticleData *pa = sphdata->pa;
1832         SPHFluidSettings *fluid = psys[0]->part->fluid;
1833         SPHRangeData pfr;
1834         SPHNeighbor *pfn;
1835         float *gravity = sphdata->gravity;
1836
1837         float dq, u, rij, dv[3];
1838         float pressure, npressure;
1839
1840         float visc = fluid->viscosity_omega;
1841
1842         float interaction_radius;
1843         float h, hinv;
1844         /* 4.77 is an experimentally determined density factor */
1845         float rest_density = fluid->rest_density * (fluid->flag & SPH_FAC_DENSITY ? 4.77f : 1.0f);
1846
1847         // Use speed of sound squared
1848         float stiffness = pow2f(fluid->stiffness_k);
1849
1850         ParticleData *npa;
1851         float vec[3];
1852         float co[3];
1853         float pressureTerm;
1854
1855         int i;
1856
1857         float qfac2 = 42.0f / (256.0f * (float)M_PI);
1858         float rij_h;
1859
1860         /* 4.0 here is to be consistent with previous formulation/interface */
1861         interaction_radius = fluid->radius * (fluid->flag & SPH_FAC_RADIUS ? 4.0f * pa->size : 1.0f);
1862         h = interaction_radius * sphdata->hfac;
1863         hinv = 1.0f / h;
1864
1865         pfr.h = h;
1866         pfr.pa = pa;
1867
1868         sph_evaluate_func(NULL, psys, state->co, &pfr, interaction_radius, sphclassical_neighbour_accum_cb);
1869         pressure =  stiffness * (pow7f(pa->sphdensity / rest_density) - 1.0f);
1870
1871         /* multiply by mass so that we return a force, not accel */
1872         qfac2 *= sphdata->mass / pow3f(pfr.h);
1873
1874         pfn = pfr.neighbors;
1875         for (i = 0; i < pfr.tot_neighbors; i++, pfn++) {
1876                 npa = pfn->psys->particles + pfn->index;
1877                 if (npa == pa) {
1878                         /* we do not contribute to ourselves */
1879                         continue;
1880                 }
1881
1882                 /* Find vector to neighbor. Exclude particles that are more than 2h
1883                  * away. Can't use current state here because it may have changed on
1884                  * another thread - so do own mini integration. Unlike basic_integrate,
1885                  * SPH integration depends on neighboring particles. - z0r */
1886                 madd_v3_v3v3fl(co, npa->prev_state.co, npa->prev_state.vel, state->time);
1887                 sub_v3_v3v3(vec, co, state->co);
1888                 rij = normalize_v3(vec);
1889                 rij_h = rij / pfr.h;
1890                 if (rij_h > 2.0f)
1891                         continue;
1892
1893                 npressure = stiffness * (pow7f(npa->sphdensity / rest_density) - 1.0f);
1894
1895                 /* First derivative of smoothing factor. Utilise the Wendland kernel.
1896                  * gnuplot:
1897                  *     q2(x) = 2.0 * (2.0 - x)**4 - 4.0 * (2.0 - x)**3 * (1.0 + 2.0 * x)
1898                  *     plot [0:2] q2(x)
1899                  * Particles > 2h away are excluded above. */
1900                 dq = qfac2 * (2.0f * pow4f(2.0f - rij_h) - 4.0f * pow3f(2.0f - rij_h) * (1.0f + 2.0f * rij_h)  );
1901
1902                 if (pfn->psys->part->flag & PART_SIZEMASS)
1903                         dq *= npa->size;
1904
1905                 pressureTerm = pressure / pow2f(pa->sphdensity) + npressure / pow2f(npa->sphdensity);
1906
1907                 /* Note that 'minus' is removed, because vec = vecBA, not vecAB.
1908                  * This applies to the viscosity calculation below, too. */
1909                 madd_v3_v3fl(force, vec, pressureTerm * dq);
1910
1911                 /* Viscosity */
1912                 if (visc > 0.0f) {
1913                         sub_v3_v3v3(dv, npa->prev_state.vel, pa->prev_state.vel);
1914                         u = dot_v3v3(vec, dv);
1915                         /* Apply parameters */
1916                         u *= -dq * hinv * visc / (0.5f * npa->sphdensity + 0.5f * pa->sphdensity);
1917                         madd_v3_v3fl(force, vec, u);
1918                 }
1919         }
1920
1921         /* Artificial buoyancy force in negative gravity direction  */
1922         if (fluid->buoyancy > 0.f && gravity)
1923                 madd_v3_v3fl(force, gravity, fluid->buoyancy * (pa->sphdensity - rest_density));
1924
1925         if (sphdata->pass == 0 && psys[0]->part->time_flag & PART_TIME_AUTOSF)
1926                 sph_particle_courant(sphdata, &pfr);
1927         sphdata->pass++;
1928 }
1929
1930 static void sphclassical_calc_dens(ParticleData *pa, float UNUSED(dfra), SPHData *sphdata)
1931 {
1932         ParticleSystem **psys = sphdata->psys;
1933         SPHFluidSettings *fluid = psys[0]->part->fluid;
1934         /* 4.0 seems to be a pretty good value */
1935         float interaction_radius  = fluid->radius * (fluid->flag & SPH_FAC_RADIUS ? 4.0f * psys[0]->part->size : 1.0f);
1936         SPHRangeData pfr;
1937         float data[2];
1938
1939         data[0] = 0;
1940         data[1] = 0;
1941         pfr.data = data;
1942         pfr.h = interaction_radius * sphdata->hfac;
1943         pfr.pa = pa;
1944         pfr.mass = sphdata->mass;
1945
1946         sph_evaluate_func( NULL, psys, pa->state.co, &pfr, interaction_radius, sphclassical_density_accum_cb);
1947         pa->sphdensity = min_ff(max_ff(data[0], fluid->rest_density * 0.9f), fluid->rest_density * 1.1f);
1948 }
1949
1950 void psys_sph_init(ParticleSimulationData *sim, SPHData *sphdata)
1951 {
1952         ParticleTarget *pt;
1953         int i;
1954
1955         // Add other coupled particle systems.
1956         sphdata->psys[0] = sim->psys;
1957         for (i=1, pt=sim->psys->targets.first; i<10; i++, pt=(pt?pt->next:NULL))
1958                 sphdata->psys[i] = pt ? psys_get_target_system(sim->ob, pt) : NULL;
1959
1960         if (psys_uses_gravity(sim))
1961                 sphdata->gravity = sim->scene->physics_settings.gravity;
1962         else
1963                 sphdata->gravity = NULL;
1964         sphdata->eh = sph_springhash_build(sim->psys);
1965
1966         // These per-particle values should be overridden later, but just for
1967         // completeness we give them default values now.
1968         sphdata->pa = NULL;
1969         sphdata->mass = 1.0f;
1970
1971         if (sim->psys->part->fluid->solver == SPH_SOLVER_DDR) {
1972                 sphdata->force_cb = sph_force_cb;
1973                 sphdata->density_cb = sph_density_accum_cb;
1974                 sphdata->hfac = 1.0f;
1975         }
1976         else {
1977                 /* SPH_SOLVER_CLASSICAL */
1978                 sphdata->force_cb = sphclassical_force_cb;
1979                 sphdata->density_cb = sphclassical_density_accum_cb;
1980                 sphdata->hfac = 0.5f;
1981         }
1982
1983 }
1984
1985 void psys_sph_finalise(SPHData *sphdata)
1986 {
1987         if (sphdata->eh) {
1988                 BLI_edgehash_free(sphdata->eh, NULL);
1989                 sphdata->eh = NULL;
1990         }
1991 }
1992 /* Sample the density field at a point in space. */
1993 void psys_sph_density(BVHTree *tree, SPHData *sphdata, float co[3], float vars[2])
1994 {
1995         ParticleSystem **psys = sphdata->psys;
1996         SPHFluidSettings *fluid = psys[0]->part->fluid;
1997         /* 4.0 seems to be a pretty good value */
1998         float interaction_radius  = fluid->radius * (fluid->flag & SPH_FAC_RADIUS ? 4.0f * psys[0]->part->size : 1.0f);
1999         SPHRangeData pfr;
2000         float density[2];
2001
2002         density[0] = density[1] = 0.0f;
2003         pfr.data = density;
2004         pfr.h = interaction_radius * sphdata->hfac;
2005         pfr.mass = sphdata->mass;
2006
2007         sph_evaluate_func(tree, psys, co, &pfr, interaction_radius, sphdata->density_cb);
2008
2009         vars[0] = pfr.data[0];
2010         vars[1] = pfr.data[1];
2011 }
2012
2013 static void sph_integrate(ParticleSimulationData *sim, ParticleData *pa, float dfra, SPHData *sphdata)
2014 {
2015         ParticleSettings *part = sim->psys->part;
2016         // float timestep = psys_get_timestep(sim); // UNUSED
2017         float pa_mass = part->mass * (part->flag & PART_SIZEMASS ? pa->size : 1.f);
2018         float dtime = dfra*psys_get_timestep(sim);
2019         // int steps = 1; // UNUSED
2020         float effector_acceleration[3];
2021
2022         sphdata->pa = pa;
2023         sphdata->mass = pa_mass;
2024         sphdata->pass = 0;
2025         //sphdata.element_size and sphdata.flow are set in the callback.
2026
2027         /* restore previous state and treat gravity & effectors as external acceleration*/
2028         sub_v3_v3v3(effector_acceleration, pa->state.vel, pa->prev_state.vel);
2029         mul_v3_fl(effector_acceleration, 1.f/dtime);
2030
2031         copy_particle_key(&pa->state, &pa->prev_state, 0);
2032
2033         integrate_particle(part, pa, dtime, effector_acceleration, sphdata->force_cb, sphdata);
2034 }
2035
2036 /************************************************/
2037 /*                      Basic physics                                           */
2038 /************************************************/
2039 typedef struct EfData {
2040         ParticleTexture ptex;
2041         ParticleSimulationData *sim;
2042         ParticleData *pa;
2043 } EfData;
2044 static void basic_force_cb(void *efdata_v, ParticleKey *state, float *force, float *impulse)
2045 {
2046         EfData *efdata = (EfData *)efdata_v;
2047         ParticleSimulationData *sim = efdata->sim;
2048         ParticleSettings *part = sim->psys->part;
2049         ParticleData *pa = efdata->pa;
2050         EffectedPoint epoint;
2051         RNG *rng = sim->rng;
2052
2053         /* add effectors */
2054         pd_point_from_particle(efdata->sim, efdata->pa, state, &epoint);
2055         if (part->type != PART_HAIR || part->effector_weights->flag & EFF_WEIGHT_DO_HAIR)
2056                 BKE_effectors_apply(sim->psys->effectors, sim->colliders, part->effector_weights, &epoint, force, impulse);
2057
2058         mul_v3_fl(force, efdata->ptex.field);
2059         mul_v3_fl(impulse, efdata->ptex.field);
2060
2061         /* calculate air-particle interaction */
2062         if (part->dragfac != 0.0f)
2063                 madd_v3_v3fl(force, state->vel, -part->dragfac * pa->size * pa->size * len_v3(state->vel));
2064
2065         /* brownian force */
2066         if (part->brownfac != 0.0f) {
2067                 force[0] += (BLI_rng_get_float(rng)-0.5f) * part->brownfac;
2068                 force[1] += (BLI_rng_get_float(rng)-0.5f) * part->brownfac;
2069                 force[2] += (BLI_rng_get_float(rng)-0.5f) * part->brownfac;
2070         }
2071
2072         if (part->flag & PART_ROT_DYN && epoint.ave)
2073                 copy_v3_v3(pa->state.ave, epoint.ave);
2074 }
2075 /* gathers all forces that effect particles and calculates a new state for the particle */
2076 static void basic_integrate(ParticleSimulationData *sim, int p, float dfra, float cfra)
2077 {
2078         ParticleSettings *part = sim->psys->part;
2079         ParticleData *pa = sim->psys->particles + p;
2080         ParticleKey tkey;
2081         float dtime=dfra*psys_get_timestep(sim), time;
2082         float *gravity = NULL, gr[3];
2083         EfData efdata;
2084
2085         psys_get_texture(sim, pa, &efdata.ptex, PAMAP_PHYSICS, cfra);
2086
2087         efdata.pa = pa;
2088         efdata.sim = sim;
2089
2090         /* add global acceleration (gravitation) */
2091         if (psys_uses_gravity(sim) &&
2092                 /* normal gravity is too strong for hair so it's disabled by default */
2093                 (part->type != PART_HAIR || part->effector_weights->flag & EFF_WEIGHT_DO_HAIR))
2094         {
2095                 zero_v3(gr);
2096                 madd_v3_v3fl(gr, sim->scene->physics_settings.gravity, part->effector_weights->global_gravity * efdata.ptex.gravity);
2097                 gravity = gr;
2098         }
2099
2100         /* maintain angular velocity */
2101         copy_v3_v3(pa->state.ave, pa->prev_state.ave);
2102
2103         integrate_particle(part, pa, dtime, gravity, basic_force_cb, &efdata);
2104
2105         /* damp affects final velocity */
2106         if (part->dampfac != 0.f)
2107                 mul_v3_fl(pa->state.vel, 1.f - part->dampfac * efdata.ptex.damp * 25.f * dtime);
2108
2109         //copy_v3_v3(pa->state.ave, states->ave);
2110
2111         /* finally we do guides */
2112         time=(cfra-pa->time)/pa->lifetime;
2113         CLAMP(time, 0.0f, 1.0f);
2114
2115         copy_v3_v3(tkey.co,pa->state.co);
2116         copy_v3_v3(tkey.vel,pa->state.vel);
2117         tkey.time=pa->state.time;
2118
2119         if (part->type != PART_HAIR) {
2120                 if (do_guides(sim->depsgraph, sim->psys->part, sim->psys->effectors, &tkey, p, time)) {
2121                         copy_v3_v3(pa->state.co,tkey.co);
2122                         /* guides don't produce valid velocity */
2123                         sub_v3_v3v3(pa->state.vel, tkey.co, pa->prev_state.co);
2124                         mul_v3_fl(pa->state.vel,1.0f/dtime);
2125                         pa->state.time=tkey.time;
2126                 }
2127         }
2128 }
2129 static void basic_rotate(ParticleSettings *part, ParticleData *pa, float dfra, float timestep)
2130 {
2131         float rotfac, rot1[4], rot2[4] = {1.0,0.0,0.0,0.0}, dtime=dfra*timestep, extrotfac;
2132
2133         if ((part->flag & PART_ROTATIONS) == 0) {
2134                 unit_qt(pa->state.rot);
2135                 return;
2136         }
2137
2138         if (part->flag & PART_ROT_DYN) {
2139                 extrotfac = len_v3(pa->state.ave);
2140         }
2141         else {
2142                 extrotfac = 0.0f;
2143         }
2144
2145         if ((part->flag & PART_ROT_DYN) && ELEM(part->avemode, PART_AVE_VELOCITY, PART_AVE_HORIZONTAL, PART_AVE_VERTICAL)) {
2146                 float angle;
2147                 float len1 = len_v3(pa->prev_state.vel);
2148                 float len2 = len_v3(pa->state.vel);
2149                 float vec[3];
2150
2151                 if (len1 == 0.0f || len2 == 0.0f) {
2152                         zero_v3(pa->state.ave);
2153                 }
2154                 else {
2155                         cross_v3_v3v3(pa->state.ave, pa->prev_state.vel, pa->state.vel);
2156                         normalize_v3(pa->state.ave);
2157                         angle = dot_v3v3(pa->prev_state.vel, pa->state.vel) / (len1 * len2);
2158                         mul_v3_fl(pa->state.ave, saacos(angle) / dtime);
2159                 }
2160
2161                 get_angular_velocity_vector(part->avemode, &pa->state, vec);
2162                 axis_angle_to_quat(rot2, vec, dtime*part->avefac);
2163         }
2164
2165         rotfac = len_v3(pa->state.ave);
2166         if (rotfac == 0.0f || (part->flag & PART_ROT_DYN)==0 || extrotfac == 0.0f) {
2167                 unit_qt(rot1);
2168         }
2169         else {
2170                 axis_angle_to_quat(rot1,pa->state.ave,rotfac*dtime);
2171         }
2172         mul_qt_qtqt(pa->state.rot,rot1,pa->prev_state.rot);
2173         mul_qt_qtqt(pa->state.rot,rot2,pa->state.rot);
2174
2175         /* keep rotation quat in good health */
2176         normalize_qt(pa->state.rot);
2177 }
2178
2179 /************************************************
2180  * Collisions
2181  *
2182  * The algorithm is roughly:
2183  *  1. Use a BVH tree to search for faces that a particle may collide with.
2184  *  2. Use Newton's method to find the exact time at which the collision occurs.
2185  *     https://en.wikipedia.org/wiki/Newton's_method
2186  *
2187  ************************************************/
2188 #define COLLISION_MIN_RADIUS 0.001f
2189 #define COLLISION_MIN_DISTANCE 0.0001f
2190 #define COLLISION_ZERO 0.00001f
2191 #define COLLISION_INIT_STEP 0.00008f
2192 typedef float (*NRDistanceFunc)(float *p, float radius, ParticleCollisionElement *pce, float *nor);
2193 static float nr_signed_distance_to_plane(float *p, float radius, ParticleCollisionElement *pce, float *nor)
2194 {
2195         float p0[3], e1[3], e2[3], d;
2196
2197         sub_v3_v3v3(e1, pce->x1, pce->x0);
2198         sub_v3_v3v3(e2, pce->x2, pce->x0);
2199         sub_v3_v3v3(p0, p, pce->x0);
2200
2201         cross_v3_v3v3(nor, e1, e2);
2202         normalize_v3(nor);
2203
2204         d = dot_v3v3(p0, nor);
2205
2206         if (pce->inv_nor == -1) {
2207                 if (d < 0.f)
2208                         pce->inv_nor = 1;
2209                 else
2210                         pce->inv_nor = 0;
2211         }
2212
2213         if (pce->inv_nor == 1) {
2214                 negate_v3(nor);
2215                 d = -d;
2216         }
2217
2218         return d - radius;
2219 }
2220 static float nr_distance_to_edge(float *p, float radius, ParticleCollisionElement *pce, float *UNUSED(nor))
2221 {
2222         float v0[3], v1[3], v2[3], c[3];
2223
2224         sub_v3_v3v3(v0, pce->x1, pce->x0);
2225         sub_v3_v3v3(v1, p, pce->x0);
2226         sub_v3_v3v3(v2, p, pce->x1);
2227
2228         cross_v3_v3v3(c, v1, v2);
2229
2230         return fabsf(len_v3(c)/len_v3(v0)) - radius;
2231 }
2232 static float nr_distance_to_vert(float *p, float radius, ParticleCollisionElement *pce, float *UNUSED(nor))
2233 {
2234         return len_v3v3(p, pce->x0) - radius;
2235 }
2236 static void collision_interpolate_element(ParticleCollisionElement *pce, float t, float fac, ParticleCollision *col)
2237 {
2238         /* t is the current time for newton rhapson */
2239         /* fac is the starting factor for current collision iteration */
2240         /* the col->fac's are factors for the particle subframe step start and end during collision modifier step */
2241         float f = fac + t*(1.f-fac);
2242         float mul = col->fac1 + f * (col->fac2-col->fac1);
2243         if (pce->tot > 0) {
2244                 madd_v3_v3v3fl(pce->x0, pce->x[0], pce->v[0], mul);
2245
2246                 if (pce->tot > 1) {
2247                         madd_v3_v3v3fl(pce->x1, pce->x[1], pce->v[1], mul);
2248
2249                         if (pce->tot > 2)
2250                                 madd_v3_v3v3fl(pce->x2, pce->x[2], pce->v[2], mul);
2251                 }
2252         }
2253 }
2254 static void collision_point_velocity(ParticleCollisionElement *pce)
2255 {
2256         float v[3];
2257
2258         copy_v3_v3(pce->vel, pce->v[0]);
2259
2260         if (pce->tot > 1) {
2261                 sub_v3_v3v3(v, pce->v[1], pce->v[0]);
2262                 madd_v3_v3fl(pce->vel, v, pce->uv[0]);
2263
2264                 if (pce->tot > 2) {
2265                         sub_v3_v3v3(v, pce->v[2], pce->v[0]);
2266                         madd_v3_v3fl(pce->vel, v, pce->uv[1]);
2267                 }
2268         }
2269 }
2270 static float collision_point_distance_with_normal(float p[3], ParticleCollisionElement *pce, float fac, ParticleCollision *col, float *nor)
2271 {
2272         if (fac >= 0.f)
2273                 collision_interpolate_element(pce, 0.f, fac, col);
2274
2275         switch (pce->tot) {
2276                 case 1:
2277                 {
2278                         sub_v3_v3v3(nor, p, pce->x0);
2279                         return normalize_v3(nor);
2280                 }
2281                 case 2:
2282                 {
2283                         float u, e[3], vec[3];
2284                         sub_v3_v3v3(e, pce->x1, pce->x0);
2285                         sub_v3_v3v3(vec, p, pce->x0);
2286                         u = dot_v3v3(vec, e) / dot_v3v3(e, e);
2287
2288                         madd_v3_v3v3fl(nor, vec, e, -u);
2289                         return normalize_v3(nor);
2290                 }
2291                 case 3:
2292                         return nr_signed_distance_to_plane(p, 0.f, pce, nor);
2293         }
2294         return 0;
2295 }
2296 static void collision_point_on_surface(float p[3], ParticleCollisionElement *pce, float fac, ParticleCollision *col, float *co)
2297 {
2298         collision_interpolate_element(pce, 0.f, fac, col);
2299
2300         switch (pce->tot) {
2301                 case 1:
2302                 {
2303                         sub_v3_v3v3(co, p, pce->x0);
2304                         normalize_v3(co);
2305                         madd_v3_v3v3fl(co, pce->x0, co, col->radius);
2306                         break;
2307                 }
2308                 case 2:
2309                 {
2310                         float u, e[3], vec[3], nor[3];
2311                         sub_v3_v3v3(e, pce->x1, pce->x0);
2312                         sub_v3_v3v3(vec, p, pce->x0);
2313                         u = dot_v3v3(vec, e) / dot_v3v3(e, e);
2314
2315                         madd_v3_v3v3fl(nor, vec, e, -u);
2316                         normalize_v3(nor);
2317
2318                         madd_v3_v3v3fl(co, pce->x0, e, pce->uv[0]);
2319                         madd_v3_v3fl(co, nor, col->radius);
2320                         break;
2321                 }
2322                 case 3:
2323                 {
2324                         float p0[3], e1[3], e2[3], nor[3];
2325
2326                         sub_v3_v3v3(e1, pce->x1, pce->x0);
2327                         sub_v3_v3v3(e2, pce->x2, pce->x0);
2328                         sub_v3_v3v3(p0, p, pce->x0);
2329
2330                         cross_v3_v3v3(nor, e1, e2);
2331                         normalize_v3(nor);
2332
2333                         if (pce->inv_nor == 1)
2334                                 negate_v3(nor);
2335
2336                         madd_v3_v3v3fl(co, pce->x0, nor, col->radius);
2337                         madd_v3_v3fl(co, e1, pce->uv[0]);
2338                         madd_v3_v3fl(co, e2, pce->uv[1]);
2339                         break;
2340                 }
2341         }
2342 }
2343 /* find first root in range [0-1] starting from 0 */
2344 static float collision_newton_rhapson(ParticleCollision *col, float radius, ParticleCollisionElement *pce, NRDistanceFunc distance_func)
2345 {
2346         float t0, t1, dt_init, d0, d1, dd, n[3];
2347         int iter;
2348
2349         pce->inv_nor = -1;
2350
2351         if (col->inv_total_time > 0.0f) {
2352                 /* Initial step size should be small, but not too small or floating point
2353                  * precision errors will appear. - z0r */
2354                 dt_init = COLLISION_INIT_STEP * col->inv_total_time;
2355         }
2356         else {
2357                 dt_init = 0.001f;
2358         }
2359
2360         /* start from the beginning */
2361         t0 = 0.f;
2362         collision_interpolate_element(pce, t0, col->f, col);
2363         d0 = distance_func(col->co1, radius, pce, n);
2364         t1 = dt_init;
2365         d1 = 0.f;
2366
2367         for (iter=0; iter<10; iter++) {//, itersum++) {
2368                 /* get current location */
2369                 collision_interpolate_element(pce, t1, col->f, col);
2370                 interp_v3_v3v3(pce->p, col->co1, col->co2, t1);
2371
2372                 d1 = distance_func(pce->p, radius, pce, n);
2373
2374                 /* particle already inside face, so report collision */
2375                 if (iter == 0 && d0 < 0.f && d0 > -radius) {
2376                         copy_v3_v3(pce->p, col->co1);
2377                         copy_v3_v3(pce->nor, n);
2378                         pce->inside = 1;
2379                         return 0.f;
2380                 }
2381
2382                 /* Zero gradient (no movement relative to element). Can't step from
2383                  * here. */
2384                 if (d1 == d0) {
2385                         /* If first iteration, try from other end where the gradient may be
2386                          * greater. Note: code duplicated below. */
2387                         if (iter == 0) {
2388                                 t0 = 1.f;
2389                                 collision_interpolate_element(pce, t0, col->f, col);
2390                                 d0 = distance_func(col->co2, radius, pce, n);
2391                                 t1 = 1.0f - dt_init;
2392                                 d1 = 0.f;
2393                                 continue;
2394                         }
2395                         else
2396                                 return -1.f;
2397                 }
2398
2399                 dd = (t1-t0)/(d1-d0);
2400
2401                 t0 = t1;
2402                 d0 = d1;
2403
2404                 t1 -= d1*dd;
2405
2406                 /* Particle moving away from plane could also mean a strangely rotating
2407                  * face, so check from end. Note: code duplicated above. */
2408                 if (iter == 0 && t1 < 0.f) {
2409                         t0 = 1.f;
2410                         collision_interpolate_element(pce, t0, col->f, col);
2411                         d0 = distance_func(col->co2, radius, pce, n);
2412                         t1 = 1.0f - dt_init;
2413                         d1 = 0.f;
2414                         continue;
2415                 }
2416                 else if (iter == 1 && (t1 < -COLLISION_ZERO || t1 > 1.f))
2417                         return -1.f;
2418
2419                 if (d1 <= COLLISION_ZERO && d1 >= -COLLISION_ZERO) {
2420                         if (t1 >= -COLLISION_ZERO && t1 <= 1.f) {
2421                                 if (distance_func == nr_signed_distance_to_plane)
2422                                         copy_v3_v3(pce->nor, n);
2423
2424                                 CLAMP(t1, 0.f, 1.f);
2425
2426                                 return t1;
2427                         }
2428                         else
2429                                 return -1.f;
2430                 }
2431         }
2432         return -1.0;
2433 }
2434 static int collision_sphere_to_tri(ParticleCollision *col, float radius, ParticleCollisionElement *pce, float *t)
2435 {
2436         ParticleCollisionElement *result = &col->pce;
2437         float ct, u, v;
2438
2439         pce->inv_nor = -1;
2440         pce->inside = 0;
2441
2442         ct = collision_newton_rhapson(col, radius, pce, nr_signed_distance_to_plane);
2443
2444         if (ct >= 0.f && ct < *t && (result->inside==0 || pce->inside==1) ) {
2445                 float e1[3], e2[3], p0[3];
2446                 float e1e1, e1e2, e1p0, e2e2, e2p0, inv;
2447
2448                 sub_v3_v3v3(e1, pce->x1, pce->x0);
2449                 sub_v3_v3v3(e2, pce->x2, pce->x0);
2450                 /* XXX: add radius correction here? */
2451                 sub_v3_v3v3(p0, pce->p, pce->x0);
2452
2453                 e1e1 = dot_v3v3(e1, e1);
2454                 e1e2 = dot_v3v3(e1, e2);
2455                 e1p0 = dot_v3v3(e1, p0);
2456                 e2e2 = dot_v3v3(e2, e2);
2457                 e2p0 = dot_v3v3(e2, p0);
2458
2459                 inv = 1.f/(e1e1 * e2e2 - e1e2 * e1e2);
2460                 u = (e2e2 * e1p0 - e1e2 * e2p0) * inv;
2461                 v = (e1e1 * e2p0 - e1e2 * e1p0) * inv;
2462
2463                 if (u>=0.f && u<=1.f && v>=0.f && u+v<=1.f) {
2464                         *result = *pce;
2465
2466                         /* normal already calculated in pce */
2467
2468                         result->uv[0] = u;
2469                         result->uv[1] = v;
2470
2471                         *t = ct;
2472                         return 1;
2473                 }
2474         }
2475         return 0;
2476 }
2477 static int collision_sphere_to_edges(ParticleCollision *col, float radius, ParticleCollisionElement *pce, float *t)
2478 {
2479         ParticleCollisionElement edge[3], *cur = NULL, *hit = NULL;
2480         ParticleCollisionElement *result = &col->pce;
2481
2482         float ct;
2483         int i;
2484
2485         for (i=0; i<3; i++) {
2486                 cur = edge+i;
2487                 cur->x[0] = pce->x[i]; cur->x[1] = pce->x[(i+1)%3];
2488                 cur->v[0] = pce->v[i]; cur->v[1] = pce->v[(i+1)%3];
2489                 cur->tot = 2;
2490                 cur->inside = 0;
2491
2492                 ct = collision_newton_rhapson(col, radius, cur, nr_distance_to_edge);
2493
2494                 if (ct >= 0.f && ct < *t) {
2495                         float u, e[3], vec[3];
2496
2497                         sub_v3_v3v3(e, cur->x1, cur->x0);
2498                         sub_v3_v3v3(vec, cur->p, cur->x0);
2499                         u = dot_v3v3(vec, e) / dot_v3v3(e, e);
2500
2501                         if (u < 0.f || u > 1.f)
2502                                 break;
2503
2504                         *result = *cur;
2505
2506                         madd_v3_v3v3fl(result->nor, vec, e, -u);
2507                         normalize_v3(result->nor);
2508
2509                         result->uv[0] = u;
2510
2511
2512                         hit = cur;
2513                         *t = ct;
2514                 }
2515
2516         }
2517
2518         return hit != NULL;
2519 }
2520 static int collision_sphere_to_verts(ParticleCollision *col, float radius, ParticleCollisionElement *pce, float *t)
2521 {
2522         ParticleCollisionElement vert[3], *cur = NULL, *hit = NULL;
2523         ParticleCollisionElement *result = &col->pce;
2524
2525         float ct;
2526         int i;
2527
2528         for (i=0; i<3; i++) {
2529                 cur = vert+i;
2530                 cur->x[0] = pce->x[i];
2531                 cur->v[0] = pce->v[i];
2532                 cur->tot = 1;
2533                 cur->inside = 0;
2534
2535                 ct = collision_newton_rhapson(col, radius, cur, nr_distance_to_vert);
2536
2537                 if (ct >= 0.f && ct < *t) {
2538                         *result = *cur;
2539
2540                         sub_v3_v3v3(result->nor, cur->p, cur->x0);
2541                         normalize_v3(result->nor);
2542
2543                         hit = cur;
2544                         *t = ct;
2545                 }
2546
2547         }
2548
2549         return hit != NULL;
2550 }
2551 /* Callback for BVHTree near test */
2552 void BKE_psys_collision_neartest_cb(void *userdata, int index, const BVHTreeRay *ray, BVHTreeRayHit *hit)
2553 {
2554         ParticleCollision *col = (ParticleCollision *) userdata;
2555         ParticleCollisionElement pce;
2556         const MVertTri *vt = &col->md->tri[index];
2557         MVert *x = col->md->x;
2558         MVert *v = col->md->current_v;
2559         float t = hit->dist/col->original_ray_length;
2560         int collision = 0;
2561
2562         pce.x[0] = x[vt->tri[0]].co;
2563         pce.x[1] = x[vt->tri[1]].co;
2564         pce.x[2] = x[vt->tri[2]].co;
2565
2566         pce.v[0] = v[vt->tri[0]].co;
2567         pce.v[1] = v[vt->tri[1]].co;
2568         pce.v[2] = v[vt->tri[2]].co;
2569
2570         pce.tot = 3;
2571         pce.inside = 0;
2572         pce.index = index;
2573
2574         collision = collision_sphere_to_tri(col, ray->radius, &pce, &t);
2575         if (col->pce.inside == 0) {
2576                 collision += collision_sphere_to_edges(col, ray->radius, &pce, &t);
2577                 collision += collision_sphere_to_verts(col, ray->radius, &pce, &t);
2578         }
2579
2580         if (collision) {
2581                 hit->dist = col->original_ray_length * t;
2582                 hit->index = index;
2583
2584                 collision_point_velocity(&col->pce);
2585
2586                 col->hit = col->current;
2587         }
2588 }
2589 static int collision_detect(ParticleData *pa, ParticleCollision *col, BVHTreeRayHit *hit, ListBase *colliders)
2590 {
2591         const int raycast_flag = BVH_RAYCAST_DEFAULT & ~(BVH_RAYCAST_WATERTIGHT);
2592         ColliderCache *coll;
2593         float ray_dir[3];
2594
2595         if (BLI_listbase_is_empty(colliders))
2596                 return 0;
2597
2598         sub_v3_v3v3(ray_dir, col->co2, col->co1);
2599         hit->index = -1;
2600         hit->dist = col->original_ray_length = normalize_v3(ray_dir);
2601         col->pce.inside = 0;
2602
2603         /* even if particle is stationary we want to check for moving colliders */
2604         /* if hit.dist is zero the bvhtree_ray_cast will just ignore everything */
2605         if (hit->dist == 0.0f)
2606                 hit->dist = col->original_ray_length = 0.000001f;
2607
2608         for (coll = colliders->first; coll; coll=coll->next) {
2609                 /* for boids: don't check with current ground object; also skip if permeated */
2610                 bool skip = false;
2611
2612                 for (int i = 0; i < col->skip_count; i++) {
2613                         if (coll->ob == col->skip[i]) {
2614                                 skip = true;
2615                                 break;
2616                         }
2617                 }
2618
2619                 if (skip)
2620                         continue;
2621
2622                 /* particles should not collide with emitter at birth */
2623                 if (coll->ob == col->emitter && pa->time < col->cfra && pa->time >= col->old_cfra)
2624                         continue;
2625
2626                 col->current = coll->ob;
2627                 col->md = coll->collmd;
2628                 col->fac1 = (col->old_cfra - coll->collmd->time_x) / (coll->collmd->time_xnew - coll->collmd->time_x);
2629                 col->fac2 = (col->cfra - coll->collmd->time_x) / (coll->collmd->time_xnew - coll->collmd->time_x);
2630
2631                 if (col->md && col->md->bvhtree) {
2632                         BLI_bvhtree_ray_cast_ex(
2633                                 col->md->bvhtree, col->co1, ray_dir, col->radius, hit,
2634                                 BKE_psys_collision_neartest_cb, col, raycast_flag);
2635                 }
2636         }
2637
2638         return hit->index >= 0;
2639 }
2640 static int collision_response(ParticleSimulationData *sim, ParticleData *pa, ParticleCollision *col, BVHTreeRayHit *hit, int kill, int dynamic_rotation)
2641 {
2642         ParticleCollisionElement *pce = &col->pce;
2643         PartDeflect *pd = col->hit->pd;
2644         RNG *rng = sim->rng;
2645         /* point of collision */
2646         float co[3];
2647         /* location factor of collision between this iteration */
2648         float x = hit->dist/col->original_ray_length;
2649         /* time factor of collision between timestep */
2650         float f = col->f + x * (1.0f - col->f);
2651         /* time since previous collision (in seconds) */
2652         float dt1 = (f - col->f) * col->total_time;
2653         /* time left after collision (in seconds) */
2654         float dt2 = (1.0f - f) * col->total_time;
2655         /* did particle pass through the collision surface? */
2656         int through = (BLI_rng_get_float(rng) < pd->pdef_perm) ? 1 : 0;
2657
2658         /* calculate exact collision location */
2659         interp_v3_v3v3(co, col->co1, col->co2, x);
2660
2661         /* particle dies in collision */
2662         if (through == 0 && (kill || pd->flag & PDEFLE_KILL_PART)) {
2663                 pa->alive = PARS_DYING;
2664                 pa->dietime = col->old_cfra + (col->cfra - col->old_cfra) * f;
2665
2666                 copy_v3_v3(pa->state.co, co);
2667                 interp_v3_v3v3(pa->state.vel, pa->prev_state.vel, pa->state.vel, f);
2668                 interp_qt_qtqt(pa->state.rot, pa->prev_state.rot, pa->state.rot, f);
2669                 interp_v3_v3v3(pa->state.ave, pa->prev_state.ave, pa->state.ave, f);
2670
2671                 /* particle is dead so we don't need to calculate further */
2672                 return 0;
2673         }
2674         /* figure out velocity and other data after collision */
2675         else {
2676                 /* velocity directly before collision to be modified into velocity directly after collision */
2677                 float v0[3];
2678                 /* normal component of v0 */
2679                 float v0_nor[3];
2680                 /* tangential component of v0 */
2681                 float v0_tan[3];
2682                 /* tangential component of collision surface velocity */
2683                 float vc_tan[3];
2684                 float v0_dot, vc_dot;
2685                 float damp = pd->pdef_damp + pd->pdef_rdamp * 2 * (BLI_rng_get_float(rng) - 0.5f);
2686                 float frict = pd->pdef_frict + pd->pdef_rfrict * 2 * (BLI_rng_get_float(rng) - 0.5f);
2687                 float distance, nor[3], dot;
2688
2689                 CLAMP(damp,0.0f, 1.0f);
2690                 CLAMP(frict,0.0f, 1.0f);
2691
2692                 /* get exact velocity right before collision */
2693                 madd_v3_v3v3fl(v0, col->ve1, col->acc, dt1);
2694
2695                 /* convert collider velocity from 1/framestep to 1/s TODO: here we assume 1 frame step for collision modifier */
2696                 mul_v3_fl(pce->vel, col->inv_timestep);
2697
2698                 /* calculate tangential particle velocity */
2699                 v0_dot = dot_v3v3(pce->nor, v0);
2700                 madd_v3_v3v3fl(v0_tan, v0, pce->nor, -v0_dot);
2701
2702                 /* calculate tangential collider velocity */
2703                 vc_dot = dot_v3v3(pce->nor, pce->vel);
2704                 madd_v3_v3v3fl(vc_tan, pce->vel, pce->nor, -vc_dot);
2705
2706                 /* handle friction effects (tangential and angular velocity) */
2707                 if (frict > 0.0f) {
2708                         /* angular <-> linear velocity */
2709                         if (dynamic_rotation) {
2710                                 float vr_tan[3], v1_tan[3], ave[3];
2711
2712                                 /* linear velocity of particle surface */
2713                                 cross_v3_v3v3(vr_tan, pce->nor, pa->state.ave);
2714                                 mul_v3_fl(vr_tan, pa->size);
2715
2716                                 /* change to coordinates that move with the collision plane */
2717                                 sub_v3_v3v3(v1_tan, v0_tan, vc_tan);
2718
2719                                 /* The resulting velocity is a weighted average of particle cm & surface
2720                                  * velocity. This weight (related to particle's moment of inertia) could
2721                                  * be made a parameter for angular <-> linear conversion.
2722                                  */
2723                                 madd_v3_v3fl(v1_tan, vr_tan, -0.4);
2724                                 mul_v3_fl(v1_tan, 1.0f/1.4f); /* 1/(1+0.4) */
2725
2726                                 /* rolling friction is around 0.01 of sliding friction
2727                                  * (could be made a parameter) */
2728                                 mul_v3_fl(v1_tan, 1.0f - 0.01f * frict);
2729
2730                                 /* surface_velocity is opposite to cm velocity */
2731                                 negate_v3_v3(vr_tan, v1_tan);
2732
2733                                 /* get back to global coordinates */
2734                                 add_v3_v3(v1_tan, vc_tan);
2735
2736                                 /* convert to angular velocity*/
2737                                 cross_v3_v3v3(ave, vr_tan, pce->nor);
2738                                 mul_v3_fl(ave, 1.0f/MAX2(pa->size, 0.001f));
2739
2740                                 /* only friction will cause change in linear & angular velocity */
2741                                 interp_v3_v3v3(pa->state.ave, pa->state.ave, ave, frict);
2742                                 interp_v3_v3v3(v0_tan, v0_tan, v1_tan, frict);
2743                         }
2744                         else {
2745                                 /* just basic friction (unphysical due to the friction model used in Blender) */
2746                                 interp_v3_v3v3(v0_tan, v0_tan, vc_tan, frict);
2747                         }
2748                 }
2749
2750                 /* stickiness was possibly added before, so cancel that before calculating new normal velocity */
2751                 /* otherwise particles go flying out of the surface because of high reversed sticky velocity */
2752                 if (v0_dot < 0.0f) {
2753                         v0_dot += pd->pdef_stickness;
2754                         if (v0_dot > 0.0f)
2755                                 v0_dot = 0.0f;
2756                 }
2757
2758                 /* damping and flipping of velocity around normal */
2759                 v0_dot *= 1.0f - damp;
2760                 vc_dot *= through ? damp : 1.0f;
2761
2762                 /* calculate normal particle velocity */
2763                 /* special case for object hitting the particle from behind */
2764                 if (through==0 && ((vc_dot>0.0f && v0_dot>0.0f && vc_dot>v0_dot) || (vc_dot<0.0f && v0_dot<0.0f && vc_dot<v0_dot)))
2765                         mul_v3_v3fl(v0_nor, pce->nor, vc_dot);
2766                 else if (v0_dot > 0.f)
2767                         mul_v3_v3fl(v0_nor, pce->nor, vc_dot + v0_dot);
2768                 else
2769                         mul_v3_v3fl(v0_nor, pce->nor, vc_dot + (through ? 1.0f : -1.0f) * v0_dot);
2770
2771                 /* combine components together again */
2772                 add_v3_v3v3(v0, v0_nor, v0_tan);
2773
2774                 if (col->boid) {
2775                         /* keep boids above ground */
2776                         BoidParticle *bpa = pa->boid;
2777                         if (bpa->data.mode == eBoidMode_OnLand || co[2] <= col->boid_z) {
2778                                 co[2] = col->boid_z;
2779                                 v0[2] = 0.0f;
2780                         }
2781                 }
2782
2783                 /* re-apply acceleration to final location and velocity */
2784                 madd_v3_v3v3fl(pa->state.co, co, v0, dt2);
2785                 madd_v3_v3fl(pa->state.co, col->acc, 0.5f*dt2*dt2);
2786                 madd_v3_v3v3fl(pa->state.vel, v0, col->acc, dt2);
2787
2788                 /* make sure particle stays on the right side of the surface */
2789                 if (!through) {
2790                         distance = collision_point_distance_with_normal(co, pce, -1.f, col, nor);
2791
2792                         if (distance < col->radius + COLLISION_MIN_DISTANCE)
2793                                 madd_v3_v3fl(co, nor, col->radius + COLLISION_MIN_DISTANCE - distance);
2794
2795                         dot = dot_v3v3(nor, v0);
2796                         if (dot < 0.f)
2797                                 madd_v3_v3fl(v0, nor, -dot);
2798
2799                         distance = collision_point_distance_with_normal(pa->state.co, pce, 1.f, col, nor);
2800
2801                         if (distance < col->radius + COLLISION_MIN_DISTANCE)
2802                                 madd_v3_v3fl(pa->state.co, nor, col->radius + COLLISION_MIN_DISTANCE - distance);
2803
2804                         dot = dot_v3v3(nor, pa->state.vel);
2805                         if (dot < 0.f)
2806                                 madd_v3_v3fl(pa->state.vel, nor, -dot);
2807                 }
2808
2809                 /* add stickiness to surface */
2810                 madd_v3_v3fl(pa->state.vel, pce->nor, -pd->pdef_stickness);
2811
2812                 /* set coordinates for next iteration */
2813                 copy_v3_v3(col->co1, co);
2814                 copy_v3_v3(col->co2, pa->state.co);
2815
2816                 copy_v3_v3(col->ve1, v0);
2817                 copy_v3_v3(col->ve2, pa->state.vel);
2818
2819                 col->f = f;
2820         }
2821
2822         /* if permeability random roll succeeded, disable collider for this sim step */
2823         if (through) {
2824                 col->skip[col->skip_count++] = col->hit;
2825         }
2826
2827         return 1;
2828 }
2829 static void collision_fail(ParticleData *pa, ParticleCollision *col)
2830 {
2831         /* final chance to prevent total failure, so stick to the surface and hope for the best */
2832         collision_point_on_surface(col->co1, &col->pce, 1.f, col, pa->state.co);
2833
2834         copy_v3_v3(pa->state.vel, col->pce.vel);
2835         mul_v3_fl(pa->state.vel, col->inv_timestep);
2836
2837
2838         /* printf("max iterations\n"); */
2839 }
2840
2841 /* Particle - Mesh collision detection and response
2842  * Features:
2843  * -friction and damping
2844  * -angular momentum <-> linear momentum
2845  * -high accuracy by re-applying particle acceleration after collision
2846  * -handles moving, rotating and deforming meshes
2847  * -uses Newton-Rhapson iteration to find the collisions
2848  * -handles spherical particles and (nearly) point like particles
2849  */
2850 static void collision_check(ParticleSimulationData *sim, int p, float dfra, float cfra)
2851 {
2852         ParticleSettings *part = sim->psys->part;
2853         ParticleData *pa = sim->psys->particles + p;
2854         ParticleCollision col;
2855         BVHTreeRayHit hit;
2856         int collision_count=0;
2857
2858         float timestep = psys_get_timestep(sim);
2859
2860         memset(&col, 0, sizeof(ParticleCollision));
2861
2862         col.total_time = timestep * dfra;
2863         col.inv_total_time = 1.0f/col.total_time;
2864         col.inv_timestep = 1.0f/timestep;
2865
2866         col.cfra = cfra;
2867         col.old_cfra = sim->psys->cfra;
2868
2869         /* get acceleration (from gravity, forcefields etc. to be re-applied in collision response) */
2870         sub_v3_v3v3(col.acc, pa->state.vel, pa->prev_state.vel);
2871         mul_v3_fl(col.acc, 1.f/col.total_time);
2872
2873         /* set values for first iteration */
2874         copy_v3_v3(col.co1, pa->prev_state.co);
2875         copy_v3_v3(col.co2, pa->state.co);
2876         copy_v3_v3(col.ve1, pa->prev_state.vel);
2877         copy_v3_v3(col.ve2, pa->state.vel);
2878         col.f = 0.0f;
2879
2880         col.radius = ((part->flag & PART_SIZE_DEFL) || (part->phystype == PART_PHYS_BOIDS)) ? pa->size : COLLISION_MIN_RADIUS;
2881
2882         /* override for boids */
2883         if (part->phystype == PART_PHYS_BOIDS && part->boids->options & BOID_ALLOW_LAND) {
2884                 col.boid = 1;
2885                 col.boid_z = pa->state.co[2];
2886                 col.skip[col.skip_count++] = pa->boid->ground;
2887         }
2888
2889         /* 10 iterations to catch multiple collisions */
2890         while (collision_count < PARTICLE_COLLISION_MAX_COLLISIONS) {
2891                 if (collision_detect(pa, &col, &hit, sim->colliders)) {
2892
2893                         collision_count++;
2894
2895                         if (collision_count == PARTICLE_COLLISION_MAX_COLLISIONS)
2896                                 collision_fail(pa, &col);
2897                         else if (collision_response(sim, pa, &col, &hit, part->flag & PART_DIE_ON_COL, part->flag & PART_ROT_DYN)==0)
2898                                 return;
2899                 }
2900                 else
2901                         return;
2902         }
2903 }
2904 /************************************************/
2905 /*                      Hair                                                            */
2906 /************************************************/
2907 /* check if path cache or children need updating and do it if needed */
2908 static void psys_update_path_cache(ParticleSimulationData *sim, float cfra, const bool use_render_params)
2909 {
2910         ParticleSystem *psys = sim->psys;
2911         ParticleSettings *part = psys->part;
2912         ParticleEditSettings *pset = &sim->scene->toolsettings->particle;
2913         int distr=0, alloc=0, skip=0;
2914
2915         if ((psys->part->childtype && psys->totchild != psys_get_tot_child(sim->scene, psys, use_render_params)) || psys->recalc&ID_RECALC_PSYS_RESET)
2916                 alloc=1;
2917
2918         if (alloc || psys->recalc&ID_RECALC_PSYS_CHILD || (psys->vgroup[PSYS_VG_DENSITY] && (sim->ob && sim->ob->mode & OB_MODE_WEIGHT_PAINT)))
2919                 distr=1;
2920
2921         if (distr) {
2922                 if (alloc)
2923                         realloc_particles(sim, sim->psys->totpart);
2924
2925                 if (psys_get_tot_child(sim->scene, psys, use_render_params)) {
2926                         /* don't generate children while computing the hair keys */
2927                         if (!(psys->part->type == PART_HAIR) || (psys->flag & PSYS_HAIR_DONE)) {
2928                                 distribute_particles(sim, PART_FROM_CHILD);
2929
2930                                 if (part->childtype==PART_CHILD_FACES && part->parents != 0.0f)
2931                                         psys_find_parents(sim, use_render_params);
2932                         }
2933                 }
2934                 else
2935                         psys_free_children(psys);
2936         }
2937
2938         if ((part->type==PART_HAIR || psys->flag&PSYS_KEYED || psys->pointcache->flag & PTCACHE_BAKED)==0)
2939                 skip = 1; /* only hair, keyed and baked stuff can have paths */
2940         else if (part->ren_as != PART_DRAW_PATH && !(part->type==PART_HAIR && ELEM(part->ren_as, PART_DRAW_OB, PART_DRAW_GR)))
2941                 skip = 1; /* particle visualization must be set as path */
2942         else if (DEG_get_mode(sim->depsgraph) != DAG_EVAL_RENDER) {
2943                 if (part->draw_as != PART_DRAW_REND)
2944                         skip = 1; /* draw visualization */
2945                 else if (psys->pointcache->flag & PTCACHE_BAKING)
2946                         skip = 1; /* no need to cache paths while baking dynamics */
2947
2948                 else if (psys_in_edit_mode(sim->depsgraph, psys)) {
2949                         if ((pset->flag & PE_DRAW_PART)==0)
2950                                 skip = 1;
2951                         else if (part->childtype==0 && (psys->flag & PSYS_HAIR_DYNAMICS && psys->pointcache->flag & PTCACHE_BAKED)==0)
2952                                 skip = 1; /* in edit mode paths are needed for child particles and dynamic hair */
2953                 }
2954         }
2955
2956         if (!skip) {
2957                 psys_cache_paths(sim, cfra, use_render_params);
2958
2959                 /* for render, child particle paths are computed on the fly */
2960                 if (part->childtype) {
2961                         if (!psys->totchild)
2962                                 skip = 1;
2963                         else if (psys->part->type == PART_HAIR && (psys->flag & PSYS_HAIR_DONE)==0)
2964                                 skip = 1;
2965
2966                         if (!skip)
2967                                 psys_cache_child_paths(sim, cfra, 0, use_render_params);
2968                 }
2969         }
2970         else if (psys->pathcache)
2971                 psys_free_path_cache(psys, NULL);
2972 }
2973
2974 static bool psys_hair_use_simulation(ParticleData *pa, float max_length)
2975 {
2976         /* Minimum segment length relative to average length.
2977          * Hairs with segments below this length will be excluded from the simulation,
2978          * because otherwise the solver will become unstable.
2979          * The hair system should always make sure the hair segments have reasonable length ratios,
2980          * but this can happen in old files when e.g. cutting hair.
2981          */
2982         const float min_length = 0.1f * max_length;
2983
2984         HairKey *key;
2985         int k;
2986
2987         if (pa->totkey < 2)
2988                 return false;
2989
2990         for (k=1, key=pa->hair+1; k<pa->totkey; k++,key++) {
2991                 float length = len_v3v3(key->co, (key-1)->co);
2992                 if (length < min_length)
2993                         return false;
2994         }
2995
2996         return true;
2997 }
2998
2999 static MDeformVert *hair_set_pinning(MDeformVert *dvert, float weight)
3000 {
3001         if (dvert) {
3002                 if (!dvert->totweight) {
3003                         dvert->dw = MEM_callocN(sizeof(MDeformWeight), "deformWeight");
3004                         dvert->totweight = 1;
3005                 }
3006
3007                 dvert->dw->weight = weight;
3008                 dvert++;
3009         }
3010         return dvert;
3011 }
3012
3013 static void hair_create_input_mesh(ParticleSimulationData *sim, int totpoint, int totedge, Mesh **r_mesh, ClothHairData **r_hairdata)
3014 {
3015         ParticleSystem *psys = sim->psys;
3016         ParticleSettings *part = psys->part;
3017         Mesh *mesh;
3018         ClothHairData *hairdata;
3019         MVert *mvert;
3020         MEdge *medge;
3021         MDeformVert *dvert;
3022         HairKey *key;
3023         PARTICLE_P;
3024         int k, hair_index;
3025         float hairmat[4][4];
3026         float max_length;
3027         float hair_radius;
3028
3029         mesh = *r_mesh;
3030         if (!mesh) {
3031                 *r_mesh = mesh = BKE_mesh_new_nomain(totpoint, totedge, 0, 0, 0);
3032                 CustomData_add_layer(&mesh->vdata, CD_MDEFORMVERT, CD_CALLOC, NULL, mesh->totvert);
3033                 BKE_mesh_update_customdata_pointers(mesh, false);
3034         }
3035         mvert = mesh->mvert;
3036         medge = mesh->medge;
3037         dvert = mesh->dvert;
3038
3039         hairdata = *r_hairdata;
3040         if (!hairdata) {
3041                 *r_hairdata = hairdata = MEM_mallocN(sizeof(ClothHairData) * totpoint, "hair data");
3042         }
3043
3044         /* calculate maximum segment length */
3045         max_length = 0.0f;
3046         LOOP_PARTICLES {
3047                 if (!(pa->flag & PARS_UNEXIST)) {
3048                         for (k=1, key=pa->hair+1; k<pa->totkey; k++,key++) {