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