Merge branch 'blender2.7'
[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         /* 4.77 is an experimentally determined density factor */
1692         float rest_density = fluid->rest_density * (fluid->flag & SPH_FAC_DENSITY ? 4.77f : 1.f);
1693         float rest_length = fluid->rest_length * (fluid->flag & SPH_FAC_REST_LENGTH ? 2.588f * pa->size : 1.f);
1694
1695         float stiffness = fluid->stiffness_k;
1696         float stiffness_near_fac = fluid->stiffness_knear * (fluid->flag & SPH_FAC_REPULSION ? fluid->stiffness_k : 1.f);
1697
1698         ParticleData *npa;
1699         float vec[3];
1700         float vel[3];
1701         float co[3];
1702         float data[2];
1703         float density, near_density;
1704
1705         int i, spring_index, index = pa - psys[0]->particles;
1706
1707         data[0] = data[1] = 0;
1708         pfr.data = data;
1709         pfr.h = h;
1710         pfr.pa = pa;
1711         pfr.mass = sphdata->mass;
1712
1713         sph_evaluate_func( NULL, psys, state->co, &pfr, interaction_radius, sph_density_accum_cb);
1714
1715         density = data[0];
1716         near_density = data[1];
1717
1718         pressure =  stiffness * (density - rest_density);
1719         near_pressure = stiffness_near_fac * near_density;
1720
1721         pfn = pfr.neighbors;
1722         for (i=0; i<pfr.tot_neighbors; i++, pfn++) {
1723                 npa = pfn->psys->particles + pfn->index;
1724
1725                 madd_v3_v3v3fl(co, npa->prev_state.co, npa->prev_state.vel, state->time);
1726
1727                 sub_v3_v3v3(vec, co, state->co);
1728                 rij = normalize_v3(vec);
1729
1730                 q = (1.f - rij/h) * pfn->psys->part->mass * inv_mass;
1731
1732                 if (pfn->psys->part->flag & PART_SIZEMASS)
1733                         q *= npa->size;
1734
1735                 copy_v3_v3(vel, npa->prev_state.vel);
1736
1737                 /* Double Density Relaxation */
1738                 madd_v3_v3fl(force, vec, -(pressure + near_pressure*q)*q);
1739
1740                 /* Viscosity */
1741                 if (visc > 0.f  || stiff_visc > 0.f) {
1742                         sub_v3_v3v3(dv, vel, state->vel);
1743                         u = dot_v3v3(vec, dv);
1744
1745                         if (u < 0.f && visc > 0.f)
1746                                 madd_v3_v3fl(force, vec, 0.5f * q * visc * u );
1747
1748                         if (u > 0.f && stiff_visc > 0.f)
1749                                 madd_v3_v3fl(force, vec, 0.5f * q * stiff_visc * u );
1750                 }
1751
1752                 if (spring_constant > 0.f) {
1753                         /* Viscoelastic spring force */
1754                         if (pfn->psys == psys[0] && fluid->flag & SPH_VISCOELASTIC_SPRINGS && springhash) {
1755                                 /* BLI_edgehash_lookup appears to be thread-safe. - z0r */
1756                                 spring_index = POINTER_AS_INT(BLI_edgehash_lookup(springhash, index, pfn->index));
1757
1758                                 if (spring_index) {
1759                                         spring = psys[0]->fluid_springs + spring_index - 1;
1760
1761                                         madd_v3_v3fl(force, vec, -10.f * spring_constant * (1.f - rij/h) * (spring->rest_length - rij));
1762                                 }
1763                                 else if (fluid->spring_frames == 0 || (pa->prev_state.time-pa->time) <= fluid->spring_frames) {
1764                                         ParticleSpring temp_spring;
1765                                         temp_spring.particle_index[0] = index;
1766                                         temp_spring.particle_index[1] = pfn->index;
1767                                         temp_spring.rest_length = (fluid->flag & SPH_CURRENT_REST_LENGTH) ? rij : rest_length;
1768                                         temp_spring.delete_flag = 0;
1769
1770                                         /* sph_spring_add is not thread-safe. - z0r */
1771                                         sph_spring_add(psys[0], &temp_spring);
1772                                 }
1773                         }
1774                         else {/* PART_SPRING_HOOKES - Hooke's spring force */
1775                                 madd_v3_v3fl(force, vec, -10.f * spring_constant * (1.f - rij/h) * (rest_length - rij));
1776                         }
1777                 }
1778         }
1779
1780         /* Artificial buoyancy force in negative gravity direction  */
1781         if (fluid->buoyancy > 0.f && gravity)
1782                 madd_v3_v3fl(force, gravity, fluid->buoyancy * (density-rest_density));
1783
1784         if (sphdata->pass == 0 && psys[0]->part->time_flag & PART_TIME_AUTOSF)
1785                 sph_particle_courant(sphdata, &pfr);
1786         sphdata->pass++;
1787 }
1788
1789 static void sphclassical_density_accum_cb(void *userdata, int index, const float co[3], float UNUSED(squared_dist))
1790 {
1791         SPHRangeData *pfr = (SPHRangeData *)userdata;
1792         ParticleData *npa = pfr->npsys->particles + index;
1793         float q;
1794         float qfac = 21.0f / (256.f * (float)M_PI);
1795         float rij, rij_h;
1796         float vec[3];
1797
1798         /* Exclude particles that are more than 2h away. Can't use squared_dist here
1799          * because it is not accurate enough. Use current state, i.e. the output of
1800          * basic_integrate() - z0r */
1801         sub_v3_v3v3(vec, npa->state.co, co);
1802         rij = len_v3(vec);
1803         rij_h = rij / pfr->h;
1804         if (rij_h > 2.0f)
1805                 return;
1806
1807         /* Smoothing factor. Utilise the Wendland kernel. gnuplot:
1808          *     q1(x) = (2.0 - x)**4 * ( 1.0 + 2.0 * x)
1809          *     plot [0:2] q1(x) */
1810         q  = qfac / pow3f(pfr->h) * pow4f(2.0f - rij_h) * ( 1.0f + 2.0f * rij_h);
1811         q *= pfr->npsys->part->mass;
1812
1813         if (pfr->use_size)
1814                 q *= pfr->pa->size;
1815
1816         pfr->data[0] += q;
1817         pfr->data[1] += q / npa->sphdensity;
1818 }
1819
1820 static void sphclassical_neighbour_accum_cb(void *userdata, int index, const float co[3], float UNUSED(squared_dist))
1821 {
1822         SPHRangeData *pfr = (SPHRangeData *)userdata;
1823         ParticleData *npa = pfr->npsys->particles + index;
1824         float rij, rij_h;
1825         float vec[3];
1826
1827         if (pfr->tot_neighbors >= SPH_NEIGHBORS)
1828                 return;
1829
1830         /* Exclude particles that are more than 2h away. Can't use squared_dist here
1831          * because it is not accurate enough. Use current state, i.e. the output of
1832          * basic_integrate() - z0r */
1833         sub_v3_v3v3(vec, npa->state.co, co);
1834         rij = len_v3(vec);
1835         rij_h = rij / pfr->h;
1836         if (rij_h > 2.0f)
1837                 return;
1838
1839         pfr->neighbors[pfr->tot_neighbors].index = index;
1840         pfr->neighbors[pfr->tot_neighbors].psys = pfr->npsys;
1841         pfr->tot_neighbors++;
1842 }
1843 static void sphclassical_force_cb(void *sphdata_v, ParticleKey *state, float *force, float *UNUSED(impulse))
1844 {
1845         SPHData *sphdata = (SPHData *)sphdata_v;
1846         ParticleSystem **psys = sphdata->psys;
1847         ParticleData *pa = sphdata->pa;
1848         SPHFluidSettings *fluid = psys[0]->part->fluid;
1849         SPHRangeData pfr;
1850         SPHNeighbor *pfn;
1851         float *gravity = sphdata->gravity;
1852
1853         float dq, u, rij, dv[3];
1854         float pressure, npressure;
1855
1856         float visc = fluid->viscosity_omega;
1857
1858         float interaction_radius;
1859         float h, hinv;
1860         /* 4.77 is an experimentally determined density factor */
1861         float rest_density = fluid->rest_density * (fluid->flag & SPH_FAC_DENSITY ? 4.77f : 1.0f);
1862
1863         // Use speed of sound squared
1864         float stiffness = pow2f(fluid->stiffness_k);
1865
1866         ParticleData *npa;
1867         float vec[3];
1868         float co[3];
1869         float pressureTerm;
1870
1871         int i;
1872
1873         float qfac2 = 42.0f / (256.0f * (float)M_PI);
1874         float rij_h;
1875
1876         /* 4.0 here is to be consistent with previous formulation/interface */
1877         interaction_radius = fluid->radius * (fluid->flag & SPH_FAC_RADIUS ? 4.0f * pa->size : 1.0f);
1878         h = interaction_radius * sphdata->hfac;
1879         hinv = 1.0f / h;
1880
1881         pfr.h = h;
1882         pfr.pa = pa;
1883
1884         sph_evaluate_func(NULL, psys, state->co, &pfr, interaction_radius, sphclassical_neighbour_accum_cb);
1885         pressure =  stiffness * (pow7f(pa->sphdensity / rest_density) - 1.0f);
1886
1887         /* multiply by mass so that we return a force, not accel */
1888         qfac2 *= sphdata->mass / pow3f(pfr.h);
1889
1890         pfn = pfr.neighbors;
1891         for (i = 0; i < pfr.tot_neighbors; i++, pfn++) {
1892                 npa = pfn->psys->particles + pfn->index;
1893                 if (npa == pa) {
1894                         /* we do not contribute to ourselves */
1895                         continue;
1896                 }
1897
1898                 /* Find vector to neighbor. Exclude particles that are more than 2h
1899                  * away. Can't use current state here because it may have changed on
1900                  * another thread - so do own mini integration. Unlike basic_integrate,
1901                  * SPH integration depends on neighboring particles. - z0r */
1902                 madd_v3_v3v3fl(co, npa->prev_state.co, npa->prev_state.vel, state->time);
1903                 sub_v3_v3v3(vec, co, state->co);
1904                 rij = normalize_v3(vec);
1905                 rij_h = rij / pfr.h;
1906                 if (rij_h > 2.0f)
1907                         continue;
1908
1909                 npressure = stiffness * (pow7f(npa->sphdensity / rest_density) - 1.0f);
1910
1911                 /* First derivative of smoothing factor. Utilise the Wendland kernel.
1912                  * gnuplot:
1913                  *     q2(x) = 2.0 * (2.0 - x)**4 - 4.0 * (2.0 - x)**3 * (1.0 + 2.0 * x)
1914                  *     plot [0:2] q2(x)
1915                  * Particles > 2h away are excluded above. */
1916                 dq = qfac2 * (2.0f * pow4f(2.0f - rij_h) - 4.0f * pow3f(2.0f - rij_h) * (1.0f + 2.0f * rij_h)  );
1917
1918                 if (pfn->psys->part->flag & PART_SIZEMASS)
1919                         dq *= npa->size;
1920
1921                 pressureTerm = pressure / pow2f(pa->sphdensity) + npressure / pow2f(npa->sphdensity);
1922
1923                 /* Note that 'minus' is removed, because vec = vecBA, not vecAB.
1924                  * This applies to the viscosity calculation below, too. */
1925                 madd_v3_v3fl(force, vec, pressureTerm * dq);
1926
1927                 /* Viscosity */
1928                 if (visc > 0.0f) {
1929                         sub_v3_v3v3(dv, npa->prev_state.vel, pa->prev_state.vel);
1930                         u = dot_v3v3(vec, dv);
1931                         /* Apply parameters */
1932                         u *= -dq * hinv * visc / (0.5f * npa->sphdensity + 0.5f * pa->sphdensity);
1933                         madd_v3_v3fl(force, vec, u);
1934                 }
1935         }
1936
1937         /* Artificial buoyancy force in negative gravity direction  */
1938         if (fluid->buoyancy > 0.f && gravity)
1939                 madd_v3_v3fl(force, gravity, fluid->buoyancy * (pa->sphdensity - rest_density));
1940
1941         if (sphdata->pass == 0 && psys[0]->part->time_flag & PART_TIME_AUTOSF)
1942                 sph_particle_courant(sphdata, &pfr);
1943         sphdata->pass++;
1944 }
1945
1946 static void sphclassical_calc_dens(ParticleData *pa, float UNUSED(dfra), SPHData *sphdata)
1947 {
1948         ParticleSystem **psys = sphdata->psys;
1949         SPHFluidSettings *fluid = psys[0]->part->fluid;
1950         /* 4.0 seems to be a pretty good value */
1951         float interaction_radius  = fluid->radius * (fluid->flag & SPH_FAC_RADIUS ? 4.0f * psys[0]->part->size : 1.0f);
1952         SPHRangeData pfr;
1953         float data[2];
1954
1955         data[0] = 0;
1956         data[1] = 0;
1957         pfr.data = data;
1958         pfr.h = interaction_radius * sphdata->hfac;
1959         pfr.pa = pa;
1960         pfr.mass = sphdata->mass;
1961
1962         sph_evaluate_func( NULL, psys, pa->state.co, &pfr, interaction_radius, sphclassical_density_accum_cb);
1963         pa->sphdensity = min_ff(max_ff(data[0], fluid->rest_density * 0.9f), fluid->rest_density * 1.1f);
1964 }
1965
1966 void psys_sph_init(ParticleSimulationData *sim, SPHData *sphdata)
1967 {
1968         ParticleTarget *pt;
1969         int i;
1970
1971         // Add other coupled particle systems.
1972         sphdata->psys[0] = sim->psys;
1973         for (i=1, pt=sim->psys->targets.first; i<10; i++, pt=(pt?pt->next:NULL))
1974                 sphdata->psys[i] = pt ? psys_get_target_system(sim->ob, pt) : NULL;
1975
1976         if (psys_uses_gravity(sim))
1977                 sphdata->gravity = sim->scene->physics_settings.gravity;
1978         else
1979                 sphdata->gravity = NULL;
1980         sphdata->eh = sph_springhash_build(sim->psys);
1981
1982         // These per-particle values should be overridden later, but just for
1983         // completeness we give them default values now.
1984         sphdata->pa = NULL;
1985         sphdata->mass = 1.0f;
1986
1987         if (sim->psys->part->fluid->solver == SPH_SOLVER_DDR) {
1988                 sphdata->force_cb = sph_force_cb;
1989                 sphdata->density_cb = sph_density_accum_cb;
1990                 sphdata->hfac = 1.0f;
1991         }
1992         else {
1993                 /* SPH_SOLVER_CLASSICAL */
1994                 sphdata->force_cb = sphclassical_force_cb;
1995                 sphdata->density_cb = sphclassical_density_accum_cb;
1996                 sphdata->hfac = 0.5f;
1997         }
1998
1999 }
2000
2001 void psys_sph_finalise(SPHData *sphdata)
2002 {
2003         if (sphdata->eh) {
2004                 BLI_edgehash_free(sphdata->eh, NULL);
2005                 sphdata->eh = NULL;
2006         }
2007 }
2008 /* Sample the density field at a point in space. */
2009 void psys_sph_density(BVHTree *tree, SPHData *sphdata, float co[3], float vars[2])
2010 {
2011         ParticleSystem **psys = sphdata->psys;
2012         SPHFluidSettings *fluid = psys[0]->part->fluid;
2013         /* 4.0 seems to be a pretty good value */
2014         float interaction_radius  = fluid->radius * (fluid->flag & SPH_FAC_RADIUS ? 4.0f * psys[0]->part->size : 1.0f);
2015         SPHRangeData pfr;
2016         float density[2];
2017
2018         density[0] = density[1] = 0.0f;
2019         pfr.data = density;
2020         pfr.h = interaction_radius * sphdata->hfac;
2021         pfr.mass = sphdata->mass;
2022
2023         sph_evaluate_func(tree, psys, co, &pfr, interaction_radius, sphdata->density_cb);
2024
2025         vars[0] = pfr.data[0];
2026         vars[1] = pfr.data[1];
2027 }
2028
2029 static void sph_integrate(ParticleSimulationData *sim, ParticleData *pa, float dfra, SPHData *sphdata)
2030 {
2031         ParticleSettings *part = sim->psys->part;
2032         // float timestep = psys_get_timestep(sim); // UNUSED
2033         float pa_mass = part->mass * (part->flag & PART_SIZEMASS ? pa->size : 1.f);
2034         float dtime = dfra*psys_get_timestep(sim);
2035         // int steps = 1; // UNUSED
2036         float effector_acceleration[3];
2037
2038         sphdata->pa = pa;
2039         sphdata->mass = pa_mass;
2040         sphdata->pass = 0;
2041         //sphdata.element_size and sphdata.flow are set in the callback.
2042
2043         /* restore previous state and treat gravity & effectors as external acceleration*/
2044         sub_v3_v3v3(effector_acceleration, pa->state.vel, pa->prev_state.vel);
2045         mul_v3_fl(effector_acceleration, 1.f/dtime);
2046
2047         copy_particle_key(&pa->state, &pa->prev_state, 0);
2048
2049         integrate_particle(part, pa, dtime, effector_acceleration, sphdata->force_cb, sphdata);
2050 }
2051
2052 /************************************************/
2053 /*                      Basic physics                                           */
2054 /************************************************/
2055 typedef struct EfData {
2056         ParticleTexture ptex;
2057         ParticleSimulationData *sim;
2058         ParticleData *pa;
2059 } EfData;
2060 static void basic_force_cb(void *efdata_v, ParticleKey *state, float *force, float *impulse)
2061 {
2062         EfData *efdata = (EfData *)efdata_v;
2063         ParticleSimulationData *sim = efdata->sim;
2064         ParticleSettings *part = sim->psys->part;
2065         ParticleData *pa = efdata->pa;
2066         EffectedPoint epoint;
2067         RNG *rng = sim->rng;
2068
2069         /* add effectors */
2070         pd_point_from_particle(efdata->sim, efdata->pa, state, &epoint);
2071         if (part->type != PART_HAIR || part->effector_weights->flag & EFF_WEIGHT_DO_HAIR)
2072                 BKE_effectors_apply(sim->psys->effectors, sim->colliders, part->effector_weights, &epoint, force, impulse);
2073
2074         mul_v3_fl(force, efdata->ptex.field);
2075         mul_v3_fl(impulse, efdata->ptex.field);
2076
2077         /* calculate air-particle interaction */
2078         if (part->dragfac != 0.0f)
2079                 madd_v3_v3fl(force, state->vel, -part->dragfac * pa->size * pa->size * len_v3(state->vel));
2080
2081         /* brownian force */
2082         if (part->brownfac != 0.0f) {
2083                 force[0] += (BLI_rng_get_float(rng)-0.5f) * part->brownfac;
2084                 force[1] += (BLI_rng_get_float(rng)-0.5f) * part->brownfac;
2085                 force[2] += (BLI_rng_get_float(rng)-0.5f) * part->brownfac;
2086         }
2087
2088         if (part->flag & PART_ROT_DYN && epoint.ave)
2089                 copy_v3_v3(pa->state.ave, epoint.ave);
2090 }
2091 /* gathers all forces that effect particles and calculates a new state for the particle */
2092 static void basic_integrate(ParticleSimulationData *sim, int p, float dfra, float cfra)
2093 {
2094         ParticleSettings *part = sim->psys->part;
2095         ParticleData *pa = sim->psys->particles + p;
2096         ParticleKey tkey;
2097         float dtime=dfra*psys_get_timestep(sim), time;
2098         float *gravity = NULL, gr[3];
2099         EfData efdata;
2100
2101         psys_get_texture(sim, pa, &efdata.ptex, PAMAP_PHYSICS, cfra);
2102
2103         efdata.pa = pa;
2104         efdata.sim = sim;
2105
2106         /* add global acceleration (gravitation) */
2107         if (psys_uses_gravity(sim) &&
2108                 /* normal gravity is too strong for hair so it's disabled by default */
2109                 (part->type != PART_HAIR || part->effector_weights->flag & EFF_WEIGHT_DO_HAIR))
2110         {
2111                 zero_v3(gr);
2112                 madd_v3_v3fl(gr, sim->scene->physics_settings.gravity, part->effector_weights->global_gravity * efdata.ptex.gravity);
2113                 gravity = gr;
2114         }
2115
2116         /* maintain angular velocity */
2117         copy_v3_v3(pa->state.ave, pa->prev_state.ave);
2118
2119         integrate_particle(part, pa, dtime, gravity, basic_force_cb, &efdata);
2120
2121         /* damp affects final velocity */
2122         if (part->dampfac != 0.f)
2123                 mul_v3_fl(pa->state.vel, 1.f - part->dampfac * efdata.ptex.damp * 25.f * dtime);
2124
2125         //copy_v3_v3(pa->state.ave, states->ave);
2126
2127         /* finally we do guides */
2128         time=(cfra-pa->time)/pa->lifetime;
2129         CLAMP(time, 0.0f, 1.0f);
2130
2131         copy_v3_v3(tkey.co,pa->state.co);
2132         copy_v3_v3(tkey.vel,pa->state.vel);
2133         tkey.time=pa->state.time;
2134
2135         if (part->type != PART_HAIR) {
2136                 if (do_guides(sim->depsgraph, sim->psys->part, sim->psys->effectors, &tkey, p, time)) {
2137                         copy_v3_v3(pa->state.co,tkey.co);
2138                         /* guides don't produce valid velocity */
2139                         sub_v3_v3v3(pa->state.vel, tkey.co, pa->prev_state.co);
2140                         mul_v3_fl(pa->state.vel,1.0f/dtime);
2141                         pa->state.time=tkey.time;
2142                 }
2143         }
2144 }
2145 static void basic_rotate(ParticleSettings *part, ParticleData *pa, float dfra, float timestep)
2146 {
2147         float rotfac, rot1[4], rot2[4] = {1.0,0.0,0.0,0.0}, dtime=dfra*timestep, extrotfac;
2148
2149         if ((part->flag & PART_ROTATIONS) == 0) {
2150                 unit_qt(pa->state.rot);
2151                 return;
2152         }
2153
2154         if (part->flag & PART_ROT_DYN) {
2155                 extrotfac = len_v3(pa->state.ave);
2156         }
2157         else {
2158                 extrotfac = 0.0f;
2159         }
2160
2161         if ((part->flag & PART_ROT_DYN) && ELEM(part->avemode, PART_AVE_VELOCITY, PART_AVE_HORIZONTAL, PART_AVE_VERTICAL)) {
2162                 float angle;
2163                 float len1 = len_v3(pa->prev_state.vel);
2164                 float len2 = len_v3(pa->state.vel);
2165                 float vec[3];
2166
2167                 if (len1 == 0.0f || len2 == 0.0f) {
2168                         zero_v3(pa->state.ave);
2169                 }
2170                 else {
2171                         cross_v3_v3v3(pa->state.ave, pa->prev_state.vel, pa->state.vel);
2172                         normalize_v3(pa->state.ave);
2173                         angle = dot_v3v3(pa->prev_state.vel, pa->state.vel) / (len1 * len2);
2174                         mul_v3_fl(pa->state.ave, saacos(angle) / dtime);
2175                 }
2176
2177                 get_angular_velocity_vector(part->avemode, &pa->state, vec);
2178                 axis_angle_to_quat(rot2, vec, dtime*part->avefac);
2179         }
2180
2181         rotfac = len_v3(pa->state.ave);
2182         if (rotfac == 0.0f || (part->flag & PART_ROT_DYN)==0 || extrotfac == 0.0f) {
2183                 unit_qt(rot1);
2184         }
2185         else {
2186                 axis_angle_to_quat(rot1,pa->state.ave,rotfac*dtime);
2187         }
2188         mul_qt_qtqt(pa->state.rot,rot1,pa->prev_state.rot);
2189         mul_qt_qtqt(pa->state.rot,rot2,pa->state.rot);
2190
2191         /* keep rotation quat in good health */
2192         normalize_qt(pa->state.rot);
2193 }
2194
2195 /************************************************
2196  * Collisions
2197  *
2198  * The algorithm is roughly:
2199  *  1. Use a BVH tree to search for faces that a particle may collide with.
2200  *  2. Use Newton's method to find the exact time at which the collision occurs.
2201  *     https://en.wikipedia.org/wiki/Newton's_method
2202  *
2203  ************************************************/
2204 #define COLLISION_MIN_RADIUS 0.001f
2205 #define COLLISION_MIN_DISTANCE 0.0001f
2206 #define COLLISION_ZERO 0.00001f
2207 #define COLLISION_INIT_STEP 0.00008f
2208 typedef float (*NRDistanceFunc)(float *p, float radius, ParticleCollisionElement *pce, float *nor);
2209 static float nr_signed_distance_to_plane(float *p, float radius, ParticleCollisionElement *pce, float *nor)
2210 {
2211         float p0[3], e1[3], e2[3], d;
2212
2213         sub_v3_v3v3(e1, pce->x1, pce->x0);
2214         sub_v3_v3v3(e2, pce->x2, pce->x0);
2215         sub_v3_v3v3(p0, p, pce->x0);
2216
2217         cross_v3_v3v3(nor, e1, e2);
2218         normalize_v3(nor);
2219
2220         d = dot_v3v3(p0, nor);
2221
2222         if (pce->inv_nor == -1) {
2223                 if (d < 0.f)
2224                         pce->inv_nor = 1;
2225                 else
2226                         pce->inv_nor = 0;
2227         }
2228
2229         if (pce->inv_nor == 1) {
2230                 negate_v3(nor);
2231                 d = -d;
2232         }
2233
2234         return d - radius;
2235 }
2236 static float nr_distance_to_edge(float *p, float radius, ParticleCollisionElement *pce, float *UNUSED(nor))
2237 {
2238         float v0[3], v1[3], v2[3], c[3];
2239
2240         sub_v3_v3v3(v0, pce->x1, pce->x0);
2241         sub_v3_v3v3(v1, p, pce->x0);
2242         sub_v3_v3v3(v2, p, pce->x1);
2243
2244         cross_v3_v3v3(c, v1, v2);
2245
2246         return fabsf(len_v3(c)/len_v3(v0)) - radius;
2247 }
2248 static float nr_distance_to_vert(float *p, float radius, ParticleCollisionElement *pce, float *UNUSED(nor))
2249 {
2250         return len_v3v3(p, pce->x0) - radius;
2251 }
2252 static void collision_interpolate_element(ParticleCollisionElement *pce, float t, float fac, ParticleCollision *col)
2253 {
2254         /* t is the current time for newton rhapson */
2255         /* fac is the starting factor for current collision iteration */
2256         /* the col->fac's are factors for the particle subframe step start and end during collision modifier step */
2257         float f = fac + t*(1.f-fac);
2258         float mul = col->fac1 + f * (col->fac2-col->fac1);
2259         if (pce->tot > 0) {
2260                 madd_v3_v3v3fl(pce->x0, pce->x[0], pce->v[0], mul);
2261
2262                 if (pce->tot > 1) {
2263                         madd_v3_v3v3fl(pce->x1, pce->x[1], pce->v[1], mul);
2264
2265                         if (pce->tot > 2)
2266                                 madd_v3_v3v3fl(pce->x2, pce->x[2], pce->v[2], mul);
2267                 }
2268         }
2269 }
2270 static void collision_point_velocity(ParticleCollisionElement *pce)
2271 {
2272         float v[3];
2273
2274         copy_v3_v3(pce->vel, pce->v[0]);
2275
2276         if (pce->tot > 1) {
2277                 sub_v3_v3v3(v, pce->v[1], pce->v[0]);
2278                 madd_v3_v3fl(pce->vel, v, pce->uv[0]);
2279
2280                 if (pce->tot > 2) {
2281                         sub_v3_v3v3(v, pce->v[2], pce->v[0]);
2282                         madd_v3_v3fl(pce->vel, v, pce->uv[1]);
2283                 }
2284         }
2285 }
2286 static float collision_point_distance_with_normal(float p[3], ParticleCollisionElement *pce, float fac, ParticleCollision *col, float *nor)
2287 {
2288         if (fac >= 0.f)
2289                 collision_interpolate_element(pce, 0.f, fac, col);
2290
2291         switch (pce->tot) {
2292                 case 1:
2293                 {
2294                         sub_v3_v3v3(nor, p, pce->x0);
2295                         return normalize_v3(nor);
2296                 }
2297                 case 2:
2298                 {
2299                         float u, e[3], vec[3];
2300                         sub_v3_v3v3(e, pce->x1, pce->x0);
2301                         sub_v3_v3v3(vec, p, pce->x0);
2302                         u = dot_v3v3(vec, e) / dot_v3v3(e, e);
2303
2304                         madd_v3_v3v3fl(nor, vec, e, -u);
2305                         return normalize_v3(nor);
2306                 }
2307                 case 3:
2308                         return nr_signed_distance_to_plane(p, 0.f, pce, nor);
2309         }
2310         return 0;
2311 }
2312 static void collision_point_on_surface(float p[3], ParticleCollisionElement *pce, float fac, ParticleCollision *col, float *co)
2313 {
2314         collision_interpolate_element(pce, 0.f, fac, col);
2315
2316         switch (pce->tot) {
2317                 case 1:
2318                 {
2319                         sub_v3_v3v3(co, p, pce->x0);
2320                         normalize_v3(co);
2321                         madd_v3_v3v3fl(co, pce->x0, co, col->radius);
2322                         break;
2323                 }
2324                 case 2:
2325                 {
2326                         float u, e[3], vec[3], nor[3];
2327                         sub_v3_v3v3(e, pce->x1, pce->x0);
2328                         sub_v3_v3v3(vec, p, pce->x0);
2329                         u = dot_v3v3(vec, e) / dot_v3v3(e, e);
2330
2331                         madd_v3_v3v3fl(nor, vec, e, -u);
2332                         normalize_v3(nor);
2333
2334                         madd_v3_v3v3fl(co, pce->x0, e, pce->uv[0]);
2335                         madd_v3_v3fl(co, nor, col->radius);
2336                         break;
2337                 }
2338                 case 3:
2339                 {
2340                         float p0[3], e1[3], e2[3], nor[3];
2341
2342                         sub_v3_v3v3(e1, pce->x1, pce->x0);
2343                         sub_v3_v3v3(e2, pce->x2, pce->x0);
2344                         sub_v3_v3v3(p0, p, pce->x0);
2345
2346                         cross_v3_v3v3(nor, e1, e2);
2347                         normalize_v3(nor);
2348
2349                         if (pce->inv_nor == 1)
2350                                 negate_v3(nor);
2351
2352                         madd_v3_v3v3fl(co, pce->x0, nor, col->radius);
2353                         madd_v3_v3fl(co, e1, pce->uv[0]);
2354                         madd_v3_v3fl(co, e2, pce->uv[1]);
2355                         break;
2356                 }
2357         }
2358 }
2359 /* find first root in range [0-1] starting from 0 */
2360 static float collision_newton_rhapson(ParticleCollision *col, float radius, ParticleCollisionElement *pce, NRDistanceFunc distance_func)
2361 {
2362         float t0, t1, dt_init, d0, d1, dd, n[3];
2363         int iter;
2364
2365         pce->inv_nor = -1;
2366
2367         if (col->inv_total_time > 0.0f) {
2368                 /* Initial step size should be small, but not too small or floating point
2369                  * precision errors will appear. - z0r */
2370                 dt_init = COLLISION_INIT_STEP * col->inv_total_time;
2371         }
2372         else {
2373                 dt_init = 0.001f;
2374         }
2375
2376         /* start from the beginning */
2377         t0 = 0.f;
2378         collision_interpolate_element(pce, t0, col->f, col);
2379         d0 = distance_func(col->co1, radius, pce, n);
2380         t1 = dt_init;
2381         d1 = 0.f;
2382
2383         for (iter=0; iter<10; iter++) {//, itersum++) {
2384                 /* get current location */
2385                 collision_interpolate_element(pce, t1, col->f, col);
2386                 interp_v3_v3v3(pce->p, col->co1, col->co2, t1);
2387
2388                 d1 = distance_func(pce->p, radius, pce, n);
2389
2390                 /* particle already inside face, so report collision */
2391                 if (iter == 0 && d0 < 0.f && d0 > -radius) {
2392                         copy_v3_v3(pce->p, col->co1);
2393                         copy_v3_v3(pce->nor, n);
2394                         pce->inside = 1;
2395                         return 0.f;
2396                 }
2397
2398                 /* Zero gradient (no movement relative to element). Can't step from
2399                  * here. */
2400                 if (d1 == d0) {
2401                         /* If first iteration, try from other end where the gradient may be
2402                          * greater. Note: code duplicated below. */
2403                         if (iter == 0) {
2404                                 t0 = 1.f;
2405                                 collision_interpolate_element(pce, t0, col->f, col);
2406                                 d0 = distance_func(col->co2, radius, pce, n);
2407                                 t1 = 1.0f - dt_init;
2408                                 d1 = 0.f;
2409                                 continue;
2410                         }
2411                         else
2412                                 return -1.f;
2413                 }
2414
2415                 dd = (t1-t0)/(d1-d0);
2416
2417                 t0 = t1;
2418                 d0 = d1;
2419
2420                 t1 -= d1*dd;
2421
2422                 /* Particle moving away from plane could also mean a strangely rotating
2423                  * face, so check from end. Note: code duplicated above. */
2424                 if (iter == 0 && t1 < 0.f) {
2425                         t0 = 1.f;
2426                         collision_interpolate_element(pce, t0, col->f, col);
2427                         d0 = distance_func(col->co2, radius, pce, n);
2428                         t1 = 1.0f - dt_init;
2429                         d1 = 0.f;
2430                         continue;
2431                 }
2432                 else if (iter == 1 && (t1 < -COLLISION_ZERO || t1 > 1.f))
2433                         return -1.f;
2434
2435                 if (d1 <= COLLISION_ZERO && d1 >= -COLLISION_ZERO) {
2436                         if (t1 >= -COLLISION_ZERO && t1 <= 1.f) {
2437                                 if (distance_func == nr_signed_distance_to_plane)
2438                                         copy_v3_v3(pce->nor, n);
2439
2440                                 CLAMP(t1, 0.f, 1.f);
2441
2442                                 return t1;
2443                         }
2444                         else
2445                                 return -1.f;
2446                 }
2447         }
2448         return -1.0;
2449 }
2450 static int collision_sphere_to_tri(ParticleCollision *col, float radius, ParticleCollisionElement *pce, float *t)
2451 {
2452         ParticleCollisionElement *result = &col->pce;
2453         float ct, u, v;
2454
2455         pce->inv_nor = -1;
2456         pce->inside = 0;
2457
2458         ct = collision_newton_rhapson(col, radius, pce, nr_signed_distance_to_plane);
2459
2460         if (ct >= 0.f && ct < *t && (result->inside==0 || pce->inside==1) ) {
2461                 float e1[3], e2[3], p0[3];
2462                 float e1e1, e1e2, e1p0, e2e2, e2p0, inv;
2463
2464                 sub_v3_v3v3(e1, pce->x1, pce->x0);
2465                 sub_v3_v3v3(e2, pce->x2, pce->x0);
2466                 /* XXX: add radius correction here? */
2467                 sub_v3_v3v3(p0, pce->p, pce->x0);
2468
2469                 e1e1 = dot_v3v3(e1, e1);
2470                 e1e2 = dot_v3v3(e1, e2);
2471                 e1p0 = dot_v3v3(e1, p0);
2472                 e2e2 = dot_v3v3(e2, e2);
2473                 e2p0 = dot_v3v3(e2, p0);
2474
2475                 inv = 1.f/(e1e1 * e2e2 - e1e2 * e1e2);
2476                 u = (e2e2 * e1p0 - e1e2 * e2p0) * inv;
2477                 v = (e1e1 * e2p0 - e1e2 * e1p0) * inv;
2478
2479                 if (u>=0.f && u<=1.f && v>=0.f && u+v<=1.f) {
2480                         *result = *pce;
2481
2482                         /* normal already calculated in pce */
2483
2484                         result->uv[0] = u;
2485                         result->uv[1] = v;
2486
2487                         *t = ct;
2488                         return 1;
2489                 }
2490         }
2491         return 0;
2492 }
2493 static int collision_sphere_to_edges(ParticleCollision *col, float radius, ParticleCollisionElement *pce, float *t)
2494 {
2495         ParticleCollisionElement edge[3], *cur = NULL, *hit = NULL;
2496         ParticleCollisionElement *result = &col->pce;
2497
2498         float ct;
2499         int i;
2500
2501         for (i=0; i<3; i++) {
2502                 cur = edge+i;
2503                 cur->x[0] = pce->x[i]; cur->x[1] = pce->x[(i+1)%3];
2504                 cur->v[0] = pce->v[i]; cur->v[1] = pce->v[(i+1)%3];
2505                 cur->tot = 2;
2506                 cur->inside = 0;
2507
2508                 ct = collision_newton_rhapson(col, radius, cur, nr_distance_to_edge);
2509
2510                 if (ct >= 0.f && ct < *t) {
2511                         float u, e[3], vec[3];
2512
2513                         sub_v3_v3v3(e, cur->x1, cur->x0);
2514                         sub_v3_v3v3(vec, cur->p, cur->x0);
2515                         u = dot_v3v3(vec, e) / dot_v3v3(e, e);
2516
2517                         if (u < 0.f || u > 1.f)
2518                                 break;
2519
2520                         *result = *cur;
2521
2522                         madd_v3_v3v3fl(result->nor, vec, e, -u);
2523                         normalize_v3(result->nor);
2524
2525                         result->uv[0] = u;
2526
2527
2528                         hit = cur;
2529                         *t = ct;
2530                 }
2531
2532         }
2533
2534         return hit != NULL;
2535 }
2536 static int collision_sphere_to_verts(ParticleCollision *col, float radius, ParticleCollisionElement *pce, float *t)
2537 {
2538         ParticleCollisionElement vert[3], *cur = NULL, *hit = NULL;
2539         ParticleCollisionElement *result = &col->pce;
2540
2541         float ct;
2542         int i;
2543
2544         for (i=0; i<3; i++) {
2545                 cur = vert+i;
2546                 cur->x[0] = pce->x[i];
2547                 cur->v[0] = pce->v[i];
2548                 cur->tot = 1;
2549                 cur->inside = 0;
2550
2551                 ct = collision_newton_rhapson(col, radius, cur, nr_distance_to_vert);
2552
2553                 if (ct >= 0.f && ct < *t) {
2554                         *result = *cur;
2555
2556                         sub_v3_v3v3(result->nor, cur->p, cur->x0);
2557                         normalize_v3(result->nor);
2558
2559                         hit = cur;
2560                         *t = ct;
2561                 }
2562
2563         }
2564
2565         return hit != NULL;
2566 }
2567 /* Callback for BVHTree near test */
2568 void BKE_psys_collision_neartest_cb(void *userdata, int index, const BVHTreeRay *ray, BVHTreeRayHit *hit)
2569 {
2570         ParticleCollision *col = (ParticleCollision *) userdata;
2571         ParticleCollisionElement pce;
2572         const MVertTri *vt = &col->md->tri[index];
2573         MVert *x = col->md->x;
2574         MVert *v = col->md->current_v;
2575         float t = hit->dist/col->original_ray_length;
2576         int collision = 0;
2577
2578         pce.x[0] = x[vt->tri[0]].co;
2579         pce.x[1] = x[vt->tri[1]].co;
2580         pce.x[2] = x[vt->tri[2]].co;
2581
2582         pce.v[0] = v[vt->tri[0]].co;
2583         pce.v[1] = v[vt->tri[1]].co;
2584         pce.v[2] = v[vt->tri[2]].co;
2585
2586         pce.tot = 3;
2587         pce.inside = 0;
2588         pce.index = index;
2589
2590         collision = collision_sphere_to_tri(col, ray->radius, &pce, &t);
2591         if (col->pce.inside == 0) {
2592                 collision += collision_sphere_to_edges(col, ray->radius, &pce, &t);
2593                 collision += collision_sphere_to_verts(col, ray->radius, &pce, &t);
2594         }
2595
2596         if (collision) {
2597                 hit->dist = col->original_ray_length * t;
2598                 hit->index = index;
2599
2600                 collision_point_velocity(&col->pce);
2601
2602                 col->hit = col->current;
2603         }
2604 }
2605 static int collision_detect(ParticleData *pa, ParticleCollision *col, BVHTreeRayHit *hit, ListBase *colliders)
2606 {
2607         const int raycast_flag = BVH_RAYCAST_DEFAULT & ~(BVH_RAYCAST_WATERTIGHT);
2608         ColliderCache *coll;
2609         float ray_dir[3];
2610
2611         if (BLI_listbase_is_empty(colliders))
2612                 return 0;
2613
2614         sub_v3_v3v3(ray_dir, col->co2, col->co1);
2615         hit->index = -1;
2616         hit->dist = col->original_ray_length = normalize_v3(ray_dir);
2617         col->pce.inside = 0;
2618
2619         /* even if particle is stationary we want to check for moving colliders */
2620         /* if hit.dist is zero the bvhtree_ray_cast will just ignore everything */
2621         if (hit->dist == 0.0f)
2622                 hit->dist = col->original_ray_length = 0.000001f;
2623
2624         for (coll = colliders->first; coll; coll=coll->next) {
2625                 /* for boids: don't check with current ground object; also skip if permeated */
2626                 bool skip = false;
2627
2628                 for (int i = 0; i < col->skip_count; i++) {
2629                         if (coll->ob == col->skip[i]) {
2630                                 skip = true;
2631                                 break;
2632                         }
2633                 }
2634
2635                 if (skip)
2636                         continue;
2637
2638                 /* particles should not collide with emitter at birth */
2639                 if (coll->ob == col->emitter && pa->time < col->cfra && pa->time >= col->old_cfra)
2640                         continue;
2641
2642                 col->current = coll->ob;
2643                 col->md = coll->collmd;
2644                 col->fac1 = (col->old_cfra - coll->collmd->time_x) / (coll->collmd->time_xnew - coll->collmd->time_x);
2645                 col->fac2 = (col->cfra - coll->collmd->time_x) / (coll->collmd->time_xnew - coll->collmd->time_x);
2646
2647                 if (col->md && col->md->bvhtree) {
2648                         BLI_bvhtree_ray_cast_ex(
2649                                 col->md->bvhtree, col->co1, ray_dir, col->radius, hit,
2650                                 BKE_psys_collision_neartest_cb, col, raycast_flag);
2651                 }
2652         }
2653
2654         return hit->index >= 0;
2655 }
2656 static int collision_response(ParticleSimulationData *sim, ParticleData *pa, ParticleCollision *col, BVHTreeRayHit *hit, int kill, int dynamic_rotation)
2657 {
2658         ParticleCollisionElement *pce = &col->pce;
2659         PartDeflect *pd = col->hit->pd;
2660         RNG *rng = sim->rng;
2661         /* point of collision */
2662         float co[3];
2663         /* location factor of collision between this iteration */
2664         float x = hit->dist/col->original_ray_length;
2665         /* time factor of collision between timestep */
2666         float f = col->f + x * (1.0f - col->f);
2667         /* time since previous collision (in seconds) */
2668         float dt1 = (f - col->f) * col->total_time;
2669         /* time left after collision (in seconds) */
2670         float dt2 = (1.0f - f) * col->total_time;
2671         /* did particle pass through the collision surface? */
2672         int through = (BLI_rng_get_float(rng) < pd->pdef_perm) ? 1 : 0;
2673
2674         /* calculate exact collision location */
2675         interp_v3_v3v3(co, col->co1, col->co2, x);
2676
2677         /* particle dies in collision */
2678         if (through == 0 && (kill || pd->flag & PDEFLE_KILL_PART)) {
2679                 pa->alive = PARS_DYING;
2680                 pa->dietime = col->old_cfra + (col->cfra - col->old_cfra) * f;
2681
2682                 copy_v3_v3(pa->state.co, co);
2683                 interp_v3_v3v3(pa->state.vel, pa->prev_state.vel, pa->state.vel, f);
2684                 interp_qt_qtqt(pa->state.rot, pa->prev_state.rot, pa->state.rot, f);
2685                 interp_v3_v3v3(pa->state.ave, pa->prev_state.ave, pa->state.ave, f);
2686
2687                 /* particle is dead so we don't need to calculate further */
2688                 return 0;
2689         }
2690         /* figure out velocity and other data after collision */
2691         else {
2692                 /* velocity directly before collision to be modified into velocity directly after collision */
2693                 float v0[3];
2694                 /* normal component of v0 */
2695                 float v0_nor[3];
2696                 /* tangential component of v0 */
2697                 float v0_tan[3];
2698                 /* tangential component of collision surface velocity */
2699                 float vc_tan[3];
2700                 float v0_dot, vc_dot;
2701                 float damp = pd->pdef_damp + pd->pdef_rdamp * 2 * (BLI_rng_get_float(rng) - 0.5f);
2702                 float frict = pd->pdef_frict + pd->pdef_rfrict * 2 * (BLI_rng_get_float(rng) - 0.5f);
2703                 float distance, nor[3], dot;
2704
2705                 CLAMP(damp,0.0f, 1.0f);
2706                 CLAMP(frict,0.0f, 1.0f);
2707
2708                 /* get exact velocity right before collision */
2709                 madd_v3_v3v3fl(v0, col->ve1, col->acc, dt1);
2710
2711                 /* convert collider velocity from 1/framestep to 1/s TODO: here we assume 1 frame step for collision modifier */
2712                 mul_v3_fl(pce->vel, col->inv_timestep);
2713
2714                 /* calculate tangential particle velocity */
2715                 v0_dot = dot_v3v3(pce->nor, v0);
2716                 madd_v3_v3v3fl(v0_tan, v0, pce->nor, -v0_dot);
2717
2718                 /* calculate tangential collider velocity */
2719                 vc_dot = dot_v3v3(pce->nor, pce->vel);
2720                 madd_v3_v3v3fl(vc_tan, pce->vel, pce->nor, -vc_dot);
2721
2722                 /* handle friction effects (tangential and angular velocity) */
2723                 if (frict > 0.0f) {
2724                         /* angular <-> linear velocity */
2725                         if (dynamic_rotation) {
2726                                 float vr_tan[3], v1_tan[3], ave[3];
2727
2728                                 /* linear velocity of particle surface */
2729                                 cross_v3_v3v3(vr_tan, pce->nor, pa->state.ave);
2730                                 mul_v3_fl(vr_tan, pa->size);
2731
2732                                 /* change to coordinates that move with the collision plane */
2733                                 sub_v3_v3v3(v1_tan, v0_tan, vc_tan);
2734
2735                                 /* The resulting velocity is a weighted average of particle cm & surface
2736                                  * velocity. This weight (related to particle's moment of inertia) could
2737                                  * be made a parameter for angular <-> linear conversion.
2738                                  */
2739                                 madd_v3_v3fl(v1_tan, vr_tan, -0.4);
2740                                 mul_v3_fl(v1_tan, 1.0f/1.4f); /* 1/(1+0.4) */
2741
2742                                 /* rolling friction is around 0.01 of sliding friction
2743                                  * (could be made a parameter) */
2744                                 mul_v3_fl(v1_tan, 1.0f - 0.01f * frict);
2745
2746                                 /* surface_velocity is opposite to cm velocity */
2747                                 negate_v3_v3(vr_tan, v1_tan);
2748
2749                                 /* get back to global coordinates */
2750                                 add_v3_v3(v1_tan, vc_tan);
2751
2752                                 /* convert to angular velocity*/
2753                                 cross_v3_v3v3(ave, vr_tan, pce->nor);
2754                                 mul_v3_fl(ave, 1.0f/MAX2(pa->size, 0.001f));
2755
2756                                 /* only friction will cause change in linear & angular velocity */
2757                                 interp_v3_v3v3(pa->state.ave, pa->state.ave, ave, frict);
2758                                 interp_v3_v3v3(v0_tan, v0_tan, v1_tan, frict);
2759                         }
2760                         else {
2761                                 /* just basic friction (unphysical due to the friction model used in Blender) */
2762                                 interp_v3_v3v3(v0_tan, v0_tan, vc_tan, frict);
2763                         }
2764                 }
2765
2766                 /* stickiness was possibly added before, so cancel that before calculating new normal velocity */
2767                 /* otherwise particles go flying out of the surface because of high reversed sticky velocity */
2768                 if (v0_dot < 0.0f) {
2769                         v0_dot += pd->pdef_stickness;
2770                         if (v0_dot > 0.0f)
2771                                 v0_dot = 0.0f;
2772                 }
2773
2774                 /* damping and flipping of velocity around normal */
2775                 v0_dot *= 1.0f - damp;
2776                 vc_dot *= through ? damp : 1.0f;
2777
2778                 /* calculate normal particle velocity */
2779                 /* special case for object hitting the particle from behind */
2780                 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)))
2781                         mul_v3_v3fl(v0_nor, pce->nor, vc_dot);
2782                 else if (v0_dot > 0.f)
2783                         mul_v3_v3fl(v0_nor, pce->nor, vc_dot + v0_dot);
2784                 else
2785                         mul_v3_v3fl(v0_nor, pce->nor, vc_dot + (through ? 1.0f : -1.0f) * v0_dot);
2786
2787                 /* combine components together again */
2788                 add_v3_v3v3(v0, v0_nor, v0_tan);
2789
2790                 if (col->boid) {
2791                         /* keep boids above ground */
2792                         BoidParticle *bpa = pa->boid;
2793                         if (bpa->data.mode == eBoidMode_OnLand || co[2] <= col->boid_z) {
2794                                 co[2] = col->boid_z;
2795                                 v0[2] = 0.0f;
2796                         }
2797                 }
2798
2799                 /* re-apply acceleration to final location and velocity */
2800                 madd_v3_v3v3fl(pa->state.co, co, v0, dt2);
2801                 madd_v3_v3fl(pa->state.co, col->acc, 0.5f*dt2*dt2);
2802                 madd_v3_v3v3fl(pa->state.vel, v0, col->acc, dt2);
2803
2804                 /* make sure particle stays on the right side of the surface */
2805                 if (!through) {
2806                         distance = collision_point_distance_with_normal(co, pce, -1.f, col, nor);
2807
2808                         if (distance < col->radius + COLLISION_MIN_DISTANCE)
2809                                 madd_v3_v3fl(co, nor, col->radius + COLLISION_MIN_DISTANCE - distance);
2810
2811                         dot = dot_v3v3(nor, v0);
2812                         if (dot < 0.f)
2813                                 madd_v3_v3fl(v0, nor, -dot);
2814
2815                         distance = collision_point_distance_with_normal(pa->state.co, pce, 1.f, col, nor);
2816
2817                         if (distance < col->radius + COLLISION_MIN_DISTANCE)
2818                                 madd_v3_v3fl(pa->state.co, nor, col->radius + COLLISION_MIN_DISTANCE - distance);
2819
2820                         dot = dot_v3v3(nor, pa->state.vel);
2821                         if (dot < 0.f)
2822                                 madd_v3_v3fl(pa->state.vel, nor, -dot);
2823                 }
2824
2825                 /* add stickiness to surface */
2826                 madd_v3_v3fl(pa->state.vel, pce->nor, -pd->pdef_stickness);
2827
2828                 /* set coordinates for next iteration */
2829                 copy_v3_v3(col->co1, co);
2830                 copy_v3_v3(col->co2, pa->state.co);
2831
2832                 copy_v3_v3(col->ve1, v0);
2833                 copy_v3_v3(col->ve2, pa->state.vel);
2834
2835                 col->f = f;
2836         }
2837
2838         /* if permeability random roll succeeded, disable collider for this sim step */
2839         if (through) {
2840                 col->skip[col->skip_count++] = col->hit;
2841         }
2842
2843         return 1;
2844 }
2845 static void collision_fail(ParticleData *pa, ParticleCollision *col)
2846 {
2847         /* final chance to prevent total failure, so stick to the surface and hope for the best */
2848         collision_point_on_surface(col->co1, &col->pce, 1.f, col, pa->state.co);
2849
2850         copy_v3_v3(pa->state.vel, col->pce.vel);
2851         mul_v3_fl(pa->state.vel, col->inv_timestep);
2852
2853
2854         /* printf("max iterations\n"); */
2855 }
2856
2857 /* Particle - Mesh collision detection and response
2858  * Features:
2859  * -friction and damping
2860  * -angular momentum <-> linear momentum
2861  * -high accuracy by re-applying particle acceleration after collision
2862  * -handles moving, rotating and deforming meshes
2863  * -uses Newton-Rhapson iteration to find the collisions
2864  * -handles spherical particles and (nearly) point like particles
2865  */
2866 static void collision_check(ParticleSimulationData *sim, int p, float dfra, float cfra)
2867 {
2868         ParticleSettings *part = sim->psys->part;
2869         ParticleData *pa = sim->psys->particles + p;
2870         ParticleCollision col;
2871         BVHTreeRayHit hit;
2872         int collision_count=0;
2873
2874         float timestep = psys_get_timestep(sim);
2875
2876         memset(&col, 0, sizeof(ParticleCollision));
2877
2878         col.total_time = timestep * dfra;
2879         col.inv_total_time = 1.0f/col.total_time;
2880         col.inv_timestep = 1.0f/timestep;
2881
2882         col.cfra = cfra;
2883         col.old_cfra = sim->psys->cfra;
2884
2885         /* get acceleration (from gravity, forcefields etc. to be re-applied in collision response) */
2886         sub_v3_v3v3(col.acc, pa->state.vel, pa->prev_state.vel);
2887         mul_v3_fl(col.acc, 1.f/col.total_time);
2888
2889         /* set values for first iteration */
2890         copy_v3_v3(col.co1, pa->prev_state.co);
2891         copy_v3_v3(col.co2, pa->state.co);
2892         copy_v3_v3(col.ve1, pa->prev_state.vel);
2893         copy_v3_v3(col.ve2, pa->state.vel);
2894         col.f = 0.0f;
2895
2896         col.radius = ((part->flag & PART_SIZE_DEFL) || (part->phystype == PART_PHYS_BOIDS)) ? pa->size : COLLISION_MIN_RADIUS;
2897
2898         /* override for boids */
2899         if (part->phystype == PART_PHYS_BOIDS && part->boids->options & BOID_ALLOW_LAND) {
2900                 col.boid = 1;
2901                 col.boid_z = pa->state.co[2];
2902                 col.skip[col.skip_count++] = pa->boid->ground;
2903         }
2904
2905         /* 10 iterations to catch multiple collisions */
2906         while (collision_count < PARTICLE_COLLISION_MAX_COLLISIONS) {
2907                 if (collision_detect(pa, &col, &hit, sim->colliders)) {
2908
2909                         collision_count++;
2910
2911                         if (collision_count == PARTICLE_COLLISION_MAX_COLLISIONS)
2912                                 collision_fail(pa, &col);
2913                         else if (collision_response(sim, pa, &col, &hit, part->flag & PART_DIE_ON_COL, part->flag & PART_ROT_DYN)==0)
2914                                 return;
2915                 }
2916                 else
2917                         return;
2918         }
2919 }
2920 /************************************************/
2921 /*                      Hair                                                            */
2922 /************************************************/
2923 /* check if path cache or children need updating and do it if needed */
2924 static void psys_update_path_cache(ParticleSimulationData *sim, float cfra, const bool use_render_params)
2925 {
2926         ParticleSystem *psys = sim->psys;
2927         ParticleSettings *part = psys->part;
2928         ParticleEditSettings *pset = &sim->scene->toolsettings->particle;
2929         int distr=0, alloc=0, skip=0;
2930
2931         if ((psys->part->childtype && psys->totchild != psys_get_tot_child(sim->scene, psys, use_render_params)) || psys->recalc&ID_RECALC_PSYS_RESET)
2932                 alloc=1;
2933
2934         if (alloc || psys->recalc&ID_RECALC_PSYS_CHILD || (psys->vgroup[PSYS_VG_DENSITY] && (sim->ob && sim->ob->mode & OB_MODE_WEIGHT_PAINT)))
2935                 distr=1;
2936
2937         if (distr) {
2938                 if (alloc)
2939                         realloc_particles(sim, sim->psys->totpart);
2940
2941                 if (psys_get_tot_child(sim->scene, psys, use_render_params)) {
2942                         /* don't generate children while computing the hair keys */
2943                         if (!(psys->part->type == PART_HAIR) || (psys->flag & PSYS_HAIR_DONE)) {
2944                                 distribute_particles(sim, PART_FROM_CHILD);
2945
2946                                 if (part->childtype==PART_CHILD_FACES && part->parents != 0.0f)
2947                                         psys_find_parents(sim, use_render_params);
2948                         }
2949                 }
2950                 else
2951                         psys_free_children(psys);
2952         }
2953
2954         if ((part->type==PART_HAIR || psys->flag&PSYS_KEYED || psys->pointcache->flag & PTCACHE_BAKED)==0)
2955                 skip = 1; /* only hair, keyed and baked stuff can have paths */
2956         else if (part->ren_as != PART_DRAW_PATH && !(part->type==PART_HAIR && ELEM(part->ren_as, PART_DRAW_OB, PART_DRAW_GR)))
2957                 skip = 1; /* particle visualization must be set as path */
2958         else if (DEG_get_mode(sim->depsgraph) != DAG_EVAL_RENDER) {
2959                 if (part->draw_as != PART_DRAW_REND)
2960                         skip = 1; /* draw visualization */
2961                 else if (psys->pointcache->flag & PTCACHE_BAKING)
2962                         skip = 1; /* no need to cache paths while baking dynamics */
2963
2964                 else if (psys_in_edit_mode(sim->depsgraph, psys)) {
2965                         if ((pset->flag & PE_DRAW_PART)==0)
2966                                 skip = 1;
2967                         else if (part->childtype==0 && (psys->flag & PSYS_HAIR_DYNAMICS && psys->pointcache->flag & PTCACHE_BAKED)==0)
2968                                 skip = 1; /* in edit mode paths are needed for child particles and dynamic hair */
2969                 }
2970         }
2971
2972
2973         /* particle instance modifier with "path" option need cached paths even if particle system doesn't */
2974         if (skip) {
2975                 FOREACH_SCENE_OBJECT_BEGIN(sim->scene, ob)
2976                 {
2977                         ModifierData *md = modifiers_findByType(ob, eModifierType_ParticleInstance);
2978                         if (md) {
2979                                 ParticleInstanceModifierData *pimd = (ParticleInstanceModifierData *)md;
2980                                 if (pimd->flag & eParticleInstanceFlag_Path && pimd->ob == sim->ob && pimd->psys == (psys - (ParticleSystem*)sim->ob->particlesystem.first)) {
2981                                         skip = 0;
2982                                         break;
2983                                 }
2984                         }
2985                 }
2986                 FOREACH_SCENE_OBJECT_END;
2987         }
2988
2989         if (!skip) {
2990                 psys_cache_paths(sim, cfra, use_render_params);
2991
2992                 /* for render, child particle paths are computed on the fly */
2993                 if (part->childtype) {
2994                         if (!psys->totchild)
2995                                 skip = 1;
2996                         else if (psys->part->type == PART_HAIR && (psys->flag & PSYS_HAIR_DONE)==0)
2997                                 skip = 1;
2998
2999                         if (!skip)
3000                                 psys_cache_child_paths(sim, cfra, 0, use_render_params);
3001                 }
3002         }
3003         else if (psys->pathcache)
3004                 psys_free_path_cache(psys, NULL);
3005 }
3006
3007 static bool psys_hair_use_simulation(ParticleData *pa, float max_length)
3008 {
3009         /* Minimum segment length relative to average length.
3010          * Hairs with segments below this length will be excluded from the simulation,
3011          * because otherwise the solver will become unstable.
3012          * The hair system should always make sure the hair segments have reasonable length ratios,
3013          * but this can happen in old files when e.g. cutting hair.
3014          */
3015         const float min_length = 0.1f * max_length;
3016
3017         HairKey *key;
3018         int k;
3019
3020         if (pa->totkey < 2)
3021                 return false;
3022
3023         for (k=1, key=pa->hair+1; k<pa->totkey; k++,key++) {
3024                 float length = len_v3v3(key->co, (key-1)->co);
3025                 if (length < min_length)
3026                         return false;
3027         }
3028
3029         return true;
3030 }
3031
3032 static MDeformVert *hair_set_pinning(MDeformVert *dvert, float weight)
3033 {
3034         if (dvert) {
3035                 if (!dvert->totweight) {
3036                         dvert->dw = MEM_callocN(sizeof(MDeformWeight), "deformWeight");
3037                         dvert->totweight = 1;
3038                 }
3039
3040                 dvert->dw->weight = weight;
3041                 dvert++;
3042         }
3043         return dvert;
3044 }
3045
3046 static void hair_create_input_mesh(ParticleSimulationData