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