Undo revision 23130 which was a merge with 2.5, a messy one because I did something...
[blender.git] / source / blender / blenkernel / intern / particle_system.c
1 /* particle_system.c
2  *
3  *
4  * $Id$
5  *
6  * ***** BEGIN GPL LICENSE BLOCK *****
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License
10  * as published by the Free Software Foundation; either version 2
11  * of the License, or (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software Foundation,
20  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
21  *
22  * The Original Code is Copyright (C) 2007 by Janne Karhu.
23  * All rights reserved.
24  *
25  * The Original Code is: all of this file.
26  *
27  * Contributor(s): none yet.
28  *
29  * ***** END GPL LICENSE BLOCK *****
30  */
31
32 #include "BLI_storage.h" /* _LARGEFILE_SOURCE */
33
34 #include <stdlib.h>
35 #include <math.h>
36 #include <string.h>
37
38 #include "MEM_guardedalloc.h"
39
40 #include "DNA_boid_types.h"
41 #include "DNA_particle_types.h"
42 #include "DNA_mesh_types.h"
43 #include "DNA_meshdata_types.h"
44 #include "DNA_modifier_types.h"
45 #include "DNA_object_force.h"
46 #include "DNA_object_types.h"
47 #include "DNA_material_types.h"
48 #include "DNA_curve_types.h"
49 #include "DNA_group_types.h"
50 #include "DNA_scene_types.h"
51 #include "DNA_texture_types.h"
52 #include "DNA_ipo_types.h" // XXX old animation system stuff... to be removed!
53 #include "DNA_listBase.h"
54
55 #include "BLI_rand.h"
56 #include "BLI_jitter.h"
57 #include "BLI_arithb.h"
58 #include "BLI_blenlib.h"
59 #include "BLI_kdtree.h"
60 #include "BLI_kdopbvh.h"
61 #include "BLI_linklist.h"
62 #include "BLI_threads.h"
63
64 #include "BKE_anim.h"
65 #include "BKE_boids.h"
66 #include "BKE_cdderivedmesh.h"
67 #include "BKE_collision.h"
68 #include "BKE_displist.h"
69 #include "BKE_effect.h"
70 #include "BKE_particle.h"
71 #include "BKE_global.h"
72 #include "BKE_utildefines.h"
73 #include "BKE_DerivedMesh.h"
74 #include "BKE_object.h"
75 #include "BKE_material.h"
76 #include "BKE_softbody.h"
77 #include "BKE_depsgraph.h"
78 #include "BKE_lattice.h"
79 #include "BKE_pointcache.h"
80 #include "BKE_mesh.h"
81 #include "BKE_modifier.h"
82 #include "BKE_scene.h"
83 #include "BKE_bvhutils.h"
84
85 #include "PIL_time.h"
86
87 #include "RE_shader_ext.h"
88
89 /* fluid sim particle import */
90 #ifndef DISABLE_ELBEEM
91 #include "DNA_object_fluidsim.h"
92 #include "LBM_fluidsim.h"
93 #include <zlib.h>
94 #include <string.h>
95
96 #ifdef WIN32
97 #ifndef snprintf
98 #define snprintf _snprintf
99 #endif
100 #endif
101
102 #endif // DISABLE_ELBEEM
103
104 /************************************************/
105 /*                      Reacting to system events                       */
106 /************************************************/
107
108 static int get_current_display_percentage(ParticleSystem *psys)
109 {
110         ParticleSettings *part=psys->part;
111
112         if(psys->renderdata || (part->child_nbr && part->childtype)
113                 || (psys->pointcache->flag & PTCACHE_BAKING))
114                 return 100;
115
116         if(part->phystype==PART_PHYS_KEYED){
117                 return psys->part->disp;
118         }
119         else
120                 return psys->part->disp;
121 }
122
123 void psys_reset(ParticleSystem *psys, int mode)
124 {
125         ParticleSettings *part= psys->part;
126         ParticleData *pa;
127         int i;
128
129         if(ELEM(mode, PSYS_RESET_ALL, PSYS_RESET_DEPSGRAPH)) {
130                 if(mode == PSYS_RESET_ALL || !(part->type == PART_HAIR && (psys->flag & PSYS_EDITED))) {
131                         if(psys->particles) {
132                                 if(psys->particles->keys)
133                                         MEM_freeN(psys->particles->keys);
134
135                                 for(i=0, pa=psys->particles; i<psys->totpart; i++, pa++)
136                                         if(pa->hair) MEM_freeN(pa->hair);
137
138                                 MEM_freeN(psys->particles);
139                                 psys->particles= NULL;
140                         }
141
142                         psys->totpart= 0;
143                         psys->totkeyed= 0;
144                         psys->flag &= ~(PSYS_HAIR_DONE|PSYS_KEYED);
145
146                         if(psys->reactevents.first)
147                                 BLI_freelistN(&psys->reactevents);
148                 }
149         }
150         else if(mode == PSYS_RESET_CACHE_MISS) {
151                 /* set all particles to be skipped */
152                 ParticleData *pa = psys->particles;
153                 int p=0;
154
155                 for(; p<psys->totpart; p++, pa++)
156                         pa->flag |= PARS_NO_DISP;
157         }
158
159         /* reset children */
160         if(psys->child) {
161                 MEM_freeN(psys->child);
162                 psys->child= 0;
163         }
164
165         psys->totchild= 0;
166
167         /* reset path cache */
168         psys_free_path_cache(psys);
169
170         /* reset point cache */
171         psys->pointcache->flag &= ~PTCACHE_SIMULATION_VALID;
172         psys->pointcache->simframe= 0;
173 }
174
175 static void realloc_particles(Object *ob, ParticleSystem *psys, int new_totpart)
176 {
177         ParticleData *newpars = 0, *pa;
178         BoidData *newboids = 0;
179         int i, totpart, totsaved = 0;
180
181         if(new_totpart<0) {
182                 if(psys->part->distr==PART_DISTR_GRID  && psys->part->from != PART_FROM_VERT) {
183                         totpart= psys->part->grid_res;
184                         totpart*=totpart*totpart;
185                 }
186                 else
187                         totpart=psys->part->totpart;
188         }
189         else
190                 totpart=new_totpart;
191
192         if(totpart) {
193                 newpars= MEM_callocN(totpart*sizeof(ParticleData), "particles");
194
195                 if(psys->part->phystype == PART_PHYS_BOIDS)
196                         newboids = MEM_callocN(totpart*sizeof(BoidData), "Boid Data");
197         }
198         if(psys->particles) {
199                 totsaved=MIN2(psys->totpart,totpart);
200                 /*save old pars*/
201                 if(totsaved) {
202                         memcpy(newpars,psys->particles,totsaved*sizeof(ParticleData));
203
204                         if(newboids)
205                                 memcpy(newboids, psys->particles->boid, totsaved*sizeof(BoidData));
206                 }
207
208                 if(psys->particles->keys)
209                         MEM_freeN(psys->particles->keys);
210
211                 if(psys->particles->boid)
212                         MEM_freeN(psys->particles->boid);
213
214                 for(i=0, pa=newpars; i<totsaved; i++, pa++) {
215                         if(pa->keys) {
216                                 pa->keys= NULL;
217                                 pa->totkey= 0;
218                         }
219                 }
220
221                 for(i=totsaved, pa=psys->particles+totsaved; i<psys->totpart; i++, pa++)
222                         if(pa->hair) MEM_freeN(pa->hair);
223
224                 MEM_freeN(psys->particles);
225         }
226         psys->particles=newpars;
227
228         if(newboids) {
229                 pa = psys->particles;
230                 pa->boid = newboids;
231                 for(i=1, pa++; i<totpart; i++,pa++)
232                         pa->boid = (pa-1)->boid + 1;
233         }
234
235         if(psys->child) {
236                 MEM_freeN(psys->child);
237                 psys->child=0;
238                 psys->totchild=0;
239         }
240
241         psys->totpart=totpart;
242 }
243
244 static int get_psys_child_number(struct Scene *scene, ParticleSystem *psys)
245 {
246         int nbr;
247
248         if(!psys->part->childtype)
249                 return 0;
250
251         if(psys->renderdata) {
252                 nbr= psys->part->ren_child_nbr;
253                 return get_render_child_particle_number(&scene->r, nbr);
254         }
255         else
256                 return psys->part->child_nbr;
257 }
258
259 static int get_psys_tot_child(struct Scene *scene, ParticleSystem *psys)
260 {
261         return psys->totpart*get_psys_child_number(scene, psys);
262 }
263
264 static void alloc_child_particles(ParticleSystem *psys, int tot)
265 {
266         if(psys->child){
267                 MEM_freeN(psys->child);
268                 psys->child=0;
269                 psys->totchild=0;
270         }
271
272         if(psys->part->childtype) {
273                 psys->totchild= tot;
274                 if(psys->totchild)
275                         psys->child= MEM_callocN(psys->totchild*sizeof(ChildParticle), "child_particles");
276         }
277 }
278
279 void psys_calc_dmcache(Object *ob, DerivedMesh *dm, ParticleSystem *psys)
280 {
281         /* use for building derived mesh mapping info:
282
283            node: the allocated links - total derived mesh element count 
284            nodearray: the array of nodes aligned with the base mesh's elements, so
285                       each original elements can reference its derived elements
286         */
287         Mesh *me= (Mesh*)ob->data;
288         ParticleData *pa= 0;
289         int p;
290         
291         /* CACHE LOCATIONS */
292         if(!dm->deformedOnly) {
293                 /* Will use later to speed up subsurf/derivedmesh */
294                 LinkNode *node, *nodedmelem, **nodearray;
295                 int totdmelem, totelem, i, *origindex;
296
297                 if(psys->part->from == PART_FROM_VERT) {
298                         totdmelem= dm->getNumVerts(dm);
299                         totelem= me->totvert;
300                         origindex= DM_get_vert_data_layer(dm, CD_ORIGINDEX);
301                 }
302                 else { /* FROM_FACE/FROM_VOLUME */
303                         totdmelem= dm->getNumFaces(dm);
304                         totelem= me->totface;
305                         origindex= DM_get_face_data_layer(dm, CD_ORIGINDEX);
306                 }
307         
308                 nodedmelem= MEM_callocN(sizeof(LinkNode)*totdmelem, "psys node elems");
309                 nodearray= MEM_callocN(sizeof(LinkNode *)*totelem, "psys node array");
310                 
311                 for(i=0, node=nodedmelem; i<totdmelem; i++, origindex++, node++) {
312                         node->link= SET_INT_IN_POINTER(i);
313
314                         if(*origindex != -1) {
315                                 if(nodearray[*origindex]) {
316                                         /* prepend */
317                                         node->next = nodearray[*origindex];
318                                         nodearray[*origindex]= node;
319                                 }
320                                 else
321                                         nodearray[*origindex]= node;
322                         }
323                 }
324                 
325                 /* cache the verts/faces! */
326                 for(p=0,pa=psys->particles; p<psys->totpart; p++,pa++) {
327                         if(psys->part->from == PART_FROM_VERT) {
328                                 if(nodearray[pa->num])
329                                         pa->num_dmcache= GET_INT_FROM_POINTER(nodearray[pa->num]->link);
330                         }
331                         else { /* FROM_FACE/FROM_VOLUME */
332                                 /* Note that somtimes the pa->num is over the nodearray size, this is bad, maybe there is a better place to fix this,
333                                  * but for now passing NULL is OK. every face will be searched for the particle so its slower - Campbell */
334                                 pa->num_dmcache= psys_particle_dm_face_lookup(ob, dm, pa->num, pa->fuv, pa->num < totelem ? nodearray[pa->num] : NULL);
335                         }
336                 }
337
338                 MEM_freeN(nodearray);
339                 MEM_freeN(nodedmelem);
340         }
341         else {
342                 /* TODO PARTICLE, make the following line unnecessary, each function
343                  * should know to use the num or num_dmcache, set the num_dmcache to
344                  * an invalid value, just incase */
345                 
346                 for(p=0,pa=psys->particles; p<psys->totpart; p++,pa++)
347                         pa->num_dmcache = -1;
348         }
349 }
350
351 static void distribute_particles_in_grid(DerivedMesh *dm, ParticleSystem *psys)
352 {
353         ParticleData *pa=0;
354         float min[3], max[3], delta[3], d;
355         MVert *mv, *mvert = dm->getVertDataArray(dm,0);
356         int totvert=dm->getNumVerts(dm), from=psys->part->from;
357         int i, j, k, p, res=psys->part->grid_res, size[3], axis;
358
359         mv=mvert;
360
361         /* find bounding box of dm */
362         VECCOPY(min,mv->co);
363         VECCOPY(max,mv->co);
364         mv++;
365
366         for(i=1; i<totvert; i++, mv++){
367                 min[0]=MIN2(min[0],mv->co[0]);
368                 min[1]=MIN2(min[1],mv->co[1]);
369                 min[2]=MIN2(min[2],mv->co[2]);
370
371                 max[0]=MAX2(max[0],mv->co[0]);
372                 max[1]=MAX2(max[1],mv->co[1]);
373                 max[2]=MAX2(max[2],mv->co[2]);
374         }
375
376         VECSUB(delta,max,min);
377
378         /* determine major axis */
379         axis = (delta[0]>=delta[1])?0:((delta[1]>=delta[2])?1:2);
380
381         d = delta[axis]/(float)res;
382
383         size[axis]=res;
384         size[(axis+1)%3]=(int)ceil(delta[(axis+1)%3]/d);
385         size[(axis+2)%3]=(int)ceil(delta[(axis+2)%3]/d);
386
387         /* float errors grrr.. */
388         size[(axis+1)%3] = MIN2(size[(axis+1)%3],res);
389         size[(axis+2)%3] = MIN2(size[(axis+2)%3],res);
390
391         min[0]+=d/2.0f;
392         min[1]+=d/2.0f;
393         min[2]+=d/2.0f;
394
395         for(i=0,p=0,pa=psys->particles; i<res; i++){
396                 for(j=0; j<res; j++){
397                         for(k=0; k<res; k++,p++,pa++){
398                                 pa->fuv[0]=min[0]+(float)i*d;
399                                 pa->fuv[1]=min[1]+(float)j*d;
400                                 pa->fuv[2]=min[2]+(float)k*d;
401                                 pa->flag |= PARS_UNEXIST;
402                                 pa->loop=0; /* abused in volume calculation */
403                         }
404                 }
405         }
406
407         /* enable particles near verts/edges/faces/inside surface */
408         if(from==PART_FROM_VERT){
409                 float vec[3];
410
411                 pa=psys->particles;
412
413                 min[0]-=d/2.0f;
414                 min[1]-=d/2.0f;
415                 min[2]-=d/2.0f;
416
417                 for(i=0,mv=mvert; i<totvert; i++,mv++){
418                         VecSubf(vec,mv->co,min);
419                         vec[0]/=delta[0];
420                         vec[1]/=delta[1];
421                         vec[2]/=delta[2];
422                         (pa     +((int)(vec[0]*(size[0]-1))*res
423                                 +(int)(vec[1]*(size[1]-1)))*res
424                                 +(int)(vec[2]*(size[2]-1)))->flag &= ~PARS_UNEXIST;
425                 }
426         }
427         else if(ELEM(from,PART_FROM_FACE,PART_FROM_VOLUME)){
428                 float co1[3], co2[3];
429
430                 MFace *mface=0;
431                 float v1[3], v2[3], v3[3], v4[4], lambda;
432                 int a, a1, a2, a0mul, a1mul, a2mul, totface;
433                 int amax= from==PART_FROM_FACE ? 3 : 1;
434
435                 totface=dm->getNumFaces(dm);
436                 mface=dm->getFaceDataArray(dm,CD_MFACE);
437                 
438                 for(a=0; a<amax; a++){
439                         if(a==0){ a0mul=res*res; a1mul=res; a2mul=1; }
440                         else if(a==1){ a0mul=res; a1mul=1; a2mul=res*res; }
441                         else{ a0mul=1; a1mul=res*res; a2mul=res; }
442
443                         for(a1=0; a1<size[(a+1)%3]; a1++){
444                                 for(a2=0; a2<size[(a+2)%3]; a2++){
445                                         mface=dm->getFaceDataArray(dm,CD_MFACE);
446
447                                         pa=psys->particles + a1*a1mul + a2*a2mul;
448                                         VECCOPY(co1,pa->fuv);
449                                         co1[a]-=d/2.0f;
450                                         VECCOPY(co2,co1);
451                                         co2[a]+=delta[a] + 0.001f*d;
452                                         co1[a]-=0.001f*d;
453                                         
454                                         /* lets intersect the faces */
455                                         for(i=0; i<totface; i++,mface++){
456                                                 VECCOPY(v1,mvert[mface->v1].co);
457                                                 VECCOPY(v2,mvert[mface->v2].co);
458                                                 VECCOPY(v3,mvert[mface->v3].co);
459
460                                                 if(AxialLineIntersectsTriangle(a,co1, co2, v2, v3, v1, &lambda)){
461                                                         if(from==PART_FROM_FACE)
462                                                                 (pa+(int)(lambda*size[a])*a0mul)->flag &= ~PARS_UNEXIST;
463                                                         else /* store number of intersections */
464                                                                 (pa+(int)(lambda*size[a])*a0mul)->loop++;
465                                                 }
466                                                 
467                                                 if(mface->v4){
468                                                         VECCOPY(v4,mvert[mface->v4].co);
469
470                                                         if(AxialLineIntersectsTriangle(a,co1, co2, v4, v1, v3, &lambda)){
471                                                                 if(from==PART_FROM_FACE)
472                                                                         (pa+(int)(lambda*size[a])*a0mul)->flag &= ~PARS_UNEXIST;
473                                                                 else
474                                                                         (pa+(int)(lambda*size[a])*a0mul)->loop++;
475                                                         }
476                                                 }
477                                         }
478
479                                         if(from==PART_FROM_VOLUME){
480                                                 int in=pa->loop%2;
481                                                 if(in) pa->loop++;
482                                                 for(i=0; i<size[0]; i++){
483                                                         if(in || (pa+i*a0mul)->loop%2)
484                                                                 (pa+i*a0mul)->flag &= ~PARS_UNEXIST;
485                                                         /* odd intersections == in->out / out->in */
486                                                         /* even intersections -> in stays same */
487                                                         in=(in + (pa+i*a0mul)->loop) % 2;
488                                                 }
489                                         }
490                                 }
491                         }
492                 }
493         }
494
495         if(psys->part->flag & PART_GRID_INVERT){
496                 for(i=0,pa=psys->particles; i<size[0]; i++){
497                         for(j=0; j<size[1]; j++){
498                                 pa=psys->particles + res*(i*res + j);
499                                 for(k=0; k<size[2]; k++, pa++){
500                                         pa->flag ^= PARS_UNEXIST;
501                                 }
502                         }
503                 }
504         }
505 }
506
507 /* modified copy from rayshade.c */
508 static void hammersley_create(float *out, int n, int seed, float amount)
509 {
510         RNG *rng;
511     double p, t, offs[2];
512     int k, kk;
513
514         rng = rng_new(31415926 + n + seed);
515         offs[0]= rng_getDouble(rng) + amount;
516         offs[1]= rng_getDouble(rng) + amount;
517         rng_free(rng);
518
519     for (k = 0; k < n; k++) {
520         t = 0;
521         for (p = 0.5, kk = k; kk; p *= 0.5, kk >>= 1)
522             if (kk & 1) /* kk mod 2 = 1 */
523                                 t += p;
524     
525                 out[2*k + 0]= fmod((double)k/(double)n + offs[0], 1.0);
526                 out[2*k + 1]= fmod(t + offs[1], 1.0);
527         }
528 }
529
530 /* modified copy from effect.c */
531 static void init_mv_jit(float *jit, int num, int seed2, float amount)
532 {
533         RNG *rng;
534         float *jit2, x, rad1, rad2, rad3;
535         int i, num2;
536
537         if(num==0) return;
538
539         rad1= (float)(1.0/sqrt((float)num));
540         rad2= (float)(1.0/((float)num));
541         rad3= (float)sqrt((float)num)/((float)num);
542
543         rng = rng_new(31415926 + num + seed2);
544         x= 0;
545         num2 = 2 * num;
546         for(i=0; i<num2; i+=2) {
547         
548                 jit[i]= x + amount*rad1*(0.5f - rng_getFloat(rng));
549                 jit[i+1]= i/(2.0f*num) + amount*rad1*(0.5f - rng_getFloat(rng));
550                 
551                 jit[i]-= (float)floor(jit[i]);
552                 jit[i+1]-= (float)floor(jit[i+1]);
553                 
554                 x+= rad3;
555                 x -= (float)floor(x);
556         }
557
558         jit2= MEM_mallocN(12 + 2*sizeof(float)*num, "initjit");
559
560         for (i=0 ; i<4 ; i++) {
561                 BLI_jitterate1(jit, jit2, num, rad1);
562                 BLI_jitterate1(jit, jit2, num, rad1);
563                 BLI_jitterate2(jit, jit2, num, rad2);
564         }
565         MEM_freeN(jit2);
566         rng_free(rng);
567 }
568
569 static void psys_uv_to_w(float u, float v, int quad, float *w)
570 {
571         float vert[4][3], co[3];
572
573         if(!quad) {
574                 if(u+v > 1.0f)
575                         v= 1.0f-v;
576                 else
577                         u= 1.0f-u;
578         }
579
580         vert[0][0]= 0.0f; vert[0][1]= 0.0f; vert[0][2]= 0.0f;
581         vert[1][0]= 1.0f; vert[1][1]= 0.0f; vert[1][2]= 0.0f;
582         vert[2][0]= 1.0f; vert[2][1]= 1.0f; vert[2][2]= 0.0f;
583
584         co[0]= u;
585         co[1]= v;
586         co[2]= 0.0f;
587
588         if(quad) {
589                 vert[3][0]= 0.0f; vert[3][1]= 1.0f; vert[3][2]= 0.0f;
590                 MeanValueWeights(vert, 4, co, w);
591         }
592         else {
593                 MeanValueWeights(vert, 3, co, w);
594                 w[3]= 0.0f;
595         }
596 }
597
598 static int binary_search_distribution(float *sum, int n, float value)
599 {
600         int mid, low=0, high=n;
601
602         while(low <= high) {
603                 mid= (low + high)/2;
604                 if(sum[mid] <= value && value <= sum[mid+1])
605                         return mid;
606                 else if(sum[mid] > value)
607                         high= mid - 1;
608                 else if(sum[mid] < value)
609                         low= mid + 1;
610                 else
611                         return mid;
612         }
613
614         return low;
615 }
616
617 /* note: this function must be thread safe, for from == PART_FROM_CHILD */
618 #define ONLY_WORKING_WITH_PA_VERTS 0
619 void psys_thread_distribute_particle(ParticleThread *thread, ParticleData *pa, ChildParticle *cpa, int p)
620 {
621         ParticleThreadContext *ctx= thread->ctx;
622         Object *ob= ctx->ob;
623         DerivedMesh *dm= ctx->dm;
624         ParticleData *tpa;
625         ParticleSettings *part= ctx->psys->part;
626         float *v1, *v2, *v3, *v4, nor[3], orco1[3], co1[3], co2[3], nor1[3], ornor1[3];
627         float cur_d, min_d, randu, randv;
628         int from= ctx->from;
629         int cfrom= ctx->cfrom;
630         int distr= ctx->distr;
631         int i, intersect, tot;
632
633         if(from == PART_FROM_VERT) {
634                 /* TODO_PARTICLE - use original index */
635                 pa->num= ctx->index[p];
636                 pa->fuv[0] = 1.0f;
637                 pa->fuv[1] = pa->fuv[2] = pa->fuv[3] = 0.0;
638                 //pa->verts[0] = pa->verts[1] = pa->verts[2] = 0;
639
640 #if ONLY_WORKING_WITH_PA_VERTS
641                 if(ctx->tree){
642                         KDTreeNearest ptn[3];
643                         int w, maxw;
644
645                         psys_particle_on_dm(ctx->dm,from,pa->num,pa->num_dmcache,pa->fuv,pa->foffset,co1,0,0,0,orco1,0);
646                         transform_mesh_orco_verts((Mesh*)ob->data, &orco1, 1, 1);
647                         maxw = BLI_kdtree_find_n_nearest(ctx->tree,3,orco1,NULL,ptn);
648
649                         for(w=0; w<maxw; w++){
650                                 pa->verts[w]=ptn->num;
651                         }
652                 }
653 #endif
654         }
655         else if(from == PART_FROM_FACE || from == PART_FROM_VOLUME) {
656                 MFace *mface;
657
658                 pa->num = i = ctx->index[p];
659                 mface = dm->getFaceData(dm,i,CD_MFACE);
660                 
661                 switch(distr){
662                 case PART_DISTR_JIT:
663                         ctx->jitoff[i] = fmod(ctx->jitoff[i],(float)ctx->jitlevel);
664                         psys_uv_to_w(ctx->jit[2*(int)ctx->jitoff[i]], ctx->jit[2*(int)ctx->jitoff[i]+1], mface->v4, pa->fuv);
665                         ctx->jitoff[i]++;
666                         //ctx->jitoff[i]=(float)fmod(ctx->jitoff[i]+ctx->maxweight/ctx->weight[i],(float)ctx->jitlevel);
667                         break;
668                 case PART_DISTR_RAND:
669                         randu= rng_getFloat(thread->rng);
670                         randv= rng_getFloat(thread->rng);
671                         psys_uv_to_w(randu, randv, mface->v4, pa->fuv);
672                         break;
673                 }
674                 pa->foffset= 0.0f;
675                 
676                 /*
677                 pa->verts[0] = mface->v1;
678                 pa->verts[1] = mface->v2;
679                 pa->verts[2] = mface->v3;
680                 */
681                 
682                 /* experimental */
683                 if(from==PART_FROM_VOLUME){
684                         MVert *mvert=dm->getVertDataArray(dm,CD_MVERT);
685
686                         tot=dm->getNumFaces(dm);
687
688                         psys_interpolate_face(mvert,mface,0,0,pa->fuv,co1,nor,0,0,0,0);
689
690                         Normalize(nor);
691                         VecMulf(nor,-100.0);
692
693                         VECADD(co2,co1,nor);
694
695                         min_d=2.0;
696                         intersect=0;
697
698                         for(i=0,mface=dm->getFaceDataArray(dm,CD_MFACE); i<tot; i++,mface++){
699                                 if(i==pa->num) continue;
700
701                                 v1=mvert[mface->v1].co;
702                                 v2=mvert[mface->v2].co;
703                                 v3=mvert[mface->v3].co;
704
705                                 if(LineIntersectsTriangle(co1, co2, v2, v3, v1, &cur_d, 0)){
706                                         if(cur_d<min_d){
707                                                 min_d=cur_d;
708                                                 pa->foffset=cur_d*50.0f; /* to the middle of volume */
709                                                 intersect=1;
710                                         }
711                                 }
712                                 if(mface->v4){
713                                         v4=mvert[mface->v4].co;
714
715                                         if(LineIntersectsTriangle(co1, co2, v4, v1, v3, &cur_d, 0)){
716                                                 if(cur_d<min_d){
717                                                         min_d=cur_d;
718                                                         pa->foffset=cur_d*50.0f; /* to the middle of volume */
719                                                         intersect=1;
720                                                 }
721                                         }
722                                 }
723                         }
724                         if(intersect==0)
725                                 pa->foffset=0.0;
726                         else switch(distr){
727                                 case PART_DISTR_JIT:
728                                         pa->foffset*= ctx->jit[2*(int)ctx->jitoff[i]];
729                                         break;
730                                 case PART_DISTR_RAND:
731                                         pa->foffset*=BLI_frand();
732                                         break;
733                         }
734                 }
735         }
736         else if(from == PART_FROM_PARTICLE) {
737                 //pa->verts[0]=0; /* not applicable */
738                 //pa->verts[1]=0;
739                 //pa->verts[2]=0;
740
741                 tpa=ctx->tpars+ctx->index[p];
742                 pa->num=ctx->index[p];
743                 pa->fuv[0]=tpa->fuv[0];
744                 pa->fuv[1]=tpa->fuv[1];
745                 /* abusing foffset a little for timing in near reaction */
746                 pa->foffset=ctx->weight[ctx->index[p]];
747                 ctx->weight[ctx->index[p]]+=ctx->maxweight;
748         }
749         else if(from == PART_FROM_CHILD) {
750                 MFace *mf;
751
752                 if(ctx->index[p] < 0) {
753                         cpa->num=0;
754                         cpa->fuv[0]=cpa->fuv[1]=cpa->fuv[2]=cpa->fuv[3]=0.0f;
755                         cpa->pa[0]=cpa->pa[1]=cpa->pa[2]=cpa->pa[3]=0;
756                         cpa->rand[0]=cpa->rand[1]=cpa->rand[2]=0.0f;
757                         return;
758                 }
759
760                 mf= dm->getFaceData(dm, ctx->index[p], CD_MFACE);
761
762                 //switch(distr){
763                 //      case PART_DISTR_JIT:
764                 //              i=index[p];
765                 //              psys_uv_to_w(ctx->jit[2*(int)ctx->jitoff[i]], ctx->jit[2*(int)ctx->jitoff[i]+1], mf->v4, cpa->fuv);
766                 //              ctx->jitoff[i]=(float)fmod(ctx->jitoff[i]+ctx->maxweight/ctx->weight[i],(float)ctx->jitlevel);
767                 //              break;
768                 //      case PART_DISTR_RAND:
769                                 randu= rng_getFloat(thread->rng);
770                                 randv= rng_getFloat(thread->rng);
771                                 psys_uv_to_w(randu, randv, mf->v4, cpa->fuv);
772                 //              break;
773                 //}
774
775                 cpa->rand[0] = rng_getFloat(thread->rng);
776                 cpa->rand[1] = rng_getFloat(thread->rng);
777                 cpa->rand[2] = rng_getFloat(thread->rng);
778                 cpa->num = ctx->index[p];
779
780                 if(ctx->tree){
781                         KDTreeNearest ptn[10];
782                         int w,maxw, do_seams;
783                         float maxd,mind,dd,totw=0.0;
784                         int parent[10];
785                         float pweight[10];
786
787                         do_seams= (part->flag&PART_CHILD_SEAMS && ctx->seams);
788
789                         psys_particle_on_dm(dm,cfrom,cpa->num,DMCACHE_ISCHILD,cpa->fuv,cpa->foffset,co1,nor1,0,0,orco1,ornor1);
790                         transform_mesh_orco_verts((Mesh*)ob->data, &orco1, 1, 1);
791                         maxw = BLI_kdtree_find_n_nearest(ctx->tree,(do_seams)?10:4,orco1,ornor1,ptn);
792
793                         maxd=ptn[maxw-1].dist;
794                         mind=ptn[0].dist;
795                         dd=maxd-mind;
796                         
797                         /* the weights here could be done better */
798                         for(w=0; w<maxw; w++){
799                                 parent[w]=ptn[w].index;
800                                 pweight[w]=(float)pow(2.0,(double)(-6.0f*ptn[w].dist/maxd));
801                                 //pweight[w]= (1.0f - ptn[w].dist*ptn[w].dist/(maxd*maxd));
802                                 //pweight[w] *= pweight[w];
803                         }
804                         for(;w<10; w++){
805                                 parent[w]=-1;
806                                 pweight[w]=0.0f;
807                         }
808                         if(do_seams){
809                                 ParticleSeam *seam=ctx->seams;
810                                 float temp[3],temp2[3],tan[3];
811                                 float inp,cur_len,min_len=10000.0f;
812                                 int min_seam=0, near_vert=0;
813                                 /* find closest seam */
814                                 for(i=0; i<ctx->totseam; i++, seam++){
815                                         VecSubf(temp,co1,seam->v0);
816                                         inp=Inpf(temp,seam->dir)/seam->length2;
817                                         if(inp<0.0f){
818                                                 cur_len=VecLenf(co1,seam->v0);
819                                         }
820                                         else if(inp>1.0f){
821                                                 cur_len=VecLenf(co1,seam->v1);
822                                         }
823                                         else{
824                                                 VecCopyf(temp2,seam->dir);
825                                                 VecMulf(temp2,inp);
826                                                 cur_len=VecLenf(temp,temp2);
827                                         }
828                                         if(cur_len<min_len){
829                                                 min_len=cur_len;
830                                                 min_seam=i;
831                                                 if(inp<0.0f) near_vert=-1;
832                                                 else if(inp>1.0f) near_vert=1;
833                                                 else near_vert=0;
834                                         }
835                                 }
836                                 seam=ctx->seams+min_seam;
837                                 
838                                 VecCopyf(temp,seam->v0);
839                                 
840                                 if(near_vert){
841                                         if(near_vert==-1)
842                                                 VecSubf(tan,co1,seam->v0);
843                                         else{
844                                                 VecSubf(tan,co1,seam->v1);
845                                                 VecCopyf(temp,seam->v1);
846                                         }
847
848                                         Normalize(tan);
849                                 }
850                                 else{
851                                         VecCopyf(tan,seam->tan);
852                                         VecSubf(temp2,co1,temp);
853                                         if(Inpf(tan,temp2)<0.0f)
854                                                 VecNegf(tan);
855                                 }
856                                 for(w=0; w<maxw; w++){
857                                         VecSubf(temp2,ptn[w].co,temp);
858                                         if(Inpf(tan,temp2)<0.0f){
859                                                 parent[w]=-1;
860                                                 pweight[w]=0.0f;
861                                         }
862                                 }
863
864                         }
865
866                         for(w=0,i=0; w<maxw && i<4; w++){
867                                 if(parent[w]>=0){
868                                         cpa->pa[i]=parent[w];
869                                         cpa->w[i]=pweight[w];
870                                         totw+=pweight[w];
871                                         i++;
872                                 }
873                         }
874                         for(;i<4; i++){
875                                 cpa->pa[i]=-1;
876                                 cpa->w[i]=0.0f;
877                         }
878
879                         if(totw>0.0f) for(w=0; w<4; w++)
880                                 cpa->w[w]/=totw;
881
882                         cpa->parent=cpa->pa[0];
883                 }
884         }
885 }
886
887 static void *exec_distribution(void *data)
888 {
889         ParticleThread *thread= (ParticleThread*)data;
890         ParticleSystem *psys= thread->ctx->psys;
891         ParticleData *pa;
892         ChildParticle *cpa;
893         int p, totpart;
894
895         if(thread->ctx->from == PART_FROM_CHILD) {
896                 totpart= psys->totchild;
897                 cpa= psys->child;
898
899                 for(p=0; p<totpart; p++, cpa++) {
900                         if(thread->ctx->skip) /* simplification skip */
901                                 rng_skip(thread->rng, 5*thread->ctx->skip[p]);
902
903                         if((p+thread->num) % thread->tot == 0)
904                                 psys_thread_distribute_particle(thread, NULL, cpa, p);
905                         else /* thread skip */
906                                 rng_skip(thread->rng, 5);
907                 }
908         }
909         else {
910                 totpart= psys->totpart;
911                 pa= psys->particles + thread->num;
912                 for(p=thread->num; p<totpart; p+=thread->tot, pa+=thread->tot)
913                         psys_thread_distribute_particle(thread, pa, NULL, p);
914         }
915
916         return 0;
917 }
918
919 /* not thread safe, but qsort doesn't take userdata argument */
920 static int *COMPARE_ORIG_INDEX = NULL;
921 static int compare_orig_index(const void *p1, const void *p2)
922 {
923         int index1 = COMPARE_ORIG_INDEX[*(const int*)p1];
924         int index2 = COMPARE_ORIG_INDEX[*(const int*)p2];
925
926         if(index1 < index2)
927                 return -1;
928         else if(index1 == index2) {
929                 /* this pointer comparison appears to make qsort stable for glibc,
930                  * and apparently on solaris too, makes the renders reproducable */
931                 if(p1 < p2)
932                         return -1;
933                 else if(p1 == p2)
934                         return 0;
935                 else
936                         return 1;
937         }
938         else
939                 return 1;
940 }
941
942 /* creates a distribution of coordinates on a DerivedMesh       */
943 /*                                                                                                                      */
944 /* 1. lets check from what we are emitting                                      */
945 /* 2. now we know that we have something to emit from so        */
946 /*        let's calculate some weights                                                  */
947 /* 2.1 from even distribution                                                           */
948 /* 2.2 and from vertex groups                                                           */
949 /* 3. next we determine the indexes of emitting thing that      */
950 /*        the particles will have                                                               */
951 /* 4. let's do jitter if we need it                                                     */
952 /* 5. now we're ready to set the indexes & distributions to     */
953 /*        the particles                                                                                 */
954 /* 6. and we're done!                                                                           */
955
956 /* This is to denote functionality that does not yet work with mesh - only derived mesh */
957 int psys_threads_init_distribution(ParticleThread *threads, Scene *scene, DerivedMesh *finaldm, int from)
958 {
959         ParticleThreadContext *ctx= threads[0].ctx;
960         Object *ob= ctx->ob;
961         ParticleSystem *psys= ctx->psys;
962         Object *tob;
963         ParticleData *pa=0, *tpars= 0;
964         ParticleSettings *part;
965         ParticleSystem *tpsys;
966         ParticleSeam *seams= 0;
967         ChildParticle *cpa=0;
968         KDTree *tree=0;
969         DerivedMesh *dm= NULL;
970         float *jit= NULL;
971         int i, seed, p=0, totthread= threads[0].tot;
972         int no_distr=0, cfrom=0;
973         int tot=0, totpart, *index=0, children=0, totseam=0;
974         //int *vertpart=0;
975         int jitlevel= 1, distr;
976         float *weight=0,*sum=0,*jitoff=0;
977         float cur, maxweight=0.0, tweight, totweight, co[3], nor[3], orco[3], ornor[3];
978         
979         if(ob==0 || psys==0 || psys->part==0)
980                 return 0;
981
982         part=psys->part;
983         totpart=psys->totpart;
984         if(totpart==0)
985                 return 0;
986
987         if (!finaldm->deformedOnly && !CustomData_has_layer( &finaldm->faceData, CD_ORIGINDEX ) ) {
988 // XXX          error("Can't paint with the current modifier stack, disable destructive modifiers");
989                 return 0;
990         }
991
992         BLI_srandom(31415926 + psys->seed);
993         
994         if(from==PART_FROM_CHILD){
995                 distr=PART_DISTR_RAND;
996                 if(part->from!=PART_FROM_PARTICLE && part->childtype==PART_CHILD_FACES){
997                         dm= finaldm;
998                         children=1;
999
1000                         tree=BLI_kdtree_new(totpart);
1001
1002                         for(p=0,pa=psys->particles; p<totpart; p++,pa++){
1003                                 psys_particle_on_dm(dm,part->from,pa->num,pa->num_dmcache,pa->fuv,pa->foffset,co,nor,0,0,orco,ornor);
1004                                 transform_mesh_orco_verts((Mesh*)ob->data, &orco, 1, 1);
1005                                 BLI_kdtree_insert(tree, p, orco, ornor);
1006                         }
1007
1008                         BLI_kdtree_balance(tree);
1009
1010                         totpart=get_psys_tot_child(scene, psys);
1011                         cfrom=from=PART_FROM_FACE;
1012
1013                         if(part->flag&PART_CHILD_SEAMS){
1014                                 MEdge *ed, *medge=dm->getEdgeDataArray(dm,CD_MEDGE);
1015                                 MVert *mvert=dm->getVertDataArray(dm,CD_MVERT);
1016                                 int totedge=dm->getNumEdges(dm);
1017
1018                                 for(p=0, ed=medge; p<totedge; p++,ed++)
1019                                         if(ed->flag&ME_SEAM)
1020                                                 totseam++;
1021
1022                                 if(totseam){
1023                                         ParticleSeam *cur_seam=seams=MEM_callocN(totseam*sizeof(ParticleSeam),"Child Distribution Seams");
1024                                         float temp[3],temp2[3];
1025
1026                                         for(p=0, ed=medge; p<totedge; p++,ed++){
1027                                                 if(ed->flag&ME_SEAM){
1028                                                         VecCopyf(cur_seam->v0,(mvert+ed->v1)->co);
1029                                                         VecCopyf(cur_seam->v1,(mvert+ed->v2)->co);
1030
1031                                                         VecSubf(cur_seam->dir,cur_seam->v1,cur_seam->v0);
1032
1033                                                         cur_seam->length2=VecLength(cur_seam->dir);
1034                                                         cur_seam->length2*=cur_seam->length2;
1035
1036                                                         temp[0]=(float)((mvert+ed->v1)->no[0]);
1037                                                         temp[1]=(float)((mvert+ed->v1)->no[1]);
1038                                                         temp[2]=(float)((mvert+ed->v1)->no[2]);
1039                                                         temp2[0]=(float)((mvert+ed->v2)->no[0]);
1040                                                         temp2[1]=(float)((mvert+ed->v2)->no[1]);
1041                                                         temp2[2]=(float)((mvert+ed->v2)->no[2]);
1042
1043                                                         VecAddf(cur_seam->nor,temp,temp2);
1044                                                         Normalize(cur_seam->nor);
1045
1046                                                         Crossf(cur_seam->tan,cur_seam->dir,cur_seam->nor);
1047
1048                                                         Normalize(cur_seam->tan);
1049
1050                                                         cur_seam++;
1051                                                 }
1052                                         }
1053                                 }
1054                                 
1055                         }
1056                 }
1057                 else{
1058                         /* no need to figure out distribution */
1059                         int child_nbr= get_psys_child_number(scene, psys);
1060
1061                         totpart= get_psys_tot_child(scene, psys);
1062                         alloc_child_particles(psys, totpart);
1063                         cpa=psys->child;
1064                         for(i=0; i<child_nbr; i++){
1065                                 for(p=0; p<psys->totpart; p++,cpa++){
1066                                         float length=2.0;
1067                                         cpa->parent=p;
1068                                         
1069                                         /* create even spherical distribution inside unit sphere */
1070                                         while(length>=1.0f){
1071                                                 cpa->fuv[0]=2.0f*BLI_frand()-1.0f;
1072                                                 cpa->fuv[1]=2.0f*BLI_frand()-1.0f;
1073                                                 cpa->fuv[2]=2.0f*BLI_frand()-1.0f;
1074                                                 length=VecLength(cpa->fuv);
1075                                         }
1076
1077                                         cpa->rand[0]=BLI_frand();
1078                                         cpa->rand[1]=BLI_frand();
1079                                         cpa->rand[2]=BLI_frand();
1080
1081                                         cpa->num=-1;
1082                                 }
1083                         }
1084
1085                         return 0;
1086                 }
1087         }
1088         else{
1089                 dm= CDDM_from_mesh((Mesh*)ob->data, ob);
1090
1091                 /* special handling of grid distribution */
1092                 if(part->distr==PART_DISTR_GRID && from != PART_FROM_VERT){
1093                         distribute_particles_in_grid(dm,psys);
1094                         dm->release(dm);
1095                         return 0;
1096                 }
1097
1098                 /* we need orco for consistent distributions */
1099                 DM_add_vert_layer(dm, CD_ORCO, CD_ASSIGN, get_mesh_orco_verts(ob));
1100
1101                 distr=part->distr;
1102                 pa=psys->particles;
1103                 if(from==PART_FROM_VERT){
1104                         MVert *mv= dm->getVertDataArray(dm, CD_MVERT);
1105                         float (*orcodata)[3]= dm->getVertDataArray(dm, CD_ORCO);
1106                         int totvert = dm->getNumVerts(dm);
1107
1108                         tree=BLI_kdtree_new(totvert);
1109
1110                         for(p=0; p<totvert; p++){
1111                                 if(orcodata) {
1112                                         VECCOPY(co,orcodata[p])
1113                                         transform_mesh_orco_verts((Mesh*)ob->data, &co, 1, 1);
1114                                 }
1115                                 else
1116                                         VECCOPY(co,mv[p].co)
1117                                 BLI_kdtree_insert(tree,p,co,NULL);
1118                         }
1119
1120                         BLI_kdtree_balance(tree);
1121                 }
1122         }
1123
1124         /* 1. */
1125         switch(from){
1126                 case PART_FROM_VERT:
1127                         tot = dm->getNumVerts(dm);
1128                         break;
1129                 case PART_FROM_VOLUME:
1130                 case PART_FROM_FACE:
1131                         tot = dm->getNumFaces(dm);
1132                         break;
1133                 case PART_FROM_PARTICLE:
1134                         if(psys->target_ob)
1135                                 tob=psys->target_ob;
1136                         else
1137                                 tob=ob;
1138
1139                         if((tpsys=BLI_findlink(&tob->particlesystem,psys->target_psys-1))){
1140                                 tpars=tpsys->particles;
1141                                 tot=tpsys->totpart;
1142                         }
1143                         break;
1144         }
1145
1146         if(tot==0){
1147                 no_distr=1;
1148                 if(children){
1149                         if(G.f & G_DEBUG)
1150                                 fprintf(stderr,"Particle child distribution error: Nothing to emit from!\n");
1151                         if(psys->child) {
1152                                 for(p=0,cpa=psys->child; p<totpart; p++,cpa++){
1153                                         cpa->fuv[0]=cpa->fuv[1]=cpa->fuv[2]=cpa->fuv[3]= 0.0;
1154                                         cpa->foffset= 0.0f;
1155                                         cpa->parent=0;
1156                                         cpa->pa[0]=cpa->pa[1]=cpa->pa[2]=cpa->pa[3]=0;
1157                                         cpa->num= -1;
1158                                 }
1159                         }
1160                 }
1161                 else {
1162                         if(G.f & G_DEBUG)
1163                                 fprintf(stderr,"Particle distribution error: Nothing to emit from!\n");
1164                         for(p=0,pa=psys->particles; p<totpart; p++,pa++){
1165                                 pa->fuv[0]=pa->fuv[1]=pa->fuv[2]= pa->fuv[3]= 0.0;
1166                                 pa->foffset= 0.0f;
1167                                 pa->num= -1;
1168                         }
1169                 }
1170
1171                 if(dm != finaldm) dm->release(dm);
1172                 return 0;
1173         }
1174
1175         /* 2. */
1176
1177         weight=MEM_callocN(sizeof(float)*tot, "particle_distribution_weights");
1178         index=MEM_callocN(sizeof(int)*totpart, "particle_distribution_indexes");
1179         sum=MEM_callocN(sizeof(float)*(tot+1), "particle_distribution_sum");
1180         jitoff=MEM_callocN(sizeof(float)*tot, "particle_distribution_jitoff");
1181
1182         /* 2.1 */
1183         if((part->flag&PART_EDISTR || children) && ELEM(from,PART_FROM_PARTICLE,PART_FROM_VERT)==0){
1184                 MVert *v1, *v2, *v3, *v4;
1185                 float totarea=0.0, co1[3], co2[3], co3[3], co4[3];
1186                 float (*orcodata)[3];
1187                 
1188                 orcodata= dm->getVertDataArray(dm, CD_ORCO);
1189
1190                 for(i=0; i<tot; i++){
1191                         MFace *mf=dm->getFaceData(dm,i,CD_MFACE);
1192
1193                         if(orcodata) {
1194                                 VECCOPY(co1, orcodata[mf->v1]);
1195                                 VECCOPY(co2, orcodata[mf->v2]);
1196                                 VECCOPY(co3, orcodata[mf->v3]);
1197                                 transform_mesh_orco_verts((Mesh*)ob->data, &co1, 1, 1);
1198                                 transform_mesh_orco_verts((Mesh*)ob->data, &co2, 1, 1);
1199                                 transform_mesh_orco_verts((Mesh*)ob->data, &co3, 1, 1);
1200                         }
1201                         else {
1202                                 v1= (MVert*)dm->getVertData(dm,mf->v1,CD_MVERT);
1203                                 v2= (MVert*)dm->getVertData(dm,mf->v2,CD_MVERT);
1204                                 v3= (MVert*)dm->getVertData(dm,mf->v3,CD_MVERT);
1205                                 VECCOPY(co1, v1->co);
1206                                 VECCOPY(co2, v2->co);
1207                                 VECCOPY(co3, v3->co);
1208                         }
1209
1210                         if (mf->v4){
1211                                 if(orcodata) {
1212                                         VECCOPY(co4, orcodata[mf->v4]);
1213                                         transform_mesh_orco_verts((Mesh*)ob->data, &co4, 1, 1);
1214                                 }
1215                                 else {
1216                                         v4= (MVert*)dm->getVertData(dm,mf->v4,CD_MVERT);
1217                                         VECCOPY(co4, v4->co);
1218                                 }
1219                                 cur= AreaQ3Dfl(co1, co2, co3, co4);
1220                         }
1221                         else
1222                                 cur= AreaT3Dfl(co1, co2, co3);
1223                         
1224                         if(cur>maxweight)
1225                                 maxweight=cur;
1226
1227                         weight[i]= cur;
1228                         totarea+=cur;
1229                 }
1230
1231                 for(i=0; i<tot; i++)
1232                         weight[i] /= totarea;
1233
1234                 maxweight /= totarea;
1235         }
1236         else if(from==PART_FROM_PARTICLE){
1237                 float val=(float)tot/(float)totpart;
1238                 for(i=0; i<tot; i++)
1239                         weight[i]=val;
1240                 maxweight=val;
1241         }
1242         else{
1243                 float min=1.0f/(float)(MIN2(tot,totpart));
1244                 for(i=0; i<tot; i++)
1245                         weight[i]=min;
1246                 maxweight=min;
1247         }
1248
1249         /* 2.2 */
1250         if(ELEM3(from,PART_FROM_VERT,PART_FROM_FACE,PART_FROM_VOLUME)){
1251                 float *vweight= psys_cache_vgroup(dm,psys,PSYS_VG_DENSITY);
1252
1253                 if(vweight){
1254                         if(from==PART_FROM_VERT) {
1255                                 for(i=0;i<tot; i++)
1256                                         weight[i]*=vweight[i];
1257                         }
1258                         else { /* PART_FROM_FACE / PART_FROM_VOLUME */
1259                                 for(i=0;i<tot; i++){
1260                                         MFace *mf=dm->getFaceData(dm,i,CD_MFACE);
1261                                         tweight = vweight[mf->v1] + vweight[mf->v2] + vweight[mf->v3];
1262                                 
1263                                         if(mf->v4) {
1264                                                 tweight += vweight[mf->v4];
1265                                                 tweight /= 4.0;
1266                                         }
1267                                         else {
1268                                                 tweight /= 3.0;
1269                                         }
1270
1271                                         weight[i]*=tweight;
1272                                 }
1273                         }
1274                         MEM_freeN(vweight);
1275                 }
1276         }
1277
1278         /* 3. */
1279         totweight= 0.0f;
1280         for(i=0;i<tot; i++)
1281                 totweight += weight[i];
1282
1283         if(totweight > 0.0f)
1284                 totweight= 1.0f/totweight;
1285
1286         sum[0]= 0.0f;
1287         for(i=0;i<tot; i++)
1288                 sum[i+1]= sum[i]+weight[i]*totweight;
1289         
1290         if((part->flag&PART_TRAND) || (part->simplify_flag&PART_SIMPLIFY_ENABLE)) {
1291                 float pos;
1292
1293                 for(p=0; p<totpart; p++) {
1294                         pos= BLI_frand();
1295                         index[p]= binary_search_distribution(sum, tot, pos);
1296                         index[p]= MIN2(tot-1, index[p]);
1297                         jitoff[index[p]]= pos;
1298                 }
1299         }
1300         else {
1301                 double step, pos;
1302                 
1303                 step= (totpart <= 1)? 0.5: 1.0/(totpart-1);
1304                 pos= 1e-16f; /* tiny offset to avoid zero weight face */
1305                 i= 0;
1306
1307                 for(p=0; p<totpart; p++, pos+=step) {
1308                         while((i < tot) && (pos > sum[i+1]))
1309                                 i++;
1310
1311                         index[p]= MIN2(tot-1, i);
1312
1313                         /* avoid zero weight face */
1314                         if(p == totpart-1 && weight[index[p]] == 0.0f)
1315                                 index[p]= index[p-1];
1316
1317                         jitoff[index[p]]= pos;
1318                 }
1319         }
1320
1321         MEM_freeN(sum);
1322
1323         /* for hair, sort by origindex, allows optimizations in rendering */
1324         /* however with virtual parents the children need to be in random order */
1325         if(part->type == PART_HAIR && !(part->childtype==PART_CHILD_FACES && part->parents!=0.0)) {
1326                 if(from != PART_FROM_PARTICLE) {
1327                         COMPARE_ORIG_INDEX = NULL;
1328
1329                         if(from == PART_FROM_VERT) {
1330                                 if(dm->numVertData)
1331                                         COMPARE_ORIG_INDEX= dm->getVertDataArray(dm, CD_ORIGINDEX);
1332                         }
1333                         else {
1334                                 if(dm->numFaceData)
1335                                         COMPARE_ORIG_INDEX= dm->getFaceDataArray(dm, CD_ORIGINDEX);
1336                         }
1337
1338                         if(COMPARE_ORIG_INDEX) {
1339                                 qsort(index, totpart, sizeof(int), compare_orig_index);
1340                                 COMPARE_ORIG_INDEX = NULL;
1341                         }
1342                 }
1343         }
1344
1345         /* weights are no longer used except for FROM_PARTICLE, which needs them zeroed for indexing */
1346         if(from==PART_FROM_PARTICLE){
1347                 for(i=0; i<tot; i++)
1348                         weight[i]=0.0f;
1349         }
1350
1351         /* 4. */
1352         if(distr==PART_DISTR_JIT && ELEM(from,PART_FROM_FACE,PART_FROM_VOLUME)) {
1353                 jitlevel= part->userjit;
1354                 
1355                 if(jitlevel == 0) {
1356                         jitlevel= totpart/tot;
1357                         if(part->flag & PART_EDISTR) jitlevel*= 2;      /* looks better in general, not very scietific */
1358                         if(jitlevel<3) jitlevel= 3;
1359                         //if(jitlevel>100) jitlevel= 100;
1360                 }
1361                 
1362                 jit= MEM_callocN((2+ jitlevel*2)*sizeof(float), "jit");
1363
1364                 /* for small amounts of particles we use regular jitter since it looks
1365                  * a bit better, for larger amounts we switch to hammersley sequence 
1366                  * because it is much faster */
1367                 if(jitlevel < 25)
1368                         init_mv_jit(jit, jitlevel, psys->seed, part->jitfac);
1369                 else
1370                         hammersley_create(jit, jitlevel+1, psys->seed, part->jitfac);
1371                 BLI_array_randomize(jit, 2*sizeof(float), jitlevel, psys->seed); /* for custom jit or even distribution */
1372         }
1373
1374         /* 5. */
1375         ctx->tree= tree;
1376         ctx->seams= seams;
1377         ctx->totseam= totseam;
1378         ctx->psys= psys;
1379         ctx->index= index;
1380         ctx->jit= jit;
1381         ctx->jitlevel= jitlevel;
1382         ctx->jitoff= jitoff;
1383         ctx->weight= weight;
1384         ctx->maxweight= maxweight;
1385         ctx->from= (children)? PART_FROM_CHILD: from;
1386         ctx->cfrom= cfrom;
1387         ctx->distr= distr;
1388         ctx->dm= dm;
1389         ctx->tpars= tpars;
1390
1391         if(children) {
1392                 totpart= psys_render_simplify_distribution(ctx, totpart);
1393                 alloc_child_particles(psys, totpart);
1394         }
1395
1396         if(!children || psys->totchild < 10000)
1397                 totthread= 1;
1398         
1399         seed= 31415926 + ctx->psys->seed;
1400         for(i=0; i<totthread; i++) {
1401                 threads[i].rng= rng_new(seed);
1402                 threads[i].tot= totthread;
1403         }
1404
1405         return 1;
1406 }
1407
1408 static void distribute_particles_on_dm(DerivedMesh *finaldm, Scene *scene, Object *ob, ParticleSystem *psys, int from)
1409 {
1410         ListBase threads;
1411         ParticleThread *pthreads;
1412         ParticleThreadContext *ctx;
1413         int i, totthread;
1414
1415         pthreads= psys_threads_create(scene, ob, psys);
1416
1417         if(!psys_threads_init_distribution(pthreads, scene, finaldm, from)) {
1418                 psys_threads_free(pthreads);
1419                 return;
1420         }
1421
1422         totthread= pthreads[0].tot;
1423         if(totthread > 1) {
1424                 BLI_init_threads(&threads, exec_distribution, totthread);
1425
1426                 for(i=0; i<totthread; i++)
1427                         BLI_insert_thread(&threads, &pthreads[i]);
1428
1429                 BLI_end_threads(&threads);
1430         }
1431         else
1432                 exec_distribution(&pthreads[0]);
1433
1434         psys_calc_dmcache(ob, finaldm, psys);
1435
1436         ctx= pthreads[0].ctx;
1437         if(ctx->dm != finaldm)
1438                 ctx->dm->release(ctx->dm);
1439
1440         psys_threads_free(pthreads);
1441 }
1442
1443 /* ready for future use, to emit particles without geometry */
1444 static void distribute_particles_on_shape(Object *ob, ParticleSystem *psys, int from)
1445 {
1446         ParticleData *pa;
1447         int totpart=psys->totpart, p;
1448
1449         fprintf(stderr,"Shape emission not yet possible!\n");
1450
1451         for(p=0,pa=psys->particles; p<totpart; p++,pa++){
1452                 pa->fuv[0]=pa->fuv[1]=pa->fuv[2]=pa->fuv[3]= 0.0;
1453                 pa->foffset= 0.0f;
1454                 pa->num= -1;
1455         }
1456 }
1457 static void distribute_particles(Scene *scene, Object *ob, ParticleSystem *psys, int from)
1458 {
1459         ParticleSystemModifierData *psmd=0;
1460         int distr_error=0;
1461         psmd=psys_get_modifier(ob,psys);
1462
1463         if(psmd){
1464                 if(psmd->dm)
1465                         distribute_particles_on_dm(psmd->dm, scene, ob, psys, from);
1466                 else
1467                         distr_error=1;
1468         }
1469         else
1470                 distribute_particles_on_shape(ob,psys,from);
1471
1472         if(distr_error){
1473                 ParticleData *pa;
1474                 int totpart=psys->totpart, p;
1475
1476                 fprintf(stderr,"Particle distribution error!\n");
1477
1478                 for(p=0,pa=psys->particles; p<totpart; p++,pa++){
1479                         pa->fuv[0]=pa->fuv[1]=pa->fuv[2]=pa->fuv[3]= 0.0;
1480                         pa->foffset= 0.0f;
1481                         pa->num= -1;
1482                 }
1483         }
1484 }
1485
1486 /* threaded child particle distribution and path caching */
1487 ParticleThread *psys_threads_create(struct Scene *scene, struct Object *ob, struct ParticleSystem *psys)
1488 {
1489         ParticleThread *threads;
1490         ParticleThreadContext *ctx;
1491         int i, totthread;
1492
1493         if(scene->r.mode & R_FIXED_THREADS)
1494                 totthread= scene->r.threads;
1495         else
1496                 totthread= BLI_system_thread_count();
1497         
1498         threads= MEM_callocN(sizeof(ParticleThread)*totthread, "ParticleThread");
1499         ctx= MEM_callocN(sizeof(ParticleThreadContext), "ParticleThreadContext");
1500
1501         ctx->scene= scene;
1502         ctx->ob= ob;
1503         ctx->psys= psys;
1504         ctx->psmd= psys_get_modifier(ob, psys);
1505         ctx->dm= ctx->psmd->dm;
1506         ctx->ma= give_current_material(ob, psys->part->omat);
1507
1508         memset(threads, 0, sizeof(ParticleThread)*totthread);
1509
1510         for(i=0; i<totthread; i++) {
1511                 threads[i].ctx= ctx;
1512                 threads[i].num= i;
1513                 threads[i].tot= totthread;
1514         }
1515
1516         return threads;
1517 }
1518
1519 void psys_threads_free(ParticleThread *threads)
1520 {
1521         ParticleThreadContext *ctx= threads[0].ctx;
1522         int i, totthread= threads[0].tot;
1523
1524         /* path caching */
1525         if(ctx->vg_length)
1526                 MEM_freeN(ctx->vg_length);
1527         if(ctx->vg_clump)
1528                 MEM_freeN(ctx->vg_clump);
1529         if(ctx->vg_kink)
1530                 MEM_freeN(ctx->vg_kink);
1531         if(ctx->vg_rough1)
1532                 MEM_freeN(ctx->vg_rough1);
1533         if(ctx->vg_rough2)
1534                 MEM_freeN(ctx->vg_rough2);
1535         if(ctx->vg_roughe)
1536                 MEM_freeN(ctx->vg_roughe);
1537
1538         if(ctx->psys->lattice){
1539                 end_latt_deform(ctx->psys->lattice);
1540                 ctx->psys->lattice= NULL;
1541         }
1542
1543         /* distribution */
1544         if(ctx->jit) MEM_freeN(ctx->jit);
1545         if(ctx->jitoff) MEM_freeN(ctx->jitoff);
1546         if(ctx->weight) MEM_freeN(ctx->weight);
1547         if(ctx->index) MEM_freeN(ctx->index);
1548         if(ctx->skip) MEM_freeN(ctx->skip);
1549         if(ctx->seams) MEM_freeN(ctx->seams);
1550         //if(ctx->vertpart) MEM_freeN(ctx->vertpart);
1551         BLI_kdtree_free(ctx->tree);
1552
1553         /* threads */
1554         for(i=0; i<totthread; i++) {
1555                 if(threads[i].rng)
1556                         rng_free(threads[i].rng);
1557                 if(threads[i].rng_path)
1558                         rng_free(threads[i].rng_path);
1559         }
1560
1561         MEM_freeN(ctx);
1562         MEM_freeN(threads);
1563 }
1564
1565 /* set particle parameters that don't change during particle's life */
1566 void initialize_particle(ParticleData *pa, int p, Object *ob, ParticleSystem *psys, ParticleSystemModifierData *psmd)
1567 {
1568         ParticleSettings *part;
1569         ParticleTexture ptex;
1570         Material *ma=0;
1571         //IpoCurve *icu=0; // XXX old animation system
1572         int totpart;
1573         float rand,length;
1574
1575         part=psys->part;
1576
1577         totpart=psys->totpart;
1578
1579         ptex.life=ptex.size=ptex.exist=ptex.length=1.0;
1580         ptex.time=(float)p/(float)totpart;
1581
1582         BLI_srandom(psys->seed+p);
1583
1584         if(part->from!=PART_FROM_PARTICLE && part->type!=PART_FLUID){
1585                 ma=give_current_material(ob,part->omat);
1586
1587                 /* TODO: needs some work to make most blendtypes generally usefull */
1588                 psys_get_texture(ob,ma,psmd,psys,pa,&ptex,MAP_PA_INIT);
1589         }
1590         
1591         pa->lifetime= part->lifetime*ptex.life;
1592
1593         if(part->type==PART_HAIR)
1594                 pa->time= 0.0f;
1595         else if(part->type==PART_REACTOR && (part->flag&PART_REACT_STA_END)==0)
1596                 pa->time= 300000.0f;    /* max frame */
1597         else{
1598                 //icu=find_ipocurve(psys->part->ipo,PART_EMIT_TIME);
1599                 //if(icu){
1600                 //      calc_icu(icu,100*ptex.time);
1601                 //      ptex.time=icu->curval;
1602                 //}
1603
1604                 pa->time= part->sta + (part->end - part->sta)*ptex.time;
1605         }
1606
1607
1608         if(part->type==PART_HAIR){
1609                 pa->lifetime=100.0f;
1610         }
1611         else{
1612 #if 0 // XXX old animation system
1613                 icu=find_ipocurve(psys->part->ipo,PART_EMIT_LIFE);
1614                 if(icu){
1615                         calc_icu(icu,100*ptex.time);
1616                         pa->lifetime*=icu->curval;
1617                 }
1618 #endif // XXX old animation system
1619
1620         /* need to get every rand even if we don't use them so that randoms don't affect each other */
1621                 rand= BLI_frand();
1622                 if(part->randlife!=0.0)
1623                         pa->lifetime*= 1.0f - part->randlife*rand;
1624         }
1625
1626         pa->dietime= pa->time+pa->lifetime;
1627
1628         pa->sizemul= BLI_frand();
1629
1630         rand= BLI_frand();
1631
1632         /* while loops are to have a spherical distribution (avoid cubic distribution) */
1633         if(part->phystype != PART_PHYS_BOIDS) {
1634                 /* boids store gravity in r_ve, so skip here */
1635                 length=2.0f;
1636                 while(length>1.0){
1637                         pa->r_ve[0]=2.0f*(BLI_frand()-0.5f);
1638                         pa->r_ve[1]=2.0f*(BLI_frand()-0.5f);
1639                         pa->r_ve[2]=2.0f*(BLI_frand()-0.5f);
1640                         length=VecLength(pa->r_ve);
1641                 }
1642         }
1643
1644         length=2.0f;
1645         while(length>1.0){
1646                 pa->r_ave[0]=2.0f*(BLI_frand()-0.5f);
1647                 pa->r_ave[1]=2.0f*(BLI_frand()-0.5f);
1648                 pa->r_ave[2]=2.0f*(BLI_frand()-0.5f);
1649                 length=VecLength(pa->r_ave);
1650         }
1651
1652         pa->r_rot[0]=2.0f*(BLI_frand()-0.5f);
1653         pa->r_rot[1]=2.0f*(BLI_frand()-0.5f);
1654         pa->r_rot[2]=2.0f*(BLI_frand()-0.5f);
1655         pa->r_rot[3]=2.0f*(BLI_frand()-0.5f);
1656
1657         NormalQuat(pa->r_rot);
1658
1659         if(part->type!=PART_HAIR && part->distr!=PART_DISTR_GRID && part->from != PART_FROM_VERT){
1660                 /* any unique random number will do (r_ave[0]) */
1661                 if(ptex.exist < 0.5*(1.0+pa->r_ave[0]))
1662                         pa->flag |= PARS_UNEXIST;
1663                 else
1664                         pa->flag &= ~PARS_UNEXIST;
1665         }
1666
1667         pa->loop=0;
1668         /* we can't reset to -1 anymore since we've figured out correct index in distribute_particles */
1669         /* usage other than straight after distribute has to handle this index by itself - jahka*/
1670         //pa->num_dmcache = DMCACHE_NOTFOUND; /* assume we dont have a derived mesh face */
1671 }
1672 static void initialize_all_particles(Object *ob, ParticleSystem *psys, ParticleSystemModifierData *psmd)
1673 {
1674         //IpoCurve *icu=0; // XXX old animation system
1675         ParticleData *pa;
1676         int p, totpart=psys->totpart;
1677
1678         for(p=0, pa=psys->particles; p<totpart; p++, pa++)
1679                 initialize_particle(pa,p,ob,psys,psmd);
1680         
1681         if(psys->part->type != PART_FLUID) {
1682 #if 0 // XXX old animation system
1683                 icu=find_ipocurve(psys->part->ipo,PART_EMIT_FREQ);
1684                 if(icu){
1685                         float time=psys->part->sta, end=psys->part->end;
1686                         float v1, v2, a=0.0f, t1,t2, d;
1687
1688                         p=0;
1689                         pa=psys->particles;
1690
1691
1692                         calc_icu(icu,time);
1693                         v1=icu->curval;
1694                         if(v1<0.0f) v1=0.0f;
1695
1696                         calc_icu(icu,time+1.0f);
1697                         v2=icu->curval;
1698                         if(v2<0.0f) v2=0.0f;
1699
1700                         for(p=0, pa=psys->particles; p<totpart && time<end; p++, pa++){
1701                                 while(a+0.5f*(v1+v2) < (float)(p+1) && time<end){
1702                                         a+=0.5f*(v1+v2);
1703                                         v1=v2;
1704                                         time++;
1705                                         calc_icu(icu,time+1.0f);
1706                                         v2=icu->curval;
1707                                 }
1708                                 if(time<end){
1709                                         if(v1==v2){
1710                                                 pa->time=time+((float)(p+1)-a)/v1;
1711                                         }
1712                                         else{
1713                                                 d=(float)sqrt(v1*v1-2.0f*(v2-v1)*(a-(float)(p+1)));
1714                                                 t1=(-v1+d)/(v2-v1);
1715                                                 t2=(-v1-d)/(v2-v1);
1716
1717                                                 /* the root between 0-1 is the correct one */
1718                                                 if(t1>0.0f && t1<=1.0f)
1719                                                         pa->time=time+t1;
1720                                                 else
1721                                                         pa->time=time+t2;
1722                                         }
1723                                 }
1724
1725                                 pa->dietime = pa->time+pa->lifetime;
1726                                 pa->flag &= ~PARS_UNEXIST;
1727                         }
1728                         for(; p<totpart; p++, pa++){
1729                                 pa->flag |= PARS_UNEXIST;
1730                         }
1731                 }
1732 #endif // XXX old animation system
1733         }
1734 }
1735 /* sets particle to the emitter surface with initial velocity & rotation */
1736 void reset_particle(Scene *scene, ParticleData *pa, ParticleSystem *psys, ParticleSystemModifierData *psmd, Object *ob,
1737                                         float dtime, float cfra, float *vg_vel, float *vg_tan, float *vg_rot)
1738 {
1739         ParticleSettings *part;
1740         ParticleTexture ptex;
1741         ParticleKey state;
1742         //IpoCurve *icu=0; // XXX old animation system
1743         float fac, phasefac, nor[3]={0,0,0},loc[3],tloc[3],vel[3]={0.0,0.0,0.0},rot[4],q2[4];
1744         float r_vel[3],r_ave[3],r_rot[4],p_vel[3]={0.0,0.0,0.0};
1745         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};
1746         float q_phase[4];
1747         part=psys->part;
1748
1749         ptex.ivel=1.0;
1750         
1751         if(part->from==PART_FROM_PARTICLE){
1752                 Object *tob;
1753                 ParticleSystem *tpsys=0;
1754                 float speed;
1755
1756                 tob=psys->target_ob;
1757                 if(tob==0)
1758                         tob=ob;
1759
1760                 tpsys=BLI_findlink(&tob->particlesystem,psys->target_psys-1);
1761
1762                 state.time = pa->time;
1763                 if(pa->num == -1)
1764                         memset(&state, 0, sizeof(state));
1765                 else
1766                         psys_get_particle_state(scene, tob,tpsys,pa->num,&state,1);
1767                 psys_get_from_key(&state,loc,nor,rot,0);
1768
1769                 QuatMulVecf(rot,vtan);
1770                 QuatMulVecf(rot,utan);
1771                 VECCOPY(r_vel,pa->r_ve);
1772                 VECCOPY(r_rot,pa->r_rot);
1773                 VECCOPY(r_ave,pa->r_ave);
1774
1775                 VECCOPY(p_vel,state.vel);
1776                 speed=Normalize(p_vel);
1777                 VecMulf(p_vel,Inpf(pa->r_ve,p_vel));
1778                 VECSUB(p_vel,pa->r_ve,p_vel);
1779                 Normalize(p_vel);
1780                 VecMulf(p_vel,speed);
1781
1782                 VECCOPY(pa->fuv,loc); /* abusing pa->fuv (not used for "from particle") for storing emit location */
1783         }
1784         else{
1785                 /* get precise emitter matrix if particle is born */
1786                 if(part->type!=PART_HAIR && pa->time < cfra && pa->time >= psys->cfra)
1787                         where_is_object_time(scene, ob,pa->time);
1788
1789                 /* get birth location from object               */
1790                 if(part->tanfac!=0.0)
1791                         psys_particle_on_emitter(psmd,part->from,pa->num, pa->num_dmcache, pa->fuv,pa->foffset,loc,nor,utan,vtan,0,0);
1792                 else
1793                         psys_particle_on_emitter(psmd,part->from,pa->num, pa->num_dmcache, pa->fuv,pa->foffset,loc,nor,0,0,0,0);
1794                 
1795                 /* save local coordinates for later             */
1796                 VECCOPY(tloc,loc);
1797                 
1798                 /* get possible textural influence */
1799                 psys_get_texture(ob,give_current_material(ob,part->omat),psmd,psys,pa,&ptex,MAP_PA_IVEL);
1800
1801                 if(vg_vel && pa->num != -1)
1802                         ptex.ivel*=psys_particle_value_from_verts(psmd->dm,part->from,pa,vg_vel);
1803
1804                 /* particles live in global space so    */
1805                 /* let's convert:                                               */
1806                 /* -location                                                    */
1807                 Mat4MulVecfl(ob->obmat,loc);
1808                 
1809                 /* -normal                                                              */
1810                 VECADD(nor,tloc,nor);
1811                 Mat4MulVecfl(ob->obmat,nor);
1812                 VECSUB(nor,nor,loc);
1813                 Normalize(nor);
1814
1815                 /* -tangent                                                             */
1816                 if(part->tanfac!=0.0){
1817                         float phase=vg_rot?2.0f*(psys_particle_value_from_verts(psmd->dm,part->from,pa,vg_rot)-0.5f):0.0f;
1818                         VecMulf(vtan,-(float)cos(M_PI*(part->tanphase+phase)));
1819                         fac=-(float)sin(M_PI*(part->tanphase+phase));
1820                         VECADDFAC(vtan,vtan,utan,fac);
1821
1822                         VECADD(vtan,tloc,vtan);
1823                         Mat4MulVecfl(ob->obmat,vtan);
1824                         VECSUB(vtan,vtan,loc);
1825
1826                         VECCOPY(utan,nor);
1827                         VecMulf(utan,Inpf(vtan,nor));
1828                         VECSUB(vtan,vtan,utan);
1829                         
1830                         Normalize(vtan);
1831                 }
1832                 
1833
1834                 /* -velocity                                                    */
1835                 if(part->randfac!=0.0){
1836                         VECADD(r_vel,tloc,pa->r_ve);
1837                         Mat4MulVecfl(ob->obmat,r_vel);
1838                         VECSUB(r_vel,r_vel,loc);
1839                         Normalize(r_vel);
1840                 }
1841
1842                 /* -angular velocity                                    */
1843                 if(part->avemode==PART_AVE_RAND){
1844                         VECADD(r_ave,tloc,pa->r_ave);
1845                         Mat4MulVecfl(ob->obmat,r_ave);
1846                         VECSUB(r_ave,r_ave,loc);
1847                         Normalize(r_ave);
1848                 }
1849                 
1850                 /* -rotation                                                    */
1851                 if(part->randrotfac != 0.0f){
1852                         QUATCOPY(r_rot,pa->r_rot);
1853                         Mat4ToQuat(ob->obmat,rot);
1854                         QuatMul(r_rot,r_rot,rot);
1855                 }
1856         }
1857
1858         if(part->phystype==PART_PHYS_BOIDS) {
1859                 float dvec[3], q[4], mat[3][3];
1860
1861                 VECCOPY(pa->state.co,loc);
1862
1863                 /* boids don't get any initial velocity  */
1864                 pa->state.vel[0]=pa->state.vel[1]=pa->state.vel[2]=0.0f;
1865
1866                 /* boids store direction in ave */
1867                 if(fabs(nor[2])==1.0f) {
1868                         VecSubf(pa->state.ave, loc, ob->obmat[3]);
1869                         Normalize(pa->state.ave);
1870                 }
1871                 else {
1872                         VECCOPY(pa->state.ave, nor);
1873                 }
1874                 /* and gravity in r_ve */
1875                 pa->r_ve[0] = pa->r_ve[1] = 0.0f;
1876                 pa->r_ve[2] = -1.0f;
1877                 if(part->acc[2]!=0.0f)
1878                         pa->r_ve[2] = part->acc[2];
1879
1880                 /* calculate rotation matrix */
1881                 Projf(dvec, pa->r_ve, pa->state.ave);
1882                 VecSubf(mat[0], pa->state.ave, dvec);
1883                 Normalize(mat[0]);
1884                 VECCOPY(mat[2], pa->r_ve);
1885                 VecMulf(mat[2], -1.0f);
1886                 Normalize(mat[2]);
1887                 Crossf(mat[1], mat[2], mat[0]);
1888                 
1889                 /* apply rotation */
1890                 Mat3ToQuat_is_ok(mat, q);
1891                 QuatCopy(pa->state.rot, q);
1892
1893                 pa->boid->health = part->boids->health;
1894                 pa->boid->mode = eBoidMode_InAir;
1895                 pa->boid->state_id = ((BoidState*)part->boids->states.first)->id;
1896                 pa->boid->acc[0]=pa->boid->acc[1]=pa->boid->acc[2]=0.0f;
1897         }
1898         else {
1899                 /* conversion done so now we apply new: */
1900                 /* -velocity from:                                              */
1901
1902                 /*              *reactions                                              */
1903                 if(dtime>0.0f){
1904                         VECSUB(vel,pa->state.vel,pa->prev_state.vel);
1905                 }
1906
1907                 /*              *emitter velocity                               */
1908                 if(dtime!=0.0 && part->obfac!=0.0){
1909                         VECSUB(vel,loc,pa->state.co);
1910                         VecMulf(vel,part->obfac/dtime);
1911                 }
1912                 
1913                 /*              *emitter normal                                 */
1914                 if(part->normfac!=0.0)
1915                         VECADDFAC(vel,vel,nor,part->normfac);
1916                 
1917                 /*              *emitter tangent                                */
1918                 if(psmd && part->tanfac!=0.0)
1919                         VECADDFAC(vel,vel,vtan,part->tanfac*(vg_tan?psys_particle_value_from_verts(psmd->dm,part->from,pa,vg_tan):1.0f));
1920
1921                 /*              *texture                                                */
1922                 /* TODO */
1923
1924                 /*              *random                                                 */
1925                 if(part->randfac!=0.0)
1926                         VECADDFAC(vel,vel,r_vel,part->randfac);
1927
1928                 /*              *particle                                               */
1929                 if(part->partfac!=0.0)
1930                         VECADDFAC(vel,vel,p_vel,part->partfac);
1931
1932                 //icu=find_ipocurve(psys->part->ipo,PART_EMIT_VEL);
1933                 //if(icu){
1934                 //      calc_icu(icu,100*((pa->time-part->sta)/(part->end-part->sta)));
1935                 //      ptex.ivel*=icu->curval;
1936                 //}
1937
1938                 VecMulf(vel,ptex.ivel);
1939
1940                 //if(ELEM(part->phystype, PART_PHYS_GRADU_EX, PART_PHYS_GRADU_SIM))
1941                 //      VecAddf(vel,vel,part->acc);
1942                 
1943                 VECCOPY(pa->state.vel,vel);
1944
1945                 /* -location from emitter                               */
1946                 VECCOPY(pa->state.co,loc);
1947
1948                 /* -rotation                                                    */
1949                 pa->state.rot[0]=1.0;
1950                 pa->state.rot[1]=pa->state.rot[2]=pa->state.rot[3]=0.0;
1951
1952                 if(part->rotmode){
1953                         /* create vector into which rotation is aligned */
1954                         switch(part->rotmode){
1955                                 case PART_ROT_NOR:
1956                                         VecCopyf(rot_vec, nor);
1957                                         break;
1958                                 case PART_ROT_VEL:
1959                                         VecCopyf(rot_vec, vel);
1960                                         break;
1961                                 case PART_ROT_GLOB_X:
1962                                 case PART_ROT_GLOB_Y:
1963                                 case PART_ROT_GLOB_Z:
1964                                         rot_vec[part->rotmode - PART_ROT_GLOB_X] = 1.0f;
1965                                         break;
1966                                 case PART_ROT_OB_X:
1967                                 case PART_ROT_OB_Y:
1968                                 case PART_ROT_OB_Z:
1969                                         VecCopyf(rot_vec, ob->obmat[part->rotmode - PART_ROT_OB_X]);
1970                                         break;
1971                         }
1972                         
1973                         /* create rotation quat */
1974                         VecNegf(rot_vec);
1975                         vectoquat(rot_vec, OB_POSX, OB_POSZ, q2);
1976
1977                         /* randomize rotation quat */
1978                         if(part->randrotfac!=0.0f)
1979                                 QuatInterpol(rot, q2, r_rot, part->randrotfac);
1980                         else
1981                                 QuatCopy(rot,q2);
1982
1983                         /* rotation phase */
1984                         phasefac = part->phasefac;
1985                         if(part->randphasefac != 0.0f) /* abuse r_ave[0] as a random number */
1986                                 phasefac += part->randphasefac * pa->r_ave[0];
1987                         VecRotToQuat(x_vec, phasefac*(float)M_PI, q_phase);
1988
1989                         /* combine base rotation & phase */
1990                         QuatMul(pa->state.rot, rot, q_phase);
1991                 }
1992
1993                 /* -angular velocity                                    */
1994
1995                 pa->state.ave[0] = pa->state.ave[1] = pa->state.ave[2] = 0.0;
1996
1997                 if(part->avemode){
1998                         switch(part->avemode){
1999                                 case PART_AVE_SPIN:
2000                                         VECCOPY(pa->state.ave,vel);
2001                                         break;
2002                                 case PART_AVE_RAND:
2003                                         VECCOPY(pa->state.ave,r_ave);
2004                                         break;
2005                         }
2006                         Normalize(pa->state.ave);
2007                         VecMulf(pa->state.ave,part->avefac);
2008
2009                         //icu=find_ipocurve(psys->part->ipo,PART_EMIT_AVE);
2010                         //if(icu){
2011                         //      calc_icu(icu,100*((pa->time-part->sta)/(part->end-part->sta)));
2012                         //      VecMulf(pa->state.ave,icu->curval);
2013                         //}
2014                 }
2015         }
2016
2017         pa->dietime = pa->time + pa->lifetime;
2018
2019         if(pa->time >= cfra)
2020                 pa->alive = PARS_UNBORN;
2021
2022         pa->state.time = cfra;
2023
2024         pa->stick_ob = 0;
2025         pa->flag &= ~PARS_STICKY;
2026 }
2027 static void reset_all_particles(Scene *scene, Object *ob, ParticleSystem *psys, ParticleSystemModifierData *psmd, float dtime, float cfra, int from)
2028 {
2029         ParticleData *pa;
2030         int p, totpart=psys->totpart;
2031         float *vg_vel=psys_cache_vgroup(psmd->dm,psys,PSYS_VG_VEL);
2032         float *vg_tan=psys_cache_vgroup(psmd->dm,psys,PSYS_VG_TAN);
2033         float *vg_rot=psys_cache_vgroup(psmd->dm,psys,PSYS_VG_ROT);
2034         
2035         for(p=from, pa=psys->particles+from; p<totpart; p++, pa++)
2036                 reset_particle(scene, pa, psys, psmd, ob, dtime, cfra, vg_vel, vg_tan, vg_rot);
2037
2038         if(vg_vel)
2039                 MEM_freeN(vg_vel);
2040 }
2041 /************************************************/
2042 /*                      Particle targets                                        */
2043 /************************************************/
2044 ParticleSystem *psys_get_target_system(Object *ob, ParticleTarget *pt)
2045 {
2046         ParticleSystem *psys = NULL;
2047
2048         if(pt->ob == NULL || pt->ob == ob)
2049                 psys = BLI_findlink(&ob->particlesystem, pt->psys-1);
2050         else
2051                 psys = BLI_findlink(&pt->ob->particlesystem, pt->psys-1);
2052
2053         if(psys)
2054                 pt->flag |= PTARGET_VALID;
2055         else
2056                 pt->flag &= ~PTARGET_VALID;
2057
2058         return psys;
2059 }
2060 /************************************************/
2061 /*                      Keyed particles                                         */
2062 /************************************************/
2063 /* Counts valid keyed targets */
2064 void psys_count_keyed_targets(Object *ob, ParticleSystem *psys)
2065 {
2066         ParticleSystem *kpsys;
2067         ParticleTarget *pt = psys->targets.first;
2068         int keys_valid = 1;
2069         psys->totkeyed = 0;
2070
2071         for(; pt; pt=pt->next) {
2072                 kpsys = psys_get_target_system(ob, pt);
2073
2074                 if(kpsys && kpsys->totpart) {
2075                         psys->totkeyed += keys_valid;
2076                         if(psys->flag & PSYS_KEYED_TIMING && pt->duration != 0.0f)
2077                                 psys->totkeyed += 1;
2078                 }
2079                 else {
2080                         keys_valid = 0;
2081                 }
2082         }
2083
2084         psys->totkeyed *= psys->flag & PSYS_KEYED_TIMING ? 1 : psys->part->keyed_loops;
2085 }
2086
2087 static void set_keyed_keys(Scene *scene, Object *ob, ParticleSystem *psys)
2088 {
2089         ParticleSystem *kpsys = psys;
2090         ParticleTarget *pt;
2091         ParticleData *pa;
2092         int totpart = psys->totpart, i, k, totkeys = psys->totkeyed;
2093
2094         /* no proper targets so let's clear and bail out */
2095         if(psys->totkeyed==0) {
2096                 free_keyed_keys(psys);
2097                 psys->flag &= ~PSYS_KEYED;
2098                 return;
2099         }
2100
2101         if(totpart && psys->particles->totkey != totkeys) {
2102                 free_keyed_keys(psys);
2103                 
2104                 psys->particles->keys = MEM_callocN(totpart*totkeys*sizeof(ParticleKey), "Keyed keys");
2105                 psys->particles->totkey = totkeys;
2106                 
2107                 for(i=1, pa=psys->particles+1; i<totpart; i++,pa++){
2108                         pa->keys = (pa-1)->keys + totkeys;
2109                         pa->totkey = totkeys;
2110                 }
2111         }
2112         
2113         psys->flag &= ~PSYS_KEYED;
2114
2115
2116         pt = psys->targets.first;
2117         for(k=0; k<totkeys; k++) {
2118                 if(pt->ob)
2119                         kpsys = BLI_findlink(&pt->ob->particlesystem, pt->psys - 1);
2120                 else
2121                         kpsys = BLI_findlink(&ob->particlesystem, pt->psys - 1);
2122
2123                 for(i=0,pa=psys->particles; i<totpart; i++, pa++) {
2124                         (pa->keys + k)->time = -1.0; /* use current time */
2125
2126                         psys_get_particle_state(scene, pt->ob, kpsys, i%kpsys->totpart, pa->keys + k, 1);
2127
2128                         if(psys->flag & PSYS_KEYED_TIMING){
2129                                 (pa->keys+k)->time = pa->time + pt->time;
2130                                 if(pt->duration != 0.0f && k+1 < totkeys) {
2131                                         copy_particle_key(pa->keys+k+1, pa->keys+k, 1);
2132                                         (pa->keys+k+1)->time = pa->time + pt->time + pt->duration;
2133                                 }
2134                         }
2135                         else if(totkeys > 1)
2136                                 (pa->keys+k)->time = pa->time + (float)k / (float)(totkeys - 1) * pa->lifetime;
2137                         else
2138                                 pa->keys->time = pa->time;
2139                 }
2140
2141                 if(psys->flag & PSYS_KEYED_TIMING && pt->duration!=0.0f)
2142                         k++;
2143
2144                 pt = (pt->next && pt->next->flag & PTARGET_VALID)? pt->next : psys->targets.first;
2145         }
2146
2147         psys->flag |= PSYS_KEYED;
2148 }
2149 /************************************************/
2150 /*                      Reactors                                                        */
2151 /************************************************/
2152 static void push_reaction(Object* ob, ParticleSystem *psys, int pa_num, int event, ParticleKey *state)
2153 {
2154         Object *rob;
2155         ParticleSystem *rpsys;
2156         ParticleSettings *rpart;
2157         ParticleData *pa;
2158         ListBase *lb=&psys->effectors;
2159         ParticleEffectorCache *ec;
2160         ParticleReactEvent *re;
2161
2162         if(lb->first) for(ec = lb->first; ec; ec= ec->next){
2163                 if(ec->type & PSYS_EC_REACTOR){
2164                         /* all validity checks already done in add_to_effectors */
2165                         rob=ec->ob;
2166                         rpsys=BLI_findlink(&rob->particlesystem,ec->psys_nbr);
2167                         rpart=rpsys->part;
2168                         if(rpsys->part->reactevent==event){
2169                                 pa=psys->particles+pa_num;
2170                                 re= MEM_callocN(sizeof(ParticleReactEvent), "react event");
2171                                 re->event=event;
2172                                 re->pa_num = pa_num;
2173                                 re->ob = ob;
2174                                 re->psys = psys;
2175                                 re->size = pa->size;
2176                                 copy_particle_key(&re->state,state,1);
2177
2178                                 switch(event){
2179                                         case PART_EVENT_DEATH:
2180                                                 re->time=pa->dietime;
2181                                                 break;
2182                                         case PART_EVENT_COLLIDE:
2183                                                 re->time=state->time;
2184                                                 break;
2185                                         case PART_EVENT_NEAR:
2186                                                 re->time=state->time;
2187                                                 break;
2188                                 }
2189
2190                                 BLI_addtail(&rpsys->reactevents, re);
2191                         }
2192                 }
2193         }
2194 }
2195 static void react_to_events(ParticleSystem *psys, int pa_num)
2196 {
2197         ParticleSettings *part=psys->part;
2198         ParticleData *pa=psys->particles+pa_num;
2199         ParticleReactEvent *re=psys->reactevents.first;
2200         int birth=0;
2201         float dist=0.0f;
2202
2203         for(re=psys->reactevents.first; re; re=re->next){
2204                 birth=0;
2205                 if(part->from==PART_FROM_PARTICLE){
2206                         if(pa->num==re->pa_num && pa->alive==PARS_UNBORN){
2207                                 if(re->event==PART_EVENT_NEAR){
2208                                         ParticleData *tpa = re->psys->particles+re->pa_num;
2209                                         float pa_time=tpa->time + pa->foffset*tpa->lifetime;
2210                                         if(re->time >= pa_time){
2211                                                 pa->time=pa_time;
2212                                                 pa->dietime=pa->time+pa->lifetime;
2213                                         }
2214                                 }
2215                                 else{
2216                                         pa->time=re->time;
2217                                         pa->dietime=pa->time+pa->lifetime;
2218                                 }
2219                         }
2220                 }
2221                 else{
2222                         dist=VecLenf(pa->state.co, re->state.co);
2223                         if(dist <= re->size){
2224                                 if(pa->alive==PARS_UNBORN){
2225                                         pa->time=re->time;
2226                                         pa->dietime=pa->time+pa->lifetime;
2227                                         birth=1;
2228                                 }
2229                                 if(birth || part->flag&PART_REACT_MULTIPLE){
2230                                         float vec[3];
2231                                         VECSUB(vec,pa->state.co, re->state.co);
2232                                         if(birth==0)
2233                                                 VecMulf(vec,(float)pow(1.0f-dist/re->size,part->reactshape));
2234                                         VECADDFAC(pa->state.vel,pa->state.vel,vec,part->reactfac);
2235                                         VECADDFAC(pa->state.vel,pa->state.vel,re->state.vel,part->partfac);
2236                                 }
2237                                 if(birth)
2238                                         VecMulf(pa->state.vel,(float)pow(1.0f-dist/re->size,part->reactshape));
2239                         }
2240                 }
2241         }
2242 }
2243 void psys_get_reactor_target(Object *ob, ParticleSystem *psys, Object **target_ob, ParticleSystem **target_psys)
2244 {
2245         Object *tob;
2246
2247         tob=psys->target_ob;
2248         if(tob==0)
2249                 tob=ob;
2250         
2251         *target_psys=BLI_findlink(&tob->particlesystem,psys->target_psys-1);
2252         if(*target_psys)
2253                 *target_ob=tob;
2254         else
2255                 *target_ob=0;
2256 }
2257 /************************************************/
2258 /*                      Point Cache                                                     */
2259 /************************************************/
2260 void psys_make_temp_pointcache(Object *ob, ParticleSystem *psys)
2261 {
2262         PointCache *cache = psys->pointcache;
2263         PTCacheID pid;
2264
2265         if((cache->flag & PTCACHE_DISK_CACHE)==0 || cache->mem_cache.first)
2266                 return;
2267
2268         BKE_ptcache_id_from_particles(&pid, ob, psys);
2269
2270         BKE_ptcache_disk_to_mem(&pid);
2271 }
2272 void psys_clear_temp_pointcache(ParticleSystem *psys)
2273 {
2274         if((psys->pointcache->flag & PTCACHE_DISK_CACHE)==0)
2275                 return;
2276
2277         BKE_ptache_free_mem(psys->pointcache);
2278 }
2279 void psys_get_pointcache_start_end(Scene *scene, ParticleSystem *psys, int *sfra, int *efra)
2280 {
2281         ParticleSettings *part = psys->part;
2282
2283         *sfra = MAX2(1, (int)part->sta);
2284         *efra = MIN2((int)(part->end + part->lifetime + 1.0), scene->r.efra);
2285 }
2286
2287 /************************************************/
2288 /*                      Effectors                                                       */
2289 /************************************************/
2290 static void update_particle_tree(ParticleSystem *psys)
2291 {
2292         if(psys) {
2293                 ParticleData *pa = psys->particles;
2294                 int p, totpart = psys->totpart;
2295
2296                 if(!psys->tree || psys->tree_frame != psys->cfra) {
2297                         
2298                         BLI_kdtree_free(psys->tree);
2299
2300                         psys->tree = BLI_kdtree_new(totpart);
2301                         
2302                         for(p=0, pa=psys->particles; p<totpart; p++,pa++){
2303                                 if(pa->flag & (PARS_NO_DISP+PARS_UNEXIST) || pa->alive != PARS_ALIVE)
2304                                         continue;
2305
2306                                 BLI_kdtree_insert(psys->tree, p, pa->state.co, NULL);
2307                         }
2308                         BLI_kdtree_balance(psys->tree);
2309
2310                         psys->tree_frame = psys->cfra;
2311                 }
2312         }
2313 }
2314 static void do_texture_effector(Tex *tex, short mode, short is_2d, float nabla, short object, float *pa_co, float obmat[4][4], float force_val, float falloff, float *field)
2315 {
2316         TexResult result[4];
2317         float tex_co[3], strength, mag_vec[3];
2318         int hasrgb;
2319         if(tex==NULL) return;
2320
2321         result[0].nor = result[1].nor = result[2].nor = result[3].nor = 0;
2322
2323         strength= force_val*falloff;///(float)pow((double)distance,(double)power);
2324
2325         VECCOPY(tex_co,pa_co);
2326
2327         if(is_2d){
2328                 float fac=-Inpf(tex_co,obmat[2]);
2329                 VECADDFAC(tex_co,tex_co,obmat[2],fac);
2330         }
2331
2332         if(object){
2333                 VecSubf(tex_co,tex_co,obmat[3]);
2334                 Mat4Mul3Vecfl(obmat,tex_co);
2335         }
2336
2337         hasrgb = multitex_ext(tex, tex_co, NULL,NULL, 1, result);
2338
2339         if(hasrgb && mode==PFIELD_TEX_RGB){
2340                 mag_vec[0]= (0.5f-result->tr)*strength;
2341                 mag_vec[1]= (0.5f-result->tg)*strength;
2342                 mag_vec[2]= (0.5f-result->tb)*strength;
2343         }
2344         else{
2345                 strength/=nabla;
2346
2347                 tex_co[0]+= nabla;
2348                 multitex_ext(tex, tex_co, NULL,NULL, 1, result+1);
2349
2350                 tex_co[0]-= nabla;
2351                 tex_co[1]+= nabla;
2352                 multitex_ext(tex, tex_co, NULL,NULL, 1, result+2);
2353
2354                 tex_co[1]-= nabla;
2355                 tex_co[2]+= nabla;
2356                 multitex_ext(tex, tex_co, NULL,NULL, 1, result+3);
2357
2358                 if(mode==PFIELD_TEX_GRAD || !hasrgb){ /* if we dont have rgb fall back to grad */
2359                         mag_vec[0]= (result[0].tin-result[1].tin)*strength;
2360                         mag_vec[1]= (result[0].tin-result[2].tin)*strength;
2361                         mag_vec[2]= (result[0].tin-result[3].tin)*strength;
2362                 }
2363                 else{ /*PFIELD_TEX_CURL*/
2364                         float dbdy,dgdz,drdz,dbdx,dgdx,drdy;
2365
2366                         dbdy= result[2].tb-result[0].tb;
2367                         dgdz= result[3].tg-result[0].tg;
2368                         drdz= result[3].tr-result[0].tr;
2369                         dbdx= result[1].tb-result[0].tb;
2370                         dgdx= result[1].tg-result[0].tg;
2371                         drdy= result[2].tr-result[0].tr;
2372
2373                         mag_vec[0]=(dbdy-dgdz)*strength;
2374                         mag_vec[1]=(drdz-dbdx)*strength;
2375                         mag_vec[2]=(dgdx-drdy)*strength;
2376                 }
2377         }
2378
2379         if(is_2d){
2380                 float fac=-Inpf(mag_vec,obmat[2]);
2381                 VECADDFAC(mag_vec,mag_vec,obmat[2],fac);
2382         }
2383
2384         VecAddf(field,field,mag_vec);
2385 }
2386 static void add_to_effectors(ListBase *lb, Scene *scene, Object *ob, Object *obsrc, ParticleSystem *psys)
2387 {
2388         ParticleEffectorCache *ec;
2389         PartDeflect *pd= ob->pd;
2390         short type=0,i;
2391
2392         if(pd && ob != obsrc){
2393                 if(pd->forcefield == PFIELD_GUIDE) {
2394                         if(ob->type==OB_CURVE) {
2395                                 Curve *cu= ob->data;
2396                                 if(cu->flag & CU_PATH) {
2397                                         if(cu->path==NULL || cu->path->data==NULL)
2398                                                 makeDispListCurveTypes(scene, ob, 0);
2399                                         if(cu->path && cu->path->data) {
2400                                                 type |= PSYS_EC_EFFECTOR;
2401                                         }
2402                                 }
2403                         }
2404                 }
2405                 else if(pd->forcefield)
2406                 {
2407                         type |= PSYS_EC_EFFECTOR;
2408                 }
2409         }
2410         
2411         if(pd && pd->deflect)
2412                 type |= PSYS_EC_DEFLECT;
2413
2414         if(type){
2415                 ec= MEM_callocN(sizeof(ParticleEffectorCache), "effector cache");
2416                 ec->ob= ob;
2417                 ec->type=type;
2418                 ec->distances=0;
2419                 ec->locations=0;
2420                 ec->rng = rng_new(1);
2421                 rng_srandom(ec->rng, (unsigned int)(ceil(PIL_check_seconds_timer()))); // use better seed
2422                 
2423                 BLI_addtail(lb, ec);
2424         }
2425
2426         type=0;
2427
2428         /* add particles as different effectors */
2429         if(ob->particlesystem.first){
2430                 ParticleSystem *epsys=ob->particlesystem.first;
2431                 ParticleSettings *epart=0;
2432                 Object *tob;
2433
2434                 for(i=0; epsys; epsys=epsys->next,i++){
2435                         if(!psys_check_enabled(ob, epsys))
2436                                 continue;
2437                         type=0;
2438                         if(epsys!=psys || (psys->part->flag & PART_SELF_EFFECT)){
2439                                 epart=epsys->part;
2440
2441                                 if((epsys->part->pd && epsys->part->pd->forcefield)
2442                                         || (epsys->part->pd2 && epsys->part->pd2->forcefield))
2443                                 {
2444                                         type=PSYS_EC_PARTICLE;
2445                                 }
2446
2447                                 if(epart->type==PART_REACTOR) {
2448                                         tob=epsys->target_ob;
2449                                         if(tob==0)
2450                                                 tob=ob;
2451                                         if(BLI_findlink(&tob->particlesystem,epsys->target_psys-1)==psys)
2452                                                 type|=PSYS_EC_REACTOR;
2453                                 }
2454
2455                                 if(type){
2456                                         ec= MEM_callocN(sizeof(ParticleEffectorCache), "effector cache");
2457                                         ec->ob= ob;
2458                                         ec->type=type;
2459                                         ec->psys_nbr=i;
2460                                         ec->rng = rng_new(1);
2461                                         rng_srandom(ec->rng, (unsigned int)(ceil(PIL_check_seconds_timer())));
2462                                         
2463                                         BLI_addtail(lb, ec);
2464                                 }
2465                         }
2466                 }
2467                                 
2468         }
2469 }
2470
2471 static void psys_init_effectors_recurs(Scene *scene, Object *ob, Object *obsrc, ParticleSystem *psys, ListBase *listb, int level)
2472 {
2473         Group *group;
2474         GroupObject *go;
2475         unsigned int layer= obsrc->lay;
2476
2477         if(level>MAX_DUPLI_RECUR) return;
2478
2479         if(ob->lay & layer) {
2480                 if(ob->pd || ob->particlesystem.first)
2481                         add_to_effectors(listb, scene, ob, obsrc, psys);
2482
2483                 if(ob->dup_group) {
2484                         group= ob->dup_group;
2485                         for(go= group->gobject.first; go; go= go->next)
2486                                 psys_init_effectors_recurs(scene, go->ob, obsrc, psys, listb, level+1);
2487                 }
2488         }
2489 }
2490
2491 void psys_init_effectors(Scene *scene, Object *obsrc, Group *group, ParticleSystem *psys)
2492 {
2493         ListBase *listb= &psys->effectors;
2494         Base *base;
2495
2496         listb->first=listb->last=0;
2497         
2498         if(group) {
2499                 GroupObject *go;
2500                 
2501                 for(go= group->gobject.first; go; go= go->next)
2502                         psys_init_effectors_recurs(scene, go->ob, obsrc, psys, listb, 0);
2503         }
2504         else {
2505                 for(base = scene->base.first; base; base= base->next)
2506                         psys_init_effectors_recurs(scene, base->object, obsrc, psys, listb, 0);
2507         }
2508 }
2509
2510 void psys_end_effectors(ParticleSystem *psys)
2511 {
2512         /* NOTE:
2513         ec->ob is not valid in here anymore! - dg
2514         */
2515         ParticleEffectorCache *ec = psys->effectors.first;
2516
2517         for(; ec; ec= ec->next){
2518                 if(ec->distances)
2519                         MEM_freeN(ec->distances);
2520
2521                 if(ec->locations)
2522                         MEM_freeN(ec->locations);
2523
2524                 if(ec->face_minmax)
2525                         MEM_freeN(ec->face_minmax);
2526
2527                 if(ec->vert_cos)
2528                         MEM_freeN(ec->vert_cos);
2529
2530                 if(ec->tree)
2531                         BLI_kdtree_free(ec->tree);
2532                 
2533                 if(ec->rng)
2534                         rng_free(ec->rng);
2535         }
2536
2537         BLI_freelistN(&psys->effectors);
2538 }
2539
2540 static void precalc_effectors(Scene *scene, Object *ob, ParticleSystem *psys, ParticleSystemModifierData *psmd, float cfra)
2541 {
2542         ListBase *lb=&psys->effectors;
2543         ParticleEffectorCache *ec;
2544         ParticleSettings *part=psys->part;
2545         ParticleData *pa;
2546         float vec2[3],loc[3],*co=0;
2547         int p,totpart;
2548         
2549         for(ec= lb->first; ec; ec= ec->next) {
2550                 PartDeflect *pd= ec->ob->pd;
2551                 co = NULL;
2552                 
2553                 if(ec->type==PSYS_EC_EFFECTOR && pd->forcefield==PFIELD_GUIDE && ec->ob->type==OB_CURVE 
2554                         && part->phystype!=PART_PHYS_BOIDS) {
2555                         float vec[4];
2556
2557                         where_on_path(ec->ob, 0.0, vec, vec2);
2558
2559                         Mat4MulVecfl(ec->ob->obmat,vec);
2560                         Mat4Mul3Vecfl(ec->ob->obmat,vec2);
2561
2562                         QUATCOPY(ec->firstloc,vec);
2563                         VECCOPY(ec->firstdir,vec2);
2564
2565                         totpart=psys->totpart;
2566
2567                         if(totpart){
2568                                 ec->distances=MEM_callocN(totpart*sizeof(float),"particle distances");
2569                                 ec->locations=MEM_callocN(totpart*3*sizeof(float),"particle locations");
2570
2571                                 for(p=0,pa=psys->particles; p<totpart; p++, pa++){
2572                                         if(part->from == PART_FROM_PARTICLE) {
2573                                                 VECCOPY(loc, pa->fuv);
2574                                         }
2575                                         else
2576                                                 psys_particle_on_emitter(psmd,part->from,pa->num,pa->num_dmcache,pa->fuv,pa->foffset,loc,0,0,0,0,0);
2577
2578                                         Mat4MulVecfl(ob->obmat,loc);
2579                                         ec->distances[p]=VecLenf(loc,vec);
2580                                         VECSUB(loc,loc,vec);
2581                                         VECCOPY(ec->locations+3*p,loc);
2582                                 }
2583                         }
2584                 }
2585                 else if(ec->type==PSYS_EC_PARTICLE){
2586                         Object *eob = ec->ob;
2587                         ParticleSystem *epsys = BLI_findlink(&eob->particlesystem,ec->psys_nbr);
2588                         ParticleSettings *epart = epsys->part;
2589                         ParticleData *epa;
2590                         int p, totepart = epsys->totpart;
2591
2592                         if(psys->part->phystype==PART_PHYS_BOIDS){
2593                                 ParticleKey state;
2594                                 PartDeflect *pd;
2595                                 
2596                                 pd= epart->pd;
2597                                 if(pd->forcefield==PFIELD_FORCE && totepart){
2598                                         KDTree *tree;
2599
2600                                         tree=BLI_kdtree_new(totepart);
2601                                         ec->tree=tree;
2602
2603                                         for(p=0, epa=epsys->particles; p<totepart; p++,epa++)
2604                                                 if(epa->alive==PARS_ALIVE && psys_get_particle_state(scene, eob,epsys,p,&state,0))
2605                                                         BLI_kdtree_insert(tree, p, state.co, NULL);
2606
2607                                         BLI_kdtree_balance(tree);
2608                                 }
2609                         }
2610
2611                 }
2612                 else if(ec->type==PSYS_EC_DEFLECT) {
2613                         CollisionModifierData *collmd = ( CollisionModifierData * ) ( modifiers_findByType ( ec->ob, eModifierType_Collision ) );
2614                         if(collmd)
2615                                 collision_move_object(collmd, 1.0, 0.0);
2616                 }
2617         }
2618 }
2619
2620 int effector_find_co(Scene *scene, float *pco, SurfaceModifierData *sur, Object *ob, PartDeflect *pd, float *co, float *nor, float *vel, int *index)
2621 {
2622         SurfaceModifierData *surmd = NULL;
2623         int ret = 0;
2624
2625         if(sur)
2626                 surmd = sur;
2627         else if(pd && pd->flag&PFIELD_SURFACE)
2628         {
2629                 surmd = (SurfaceModifierData *)modifiers_findByType ( ob, eModifierType_Surface );
2630         }
2631
2632         if(surmd) {
2633                 /* closest point in the object surface is an effector */
2634                 BVHTreeNearest nearest;
2635
2636                 nearest.index = -1;
2637                 nearest.dist = FLT_MAX;
2638
2639                 BLI_bvhtree_find_nearest(surmd->bvhtree->tree, pco, &nearest, surmd->bvhtree->nearest_callback, surmd->bvhtree);
2640
2641                 if(nearest.index != -1) {
2642                         VECCOPY(co, nearest.co);
2643
2644                         if(nor) {
2645                                 VECCOPY(nor, nearest.no);
2646                         }
2647
2648                         if(vel) {
2649                                 MFace *mface = CDDM_get_face(surmd->dm, nearest.index);
2650                                 
2651                                 VECCOPY(vel, surmd->v[mface->v1].co);
2652                                 VecAddf(vel, vel, surmd->v[mface->v2].co);
2653                                 VecAddf(vel, vel, surmd->v[mface->v3].co);
2654                                 if(mface->v4)
2655                                         VecAddf(vel, vel, surmd->v[mface->v4].co);
2656
2657                                 VecMulf(vel, mface->v4 ? 0.25f : 0.333f);
2658                         }
2659
2660                         if(index)
2661                                 *index = nearest.index;
2662
2663                         ret = 1;
2664                 }
2665                 else {
2666                         co[0] = co[1] = co[2] = 0.0f;
2667
2668                         if(nor)
2669                                 nor[0] = nor[1] = nor[2] = 0.0f;
2670
2671                         if(vel)
2672                                 vel[0] = vel[1] = vel[2] = 0.0f;
2673                 }
2674         }
2675         else {
2676                 /* use center of object for distance calculus */
2677                 VECCOPY(co, ob->obmat[3]);
2678
2679                 if(nor) {
2680                         VECCOPY(nor, ob->obmat[2]);
2681                 }
2682
2683                 if(vel) {
2684                         Object obcopy = *ob;
2685                         
2686                         VECCOPY(vel, ob->obmat[3]);
2687
2688                         where_is_object_time(scene, ob, scene->r.cfra - 1.0);
2689
2690                         VecSubf(vel, vel, ob->obmat[3]);
2691
2692                         *ob = obcopy;
2693                 }
2694         }
2695
2696         return ret;
2697 }
2698 /* calculate forces that all effectors apply to a particle*/
2699 void do_effectors(int pa_no, ParticleData *pa, ParticleKey *state, Scene *scene, Object *ob, ParticleSystem *psys, float *rootco, float *force_field, float *vel,float framestep, float cfra)
2700 {
2701         Object *eob;
2702         ParticleSystem *epsys;
2703         ParticleSettings *epart;
2704         ParticleData *epa;
2705         ParticleKey estate;
2706         PartDeflect *pd;
2707         ListBase *lb=&psys->effectors;
2708         ParticleEffectorCache *ec;
2709         float distance, vec_to_part[3], pco[3], co[3];
2710         float falloff, charge = 0.0f, strength;
2711         int p, face_index=-1;
2712
2713         /* check all effector objects for interaction */
2714         if(lb->first){
2715                 if(psys->part->pd && psys->part->pd->forcefield==PFIELD_CHARGE){
2716                         /* Only the charge of the effected particle is used for 
2717                            interaction, not fall-offs. If the fall-offs aren't the      
2718                            same this will be unphysical, but for animation this         
2719                            could be the wanted behavior. If you want physical
2720                            correctness the fall-off should be spherical 2.0 anyways.
2721                          */
2722                         charge = psys->part->pd->f_strength;
2723                 }
2724                 if(psys->part->pd2 && psys->part->pd2->forcefield==PFIELD_CHARGE){
2725                         charge += psys->part->pd2->f_strength;
2726                 }
2727                 for(ec = lb->first; ec; ec= ec->next){
2728                         eob= ec->ob;
2729                         if(ec->type & PSYS_EC_EFFECTOR){
2730                                 pd=eob->pd;
2731                                 if(psys->part->type!=PART_HAIR && psys->part->integrator)
2732                                         where_is_object_time(scene, eob,cfra);
2733
2734                                 if(pd && pd->flag&PFIELD_SURFACE) {
2735                                         float velocity[3];
2736                                         /* using velocity corrected location allows for easier sliding over effector surface */
2737                                         VecCopyf(velocity, state->vel);
2738                                         VecMulf(velocity, psys_get_timestep(psys->part));
2739                                         VecAddf(pco, state->co, velocity);
2740                                 }
2741                                 else 
2742                                         VECCOPY(pco, state->co);
2743
2744                                 effector_find_co(scene, pco, NULL, eob, pd, co, NULL, NULL, &face_index);
2745                                 
2746                                 VecSubf(vec_to_part, state->co, co);
2747
2748                                 distance = VecLength(vec_to_part);
2749
2750                                 falloff=effector_falloff(pd,eob->obmat[2],vec_to_part);
2751
2752                                 strength = pd->f_strength * psys->part->effector_weight[0] * psys->part->effector_weight[pd->forcefield];
2753
2754                                 if(falloff<=0.0f)
2755                                         ;       /* don't do anything */
2756                                 else if(pd->forcefield==PFIELD_TEXTURE) {
2757                                         do_texture_effector(pd->tex, pd->tex_mode, pd->flag&PFIELD_TEX_2D, pd->tex_nabla,
2758                                                                         pd->flag & PFIELD_TEX_OBJECT, (pd->flag & PFIELD_TEX_ROOTCO) ? rootco : state->co, eob->obmat,
2759                                                                         strength, falloff, force_field);
2760                                 } else {
2761                                         do_physical_effector(scene, eob, state->co, pd->forcefield,strength,distance,
2762                                                                                 falloff,0.0,pd->f_damp,eob->obmat[2],vec_to_part,
2763                                                                                 state->vel,force_field,pd->flag&PFIELD_PLANAR,ec->rng,pd->f_noise,charge,pa->size);
2764                                 }
2765                         }
2766                         if(ec->type & PSYS_EC_PARTICLE){
2767                                 int totepart, i;
2768                                 epsys= BLI_findlink(&eob->particlesystem,ec->psys_nbr);
2769                                 epart= epsys->part;
2770                                 pd=epart->pd;
2771                                 totepart= epsys->totpart;
2772                                 
2773                                 if(totepart <= 0)
2774                                         continue;
2775                                 
2776                                 if(pd && pd->forcefield==PFIELD_HARMONIC){
2777                                         /* every particle is mapped to only one harmonic effector particle */
2778                                         p= pa_no%epsys->totpart;
2779                                         totepart= p+1;
2780                                 }
2781                                 else{
2782                                         p=0;
2783                                 }
2784
2785                                 epsys->lattice= psys_get_lattice(scene, ob, psys);
2786
2787                                 for(; p<totepart; p++){
2788                                         /* particle skips itself as effector */
2789                                         if(epsys==psys && p == pa_no) continue;
2790
2791                                         epa = epsys->particles + p;
2792                                         estate.time=cfra;
2793                                         if(psys_get_particle_state(scene, eob,epsys,p,&estate,0)){
2794                                                 VECSUB(vec_to_part, state->co, estate.co);
2795                                                 distance = VecLength(vec_to_part);
2796                                                 
2797                                                 for(i=0, pd = epart->pd; i<2; i++,pd = epart->pd2) {
2798                                                         if(pd==NULL || pd->forcefield==0) continue;
2799
2800                                                         falloff=effector_falloff(pd,estate.vel,vec_to_part);
2801
2802                                                         strength = pd->f_strength * psys->part->effector_weight[0] * psys->part->effector_weight[pd->forcefield];
2803
2804                                                         if(falloff<=0.0f)
2805                                                                 ;       /* don't do anything */
2806                                                         else
2807                                                                 do_physical_effector(scene, eob, state->co, pd->forcefield,strength,distance,
2808                                                                 falloff,epart->size,pd->f_damp,estate.vel,vec_to_part,
2809                                                                 state->vel,force_field,0, ec->rng, pd->f_noise,charge,pa->size);
2810                                                 }
2811                                         }
2812                                         else if(pd && pd->forcefield==PFIELD_HARMONIC && cfra-framestep <= epa->dietime && cfra>epa->dietime){
2813                                                 /* first step after key release */
2814                                                 psys_get_particle_state(scene, eob,epsys,p,&estate,1);
2815                                                 VECADD(vel,vel,estate.vel);
2816                                                 /* TODO: add rotation handling here too */
2817                                         }
2818                                 }
2819
2820                                 if(epsys->lattice){
2821                                         end_latt_deform(epsys->lattice);
2822                                         epsys->lattice= NULL;
2823                                 }
2824                         }
2825                 }
2826         }
2827 }
2828
2829 /************************************************/
2830 /*                      Newtonian physics                                       */
2831 /************************************************/
2832 /* gathers all forces that effect particles and calculates a new state for the particle */
2833 static void apply_particle_forces(Scene *scene, int pa_no, ParticleData *pa, Object *ob, ParticleSystem *psys, ParticleSettings *part, float timestep, float dfra, float cfra)
2834 {
2835         ParticleKey states[5], tkey;
2836         float force[3],tvel[3],dx[4][3],dv[4][3];
2837         float dtime=dfra*timestep, time, pa_mass=part->mass, fac, fra=psys->cfra;
2838         int i, steps=1;
2839         
2840         /* maintain angular velocity */
2841         VECCOPY(pa->state.ave,pa->prev_state.ave);
2842
2843         if(part->flag & PART_SIZEMASS)
2844                 pa_mass*=pa->size;
2845
2846         switch(part->integrator){
2847                 case PART_INT_EULER:
2848                         steps=1;
2849                         break;
2850                 case PART_INT_MIDPOINT:
2851                         steps=2;
2852                         break;
2853                 case PART_INT_RK4:
2854                         steps=4;
2855                         break;
2856         }
2857
2858         copy_particle_key(states,&pa->state,1);
2859
2860         for(i=0; i<steps; i++){
2861                 force[0]=force[1]=force[2]=0.0;
2862                 tvel[0]=tvel[1]=tvel[2]=0.0;
2863                 /* add effectors */
2864                 if(part->type != PART_HAIR)
2865                         do_effectors(pa_no,pa,states+i,scene, ob, psys,states->co,force,tvel,dfra,fra);
2866
2867                 /* calculate air-particle interaction */
2868                 if(part->dragfac!=0.0f){
2869                         fac=-part->dragfac*pa->size*pa->size*VecLength(states[i].vel);
2870                         VECADDFAC(force,force,states[i].vel,fac);
2871                 }
2872
2873                 /* brownian force */
2874                 if(part->brownfac!=0.0){
2875                         force[0]+=(BLI_frand()-0.5f)*part->brownfac;
2876                         force[1]+=(BLI_frand()-0.5f)*part->brownfac;
2877                         force[2]+=(BLI_frand()-0.5f)*part->brownfac;
2878                 }
2879
2880                 /* force to acceleration*/
2881                 VecMulf(force,1.0f/pa_mass);
2882
2883                 /* add global acceleration (gravitation) */
2884                 VECADD(force,force,part->acc);
2885                 
2886                 /* calculate next state */
2887                 VECADD(states[i].vel,states[i].vel,tvel);
2888
2889                 switch(part->integrator){
2890                         case PART_INT_EULER:
2891                                 VECADDFAC(pa->state.co,states->co,states->vel,dtime);
2892                                 VECADDFAC(pa->state.vel,states->vel,force,dtime);
2893                                 break;
2894                         case PART_INT_MIDPOINT:
2895                                 if(i==0){
2896                          &n