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