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