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