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