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