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