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