svn merge -r 16593:16648 https://svn.blender.org/svnroot/bf-blender/trunk/blender
[blender-staging.git] / source / blender / blenkernel / intern / particle_system.c
1 /* particle_system.c
2  *
3  *
4  * $Id: particle_system.c $
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 <stdlib.h>
33 #include <math.h>
34 #include <string.h>
35
36 #include "MEM_guardedalloc.h"
37
38 #include "DNA_particle_types.h"
39 #include "DNA_mesh_types.h"
40 #include "DNA_meshdata_types.h"
41 #include "DNA_modifier_types.h"
42 #include "DNA_object_force.h"
43 #include "DNA_object_types.h"
44 #include "DNA_material_types.h"
45 #include "DNA_ipo_types.h"
46 #include "DNA_curve_types.h"
47 #include "DNA_group_types.h"
48 #include "DNA_scene_types.h"
49 #include "DNA_texture_types.h"
50
51 #include "BLI_rand.h"
52 #include "BLI_jitter.h"
53 #include "BLI_arithb.h"
54 #include "BLI_blenlib.h"
55 #include "BLI_kdtree.h"
56 #include "BLI_kdopbvh.h"
57 #include "BLI_linklist.h"
58 #include "BLI_threads.h"
59
60 #include "BKE_anim.h"
61 #include "BKE_bad_level_calls.h"
62 #include "BKE_cdderivedmesh.h"
63 #include "BKE_collision.h"
64 #include "BKE_displist.h"
65 #include "BKE_effect.h"
66 #include "BKE_particle.h"
67 #include "BKE_global.h"
68 #include "BKE_utildefines.h"
69 #include "BKE_DerivedMesh.h"
70 #include "BKE_object.h"
71 #include "BKE_material.h"
72 #include "BKE_ipo.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
81 #include "PIL_time.h"
82
83 #include "BSE_headerbuttons.h"
84
85 #include "blendef.h"
86
87 #include "RE_shader_ext.h"
88
89 /* fluid sim particle import */
90 #ifndef DISABLE_ELBEEM
91 #include "DNA_object_fluidsim.h"
92 #include "LBM_fluidsim.h"
93 #include "elbeem.h"
94 #include <zlib.h>
95 #include <string.h>
96
97 #ifdef WIN32
98 #ifndef snprintf
99 #define snprintf _snprintf
100 #endif
101 #endif
102
103 #endif // DISABLE_ELBEEM
104
105 /************************************************/
106 /*                      Reacting to system events                       */
107 /************************************************/
108
109 static int get_current_display_percentage(ParticleSystem *psys)
110 {
111         ParticleSettings *part=psys->part;
112
113         if(psys->renderdata || (part->child_nbr && part->childtype)) 
114                 return 100;
115
116         if(part->phystype==PART_PHYS_KEYED){
117                 if(psys->flag & PSYS_FIRST_KEYED)
118                         return psys->part->disp;
119                 else
120                         return 100;
121         }
122         else
123                 return psys->part->disp;
124 }
125
126 void psys_reset(ParticleSystem *psys, int mode)
127 {
128         ParticleSettings *part= psys->part;
129         ParticleData *pa;
130         int i;
131
132         if(ELEM(mode, PSYS_RESET_ALL, PSYS_RESET_DEPSGRAPH)) {
133                 if(mode == PSYS_RESET_ALL || !(part->type == PART_HAIR && (psys->flag & PSYS_EDITED))) {
134                         if(psys->particles) {
135                                 if(psys->particles->keys)
136                                         MEM_freeN(psys->particles->keys);
137
138                                 for(i=0, pa=psys->particles; i<psys->totpart; i++, pa++)
139                                         if(pa->hair) MEM_freeN(pa->hair);
140
141                                 MEM_freeN(psys->particles);
142                                 psys->particles= NULL;
143                         }
144
145                         psys->totpart= 0;
146                         psys->totkeyed= 0;
147                         psys->flag &= ~(PSYS_HAIR_DONE|PSYS_KEYED);
148
149                         if(psys->reactevents.first)
150                                 BLI_freelistN(&psys->reactevents);
151                 }
152         }
153         else if(mode == PSYS_RESET_CACHE_MISS) {
154                 /* set all particles to be skipped */
155                 ParticleData *pa = psys->particles;
156                 int p=0;
157
158                 for(; p<psys->totpart; p++, pa++)
159                         pa->flag |= PARS_NO_DISP;
160         }
161
162         /* reset children */
163         if(psys->child) {
164                 MEM_freeN(psys->child);
165                 psys->child= 0;
166         }
167
168         psys->totchild= 0;
169
170         /* reset path cache */
171         psys_free_path_cache(psys);
172
173         /* reset point cache */
174         psys->pointcache->flag &= ~PTCACHE_SIMULATION_VALID;
175         psys->pointcache->simframe= 0;
176 }
177
178 static void realloc_particles(Object *ob, ParticleSystem *psys, int new_totpart)
179 {
180         ParticleData *newpars = 0, *pa;
181         int i, totpart, totsaved = 0;
182
183         if(new_totpart<0) {
184                 if(psys->part->distr==PART_DISTR_GRID  && psys->part->from != PART_FROM_VERT) {
185                         totpart= psys->part->grid_res;
186                         totpart*=totpart*totpart;
187                 }
188                 else
189                         totpart=psys->part->totpart;
190         }
191         else
192                 totpart=new_totpart;
193
194         if(totpart)
195                 newpars= MEM_callocN(totpart*sizeof(ParticleData), "particles");
196         if(psys->particles) {
197                 totsaved=MIN2(psys->totpart,totpart);
198                 /*save old pars*/
199                 if(totsaved)
200                         memcpy(newpars,psys->particles,totsaved*sizeof(ParticleData));
201
202                 if(psys->particles->keys)
203                         MEM_freeN(psys->particles->keys);
204
205                 for(i=0, pa=psys->particles; i<totsaved; i++, pa++)
206                         if(pa->keys) pa->keys= NULL;
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(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(&G.scene->r, nbr);
234         }
235         else
236                 return psys->part->child_nbr;
237 }
238
239 static int get_psys_tot_child(ParticleSystem *psys)
240 {
241         return psys->totpart*get_psys_child_number(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->ob,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(ob,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                                                 VecMulf(tan,-1.0f);
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 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, 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                 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(ob,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(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(psys);
1040
1041                         totpart= get_psys_tot_child(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         if(part->type == PART_HAIR) {
1305                 COMPARE_ORIG_INDEX= dm->getFaceDataArray(dm, CD_ORIGINDEX);
1306                 if(COMPARE_ORIG_INDEX)
1307                         qsort(index, totpart, sizeof(int), compare_orig_index);
1308         }
1309
1310         /* weights are no longer used except for FROM_PARTICLE, which needs them zeroed for indexing */
1311         if(from==PART_FROM_PARTICLE){
1312                 for(i=0; i<tot; i++)
1313                         weight[i]=0.0f;
1314         }
1315
1316         /* 4. */
1317         if(distr==PART_DISTR_JIT && ELEM(from,PART_FROM_FACE,PART_FROM_VOLUME)) {
1318                 jitlevel= part->userjit;
1319                 
1320                 if(jitlevel == 0) {
1321                         jitlevel= totpart/tot;
1322                         if(part->flag & PART_EDISTR) jitlevel*= 2;      /* looks better in general, not very scietific */
1323                         if(jitlevel<3) jitlevel= 3;
1324                         //if(jitlevel>100) jitlevel= 100;
1325                 }
1326                 
1327                 jit= MEM_callocN((2+ jitlevel*2)*sizeof(float), "jit");
1328
1329                 /* for small amounts of particles we use regular jitter since it looks
1330                  * a bit better, for larger amounts we switch to hammersley sequence 
1331                  * because it is much faster */
1332                 if(jitlevel < 25)
1333                         init_mv_jit(jit, jitlevel, psys->seed, part->jitfac);
1334                 else
1335                         hammersley_create(jit, jitlevel+1, psys->seed, part->jitfac);
1336                 BLI_array_randomize(jit, 2*sizeof(float), jitlevel, psys->seed); /* for custom jit or even distribution */
1337         }
1338
1339         /* 5. */
1340         ctx->tree= tree;
1341         ctx->seams= seams;
1342         ctx->totseam= totseam;
1343         ctx->psys= psys;
1344         ctx->index= index;
1345         ctx->jit= jit;
1346         ctx->jitlevel= jitlevel;
1347         ctx->jitoff= jitoff;
1348         ctx->weight= weight;
1349         ctx->maxweight= maxweight;
1350         ctx->from= (children)? PART_FROM_CHILD: from;
1351         ctx->cfrom= cfrom;
1352         ctx->distr= distr;
1353         ctx->dm= dm;
1354         ctx->tpars= tpars;
1355
1356         if(children) {
1357                 totpart= psys_render_simplify_distribution(ctx, totpart);
1358                 alloc_child_particles(psys, totpart);
1359         }
1360
1361         if(!children || psys->totchild < 10000)
1362                 totthread= 1;
1363         
1364         seed= 31415926 + ctx->psys->seed;
1365         for(i=0; i<totthread; i++) {
1366                 threads[i].rng= rng_new(seed);
1367                 threads[i].tot= totthread;
1368         }
1369
1370         return 1;
1371 }
1372
1373 static void distribute_particles_on_dm(DerivedMesh *finaldm, Object *ob, ParticleSystem *psys, int from)
1374 {
1375         ListBase threads;
1376         ParticleThread *pthreads;
1377         ParticleThreadContext *ctx;
1378         int i, totthread;
1379
1380         pthreads= psys_threads_create(ob, psys);
1381
1382         if(!psys_threads_init_distribution(pthreads, finaldm, from)) {
1383                 psys_threads_free(pthreads);
1384                 return;
1385         }
1386
1387         totthread= pthreads[0].tot;
1388         if(totthread > 1) {
1389                 BLI_init_threads(&threads, exec_distribution, totthread);
1390
1391                 for(i=0; i<totthread; i++)
1392                         BLI_insert_thread(&threads, &pthreads[i]);
1393
1394                 BLI_end_threads(&threads);
1395         }
1396         else
1397                 exec_distribution(&pthreads[0]);
1398
1399         psys_calc_dmcache(ob, finaldm, psys);
1400
1401         ctx= pthreads[0].ctx;
1402         if(ctx->dm != finaldm)
1403                 ctx->dm->release(ctx->dm);
1404
1405         psys_threads_free(pthreads);
1406 }
1407
1408 /* ready for future use, to emit particles without geometry */
1409 static void distribute_particles_on_shape(Object *ob, ParticleSystem *psys, int from)
1410 {
1411         ParticleData *pa;
1412         int totpart=psys->totpart, p;
1413
1414         fprintf(stderr,"Shape emission not yet possible!\n");
1415
1416         for(p=0,pa=psys->particles; p<totpart; p++,pa++){
1417                 pa->fuv[0]=pa->fuv[1]=pa->fuv[2]=pa->fuv[3]= 0.0;
1418                 pa->foffset= 0.0f;
1419                 pa->num= -1;
1420         }
1421 }
1422 static void distribute_particles(Object *ob, ParticleSystem *psys, int from)
1423 {
1424         ParticleSystemModifierData *psmd=0;
1425         int distr_error=0;
1426         psmd=psys_get_modifier(ob,psys);
1427
1428         if(psmd){
1429                 if(psmd->dm)
1430                         distribute_particles_on_dm(psmd->dm,ob,psys,from);
1431                 else
1432                         distr_error=1;
1433         }
1434         else
1435                 distribute_particles_on_shape(ob,psys,from);
1436
1437         if(distr_error){
1438                 ParticleData *pa;
1439                 int totpart=psys->totpart, p;
1440
1441                 fprintf(stderr,"Particle distribution error!\n");
1442
1443                 for(p=0,pa=psys->particles; p<totpart; p++,pa++){
1444                         pa->fuv[0]=pa->fuv[1]=pa->fuv[2]=pa->fuv[3]= 0.0;
1445                         pa->foffset= 0.0f;
1446                         pa->num= -1;
1447                 }
1448         }
1449 }
1450
1451 /* threaded child particle distribution and path caching */
1452 ParticleThread *psys_threads_create(struct Object *ob, struct ParticleSystem *psys)
1453 {
1454         ParticleThread *threads;
1455         ParticleThreadContext *ctx;
1456         int i, totthread;
1457
1458         if(G.scene->r.mode & R_FIXED_THREADS)
1459                 totthread= G.scene->r.threads;
1460         else
1461                 totthread= BLI_system_thread_count();
1462         
1463         threads= MEM_callocN(sizeof(ParticleThread)*totthread, "ParticleThread");
1464         ctx= MEM_callocN(sizeof(ParticleThreadContext), "ParticleThreadContext");
1465
1466         ctx->ob= ob;
1467         ctx->psys= psys;
1468         ctx->psmd= psys_get_modifier(ob, psys);
1469         ctx->dm= ctx->psmd->dm;
1470         ctx->ma= give_current_material(ob, psys->part->omat);
1471
1472         memset(threads, 0, sizeof(ParticleThread)*totthread);
1473
1474         for(i=0; i<totthread; i++) {
1475                 threads[i].ctx= ctx;
1476                 threads[i].num= i;
1477                 threads[i].tot= totthread;
1478         }
1479
1480         return threads;
1481 }
1482
1483 void psys_threads_free(ParticleThread *threads)
1484 {
1485         ParticleThreadContext *ctx= threads[0].ctx;
1486         int i, totthread= threads[0].tot;
1487
1488         /* path caching */
1489         if(ctx->vg_length)
1490                 MEM_freeN(ctx->vg_length);
1491         if(ctx->vg_clump)
1492                 MEM_freeN(ctx->vg_clump);
1493         if(ctx->vg_kink)
1494                 MEM_freeN(ctx->vg_kink);
1495         if(ctx->vg_rough1)
1496                 MEM_freeN(ctx->vg_rough1);
1497         if(ctx->vg_rough2)
1498                 MEM_freeN(ctx->vg_rough2);
1499         if(ctx->vg_roughe)
1500                 MEM_freeN(ctx->vg_roughe);
1501
1502         if(ctx->psys->lattice){
1503                 end_latt_deform();
1504                 ctx->psys->lattice=0;
1505         }
1506
1507         /* distribution */
1508         if(ctx->jit) MEM_freeN(ctx->jit);
1509         if(ctx->jitoff) MEM_freeN(ctx->jitoff);
1510         if(ctx->weight) MEM_freeN(ctx->weight);
1511         if(ctx->index) MEM_freeN(ctx->index);
1512         if(ctx->skip) MEM_freeN(ctx->skip);
1513         if(ctx->seams) MEM_freeN(ctx->seams);
1514         //if(ctx->vertpart) MEM_freeN(ctx->vertpart);
1515         BLI_kdtree_free(ctx->tree);
1516
1517         /* threads */
1518         for(i=0; i<totthread; i++) {
1519                 if(threads[i].rng)
1520                         rng_free(threads[i].rng);
1521                 if(threads[i].rng_path)
1522                         rng_free(threads[i].rng_path);
1523         }
1524
1525         MEM_freeN(ctx);
1526         MEM_freeN(threads);
1527 }
1528
1529 /* set particle parameters that don't change during particle's life */
1530 void initialize_particle(ParticleData *pa, int p, Object *ob, ParticleSystem *psys, ParticleSystemModifierData *psmd)
1531 {
1532         ParticleSettings *part;
1533         ParticleTexture ptex;
1534         Material *ma=0;
1535         IpoCurve *icu=0;
1536         int totpart;
1537         float rand,length;
1538
1539         part=psys->part;
1540
1541         totpart=psys->totpart;
1542
1543         ptex.life=ptex.size=ptex.exist=ptex.length=1.0;
1544         ptex.time=(float)p/(float)totpart;
1545
1546         BLI_srandom(psys->seed+p);
1547
1548         if(part->from!=PART_FROM_PARTICLE && part->type!=PART_FLUID){
1549                 ma=give_current_material(ob,part->omat);
1550
1551                 /* TODO: needs some work to make most blendtypes generally usefull */
1552                 psys_get_texture(ob,ma,psmd,psys,pa,&ptex,MAP_PA_INIT);
1553         }
1554         
1555         pa->lifetime= part->lifetime*ptex.life;
1556
1557         if(part->type==PART_HAIR)
1558                 pa->time=0.0f;
1559         else if(part->type==PART_REACTOR && (part->flag&PART_REACT_STA_END)==0)
1560                 pa->time=MAXFRAMEF;
1561         else{
1562                 //icu=find_ipocurve(psys->part->ipo,PART_EMIT_TIME);
1563                 //if(icu){
1564                 //      calc_icu(icu,100*ptex.time);
1565                 //      ptex.time=icu->curval;
1566                 //}
1567
1568                 pa->time= part->sta + (part->end - part->sta)*ptex.time;
1569         }
1570
1571
1572         if(part->type==PART_HAIR){
1573                 pa->lifetime=100.0f;
1574         }
1575         else{
1576                 icu=find_ipocurve(psys->part->ipo,PART_EMIT_LIFE);
1577                 if(icu){
1578                         calc_icu(icu,100*ptex.time);
1579                         pa->lifetime*=icu->curval;
1580                 }
1581
1582         /* need to get every rand even if we don't use them so that randoms don't affect eachother */
1583                 rand= BLI_frand();
1584                 if(part->randlife!=0.0)
1585                         pa->lifetime*= 1.0f - part->randlife*rand;
1586         }
1587
1588         pa->dietime= pa->time+pa->lifetime;
1589
1590         pa->sizemul= BLI_frand();
1591
1592         rand= BLI_frand();
1593
1594         /* while loops are to have a spherical distribution (avoid cubic distribution) */
1595         length=2.0f;
1596         while(length>1.0){
1597                 pa->r_ve[0]=2.0f*(BLI_frand()-0.5f);
1598                 pa->r_ve[1]=2.0f*(BLI_frand()-0.5f);
1599                 pa->r_ve[2]=2.0f*(BLI_frand()-0.5f);
1600                 length=VecLength(pa->r_ve);
1601         }
1602
1603         length=2.0f;
1604         while(length>1.0){
1605                 pa->r_ave[0]=2.0f*(BLI_frand()-0.5f);
1606                 pa->r_ave[1]=2.0f*(BLI_frand()-0.5f);
1607                 pa->r_ave[2]=2.0f*(BLI_frand()-0.5f);
1608                 length=VecLength(pa->r_ave);
1609         }
1610
1611         pa->r_rot[0]=2.0f*(BLI_frand()-0.5f);
1612         pa->r_rot[1]=2.0f*(BLI_frand()-0.5f);
1613         pa->r_rot[2]=2.0f*(BLI_frand()-0.5f);
1614         pa->r_rot[3]=2.0f*(BLI_frand()-0.5f);
1615
1616         NormalQuat(pa->r_rot);
1617
1618         if(part->distr!=PART_DISTR_GRID && part->from != PART_FROM_VERT){
1619                 /* any unique random number will do (r_ave[0]) */
1620                 if(ptex.exist < 0.5*(1.0+pa->r_ave[0]))
1621                         pa->flag |= PARS_UNEXIST;
1622                 else
1623                         pa->flag &= ~PARS_UNEXIST;
1624         }
1625
1626         pa->loop=0;
1627         /* we can't reset to -1 anymore since we've figured out correct index in distribute_particles */
1628         /* usage other than straight after distribute has to handle this index by itself - jahka*/
1629         //pa->num_dmcache = DMCACHE_NOTFOUND; /* assume we dont have a derived mesh face */
1630 }
1631 static void initialize_all_particles(Object *ob, ParticleSystem *psys, ParticleSystemModifierData *psmd)
1632 {
1633         IpoCurve *icu=0;
1634         ParticleData *pa;
1635         int p, totpart=psys->totpart;
1636
1637         for(p=0, pa=psys->particles; p<totpart; p++, pa++)
1638                 initialize_particle(pa,p,ob,psys,psmd);
1639         
1640         if(psys->part->type != PART_FLUID) {
1641                 icu=find_ipocurve(psys->part->ipo,PART_EMIT_FREQ);
1642                 if(icu){
1643                         float time=psys->part->sta, end=psys->part->end;
1644                         float v1, v2, a=0.0f, t1,t2, d;
1645
1646                         p=0;
1647                         pa=psys->particles;
1648
1649                         calc_icu(icu,time);
1650                         v1=icu->curval;
1651                         if(v1<0.0f) v1=0.0f;
1652
1653                         calc_icu(icu,time+1.0f);
1654                         v2=icu->curval;
1655                         if(v2<0.0f) v2=0.0f;
1656
1657                         for(p=0, pa=psys->particles; p<totpart && time<end; p++, pa++){
1658                                 while(a+0.5f*(v1+v2) < (float)(p+1) && time<end){
1659                                         a+=0.5f*(v1+v2);
1660                                         v1=v2;
1661                                         time++;
1662                                         calc_icu(icu,time+1.0f);
1663                                         v2=icu->curval;
1664                                 }
1665                                 if(time<end){
1666                                         if(v1==v2){
1667                                                 pa->time=time+((float)(p+1)-a)/v1;
1668                                         }
1669                                         else{
1670                                                 d=(float)sqrt(v1*v1-2.0f*(v2-v1)*(a-(float)(p+1)));
1671                                                 t1=(-v1+d)/(v2-v1);
1672                                                 t2=(-v1-d)/(v2-v1);
1673
1674                                                 /* the root between 0-1 is the correct one */
1675                                                 if(t1>0.0f && t1<=1.0f)
1676                                                         pa->time=time+t1;
1677                                                 else
1678                                                         pa->time=time+t2;
1679                                         }
1680                                 }
1681
1682                                 pa->dietime = pa->time+pa->lifetime;
1683                                 pa->flag &= ~PARS_UNEXIST;
1684                         }
1685                         for(; p<totpart; p++, pa++){
1686                                 pa->flag |= PARS_UNEXIST;
1687                         }
1688                 }
1689         }
1690 }
1691 /* sets particle to the emitter surface with initial velocity & rotation */
1692 void reset_particle(ParticleData *pa, ParticleSystem *psys, ParticleSystemModifierData *psmd, Object *ob,
1693                                         float dtime, float cfra, float *vg_vel, float *vg_tan, float *vg_rot)
1694 {
1695         ParticleSettings *part;
1696         ParticleTexture ptex;
1697         ParticleKey state;
1698         IpoCurve *icu=0;
1699         float fac, phasefac, nor[3]={0,0,0},loc[3],tloc[3],vel[3]={0.0,0.0,0.0},rot[4],q2[4];
1700         float r_vel[3],r_ave[3],r_rot[4],p_vel[3]={0.0,0.0,0.0};
1701         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};
1702         float q_phase[4];
1703         part=psys->part;
1704
1705         ptex.ivel=1.0;
1706         
1707         if(part->from==PART_FROM_PARTICLE){
1708                 Object *tob;
1709                 ParticleSystem *tpsys=0;
1710                 float speed;
1711
1712                 tob=psys->target_ob;
1713                 if(tob==0)
1714                         tob=ob;
1715
1716                 tpsys=BLI_findlink(&tob->particlesystem,psys->target_psys-1);
1717                 
1718                 /*TODO: get precise location of particle at birth*/
1719
1720                 state.time=cfra;
1721                 if(pa->num == -1)
1722                         memset(&state, 0, sizeof(state));
1723                 else
1724                         psys_get_particle_state(tob,tpsys,pa->num,&state,1);
1725                 psys_get_from_key(&state,loc,nor,rot,0);
1726
1727                 QuatMulVecf(rot,vtan);
1728                 QuatMulVecf(rot,utan);
1729                 VECCOPY(r_vel,pa->r_ve);
1730                 VECCOPY(r_rot,pa->r_rot);
1731                 VECCOPY(r_ave,pa->r_ave);
1732
1733                 VECCOPY(p_vel,state.vel);
1734                 speed=Normalize(p_vel);
1735                 VecMulf(p_vel,Inpf(pa->r_ve,p_vel));
1736                 VECSUB(p_vel,pa->r_ve,p_vel);
1737                 Normalize(p_vel);
1738                 VecMulf(p_vel,speed);
1739         }
1740         else{
1741                 /* get precise emitter matrix if particle is born */
1742                 if(part->type!=PART_HAIR && pa->time < cfra && pa->time >= psys->cfra)
1743                         where_is_object_time(ob,pa->time);
1744
1745                 /* get birth location from object               */
1746                 psys_particle_on_emitter(ob,psmd,part->from,pa->num, pa->num_dmcache, pa->fuv,pa->foffset,loc,nor,utan,vtan,0,0);
1747                 
1748                 /* save local coordinates for later             */
1749                 VECCOPY(tloc,loc);
1750                 
1751                 /* get possible textural influence */
1752                 psys_get_texture(ob,give_current_material(ob,part->omat),psmd,psys,pa,&ptex,MAP_PA_IVEL);
1753
1754                 if(vg_vel && pa->num != -1)
1755                         ptex.ivel*=psys_interpolate_value_from_verts(psmd->dm,part->from,pa->num,pa->fuv,vg_vel);
1756
1757                 /* particles live in global space so    */
1758                 /* let's convert:                                               */
1759                 /* -location                                                    */
1760                 Mat4MulVecfl(ob->obmat,loc);
1761                 
1762                 /* -normal                                                              */
1763                 VECADD(nor,tloc,nor);
1764                 Mat4MulVecfl(ob->obmat,nor);
1765                 VECSUB(nor,nor,loc);
1766                 Normalize(nor);
1767
1768                 /* -tangent                                                             */
1769                 if(part->tanfac!=0.0){
1770                         float phase=vg_rot?2.0f*(psys_interpolate_value_from_verts(psmd->dm,part->from,pa->num,pa->fuv,vg_rot)-0.5f):0.0f;
1771                         VecMulf(vtan,-(float)cos(M_PI*(part->tanphase+phase)));
1772                         fac=-(float)sin(M_PI*(part->tanphase+phase));
1773                         VECADDFAC(vtan,vtan,utan,fac);
1774
1775                         VECADD(vtan,tloc,vtan);
1776                         Mat4MulVecfl(ob->obmat,vtan);
1777                         VECSUB(vtan,vtan,loc);
1778
1779                         VECCOPY(utan,nor);
1780                         VecMulf(utan,Inpf(vtan,nor));
1781                         VECSUB(vtan,vtan,utan);
1782                         
1783                         Normalize(vtan);
1784                 }
1785                 
1786
1787                 /* -velocity                                                    */
1788                 if(part->randfac!=0.0){
1789                         VECADD(r_vel,tloc,pa->r_ve);
1790                         Mat4MulVecfl(ob->obmat,r_vel);
1791                         VECSUB(r_vel,r_vel,loc);
1792                         Normalize(r_vel);
1793                 }
1794
1795                 /* -angular velocity                                    */
1796                 if(part->avemode==PART_AVE_RAND){
1797                         VECADD(r_ave,tloc,pa->r_ave);
1798                         Mat4MulVecfl(ob->obmat,r_ave);
1799                         VECSUB(r_ave,r_ave,loc);
1800                         Normalize(r_ave);
1801                 }
1802                 
1803                 /* -rotation                                                    */
1804                 if(part->randrotfac != 0.0f){
1805                         QUATCOPY(r_rot,pa->r_rot);
1806                         Mat4ToQuat(ob->obmat,rot);
1807                         QuatMul(r_rot,r_rot,rot);
1808                 }
1809         }
1810         /* conversion done so now we apply new: */
1811         /* -velocity from:                                              */
1812         /*              *emitter velocity                               */
1813         if(dtime!=0.0 && part->obfac!=0.0){
1814                 VECSUB(vel,loc,pa->state.co);
1815                 VecMulf(vel,part->obfac/dtime);
1816         }
1817         
1818         /*              *emitter normal                                 */
1819         if(part->normfac!=0.0)
1820                 VECADDFAC(vel,vel,nor,part->normfac);
1821         
1822         /*              *emitter tangent                                */
1823         if(part->tanfac!=0.0)
1824                 VECADDFAC(vel,vel,vtan,part->tanfac*(vg_tan?psys_interpolate_value_from_verts(psmd->dm,part->from,pa->num,pa->fuv,vg_tan):1.0f));
1825
1826         /*              *texture                                                */
1827         /* TODO */
1828
1829         /*              *random                                                 */
1830         if(part->randfac!=0.0)
1831                 VECADDFAC(vel,vel,r_vel,part->randfac);
1832
1833         /*              *particle                                               */
1834         if(part->partfac!=0.0)
1835                 VECADDFAC(vel,vel,p_vel,part->partfac);
1836
1837         icu=find_ipocurve(psys->part->ipo,PART_EMIT_VEL);
1838         if(icu){
1839                 calc_icu(icu,100*((pa->time-part->sta)/(part->end-part->sta)));
1840                 ptex.ivel*=icu->curval;
1841         }
1842
1843         VecMulf(vel,ptex.ivel);
1844         
1845         VECCOPY(pa->state.vel,vel);
1846
1847         /* -location from emitter                               */
1848         VECCOPY(pa->state.co,loc);
1849
1850         /* -rotation                                                    */
1851         pa->state.rot[0]=1.0;
1852         pa->state.rot[1]=pa->state.rot[2]=pa->state.rot[3]=0.0;
1853
1854         if(part->rotmode){
1855                 /* create vector into which rotation is aligned */
1856                 switch(part->rotmode){
1857                         case PART_ROT_NOR:
1858                                 VecCopyf(rot_vec, nor);
1859                                 break;
1860                         case PART_ROT_VEL:
1861                                 VecCopyf(rot_vec, vel);
1862                                 break;
1863                         case PART_ROT_GLOB_X:
1864                         case PART_ROT_GLOB_Y:
1865                         case PART_ROT_GLOB_Z:
1866                                 rot_vec[part->rotmode - PART_ROT_GLOB_X] = 1.0f;
1867                                 break;
1868                         case PART_ROT_OB_X:
1869                         case PART_ROT_OB_Y:
1870                         case PART_ROT_OB_Z:
1871                                 VecCopyf(rot_vec, ob->obmat[part->rotmode - PART_ROT_OB_X]);
1872                                 break;
1873                 }
1874                 
1875                 /* create rotation quat */
1876                 VecMulf(rot_vec,-1.0);
1877                 vectoquat(rot_vec, OB_POSX, OB_POSZ, q2);
1878
1879                 /* randomize rotation quat */
1880                 if(part->randrotfac!=0.0f)
1881                         QuatInterpol(rot, q2, r_rot, part->randrotfac);
1882                 else
1883                         QuatCopy(rot,q2);
1884
1885                 /* rotation phase */
1886                 phasefac = part->phasefac;
1887                 if(part->randphasefac != 0.0f) /* abuse r_ave[0] as a random number */
1888                         phasefac += part->randphasefac * pa->r_ave[0];
1889                 VecRotToQuat(x_vec, phasefac*(float)M_PI, q_phase);
1890
1891                 /* combine base rotation & phase */
1892                 QuatMul(pa->state.rot, rot, q_phase);
1893         }
1894
1895         /* -angular velocity                                    */
1896
1897         pa->state.ave[0] = pa->state.ave[1] = pa->state.ave[2] = 0.0;
1898
1899         if(part->avemode){
1900                 switch(part->avemode){
1901                         case PART_AVE_SPIN:
1902                                 VECCOPY(pa->state.ave,vel);
1903                                 break;
1904                         case PART_AVE_RAND:
1905                                 VECCOPY(pa->state.ave,r_ave);
1906                                 break;
1907                 }
1908                 Normalize(pa->state.ave);
1909                 VecMulf(pa->state.ave,part->avefac);
1910
1911                 icu=find_ipocurve(psys->part->ipo,PART_EMIT_AVE);
1912                 if(icu){
1913                         calc_icu(icu,100*((pa->time-part->sta)/(part->end-part->sta)));
1914                         VecMulf(pa->state.ave,icu->curval);
1915                 }
1916         }
1917
1918         pa->dietime = pa->time + pa->lifetime;
1919
1920         if(pa->time >= cfra)
1921                 pa->alive = PARS_UNBORN;
1922
1923         pa->state.time = cfra;
1924
1925         pa->stick_ob = 0;
1926         pa->flag &= ~PARS_STICKY;
1927 }
1928 static void reset_all_particles(Object *ob, ParticleSystem *psys, ParticleSystemModifierData *psmd, float dtime, float cfra, int from)
1929 {
1930         ParticleData *pa;
1931         int p, totpart=psys->totpart;
1932         float *vg_vel=psys_cache_vgroup(psmd->dm,psys,PSYS_VG_VEL);
1933         float *vg_tan=psys_cache_vgroup(psmd->dm,psys,PSYS_VG_TAN);
1934         float *vg_rot=psys_cache_vgroup(psmd->dm,psys,PSYS_VG_ROT);
1935         
1936         for(p=from, pa=psys->particles+from; p<totpart; p++, pa++)
1937                 reset_particle(pa, psys, psmd, ob, dtime, cfra, vg_vel, vg_tan, vg_rot);
1938
1939         if(vg_vel)
1940                 MEM_freeN(vg_vel);
1941 }
1942 /************************************************/
1943 /*                      Keyed particles                                         */
1944 /************************************************/
1945 /* a bit of an unintuitive function :) counts objects in a keyed chain and returns 1 if some of them were selected (used in drawing) */
1946 int psys_count_keyed_targets(Object *ob, ParticleSystem *psys)
1947 {
1948         ParticleSystem *kpsys=psys,*tpsys;
1949         ParticleSettings *tpart;
1950         Object *kob=ob,*tob;
1951         int select=ob->flag&SELECT;
1952         short totkeyed=0;
1953         Base *base;
1954
1955         ListBase lb;
1956         lb.first=lb.last=0;
1957
1958         tob=psys->keyed_ob;
1959         while(tob){
1960                 if((tpsys=BLI_findlink(&tob->particlesystem,kpsys->keyed_psys-1))){
1961                         tpart=tpsys->part;
1962
1963                         if(tpart->phystype==PART_PHYS_KEYED){
1964                                 if(lb.first){
1965                                         for(base=lb.first;base;base=base->next){
1966                                                 if(tob==base->object){
1967                                                         fprintf(stderr,"Error: loop in keyed chain!\n");
1968                                                         BLI_freelistN(&lb);
1969                                                         return select;
1970                                                 }
1971                                         }
1972                                 }
1973                                 base=MEM_callocN(sizeof(Base), "keyed base");
1974                                 base->object=tob;
1975                                 BLI_addtail(&lb,base);
1976
1977                                 if(tob->flag&SELECT)
1978                                         select++;
1979                                 kob=tob;
1980                                 kpsys=tpsys;
1981                                 tob=tpsys->keyed_ob;
1982                                 totkeyed++;
1983                         }
1984                         else{
1985                                 tob=0;
1986                                 totkeyed++;
1987                         }
1988                 }
1989                 else
1990                         tob=0;
1991         }
1992         psys->totkeyed=totkeyed;
1993         BLI_freelistN(&lb);
1994         return select;
1995 }
1996
1997 static void set_keyed_keys(Object *ob, ParticleSystem *psys)
1998 {
1999         Object *kob = ob;
2000         ParticleSystem *kpsys = psys;
2001         ParticleData *pa;
2002         ParticleKey state;
2003         int totpart = psys->totpart, i, k, totkeys = psys->totkeyed + 1;
2004         float prevtime, nexttime, keyedtime;
2005
2006         /* no proper targets so let's clear and bail out */
2007         if(psys->totkeyed==0) {
2008                 free_keyed_keys(psys);
2009                 psys->flag &= ~PSYS_KEYED;
2010                 return;
2011         }
2012
2013         if(totpart && psys->particles->totkey != totkeys) {
2014                 free_keyed_keys(psys);
2015                 
2016                 psys->particles->keys = MEM_callocN(psys->totpart*totkeys*sizeof(ParticleKey), "Keyed keys");
2017                 psys->particles->totkey = totkeys;
2018                 
2019                 for(i=1, pa=psys->particles+1; i<totpart; i++,pa++){
2020                         pa->keys = (pa-1)->keys + totkeys;
2021                         pa->totkey = totkeys;
2022                 }
2023         }
2024         
2025         psys->flag &= ~PSYS_KEYED;
2026         state.time=-1.0;
2027
2028         for(k=0; k<totkeys; k++) {
2029                 for(i=0,pa=psys->particles; i<totpart; i++, pa++) {
2030                         if(kpsys->totpart > 0)
2031                                 psys_get_particle_state(kob, kpsys, i%kpsys->totpart, pa->keys + k, 1);
2032
2033                         if(k==0)
2034                                 pa->keys->time = pa->time;
2035                         else if(k==totkeys-1)
2036                                 (pa->keys + k)->time = pa->time + pa->lifetime;
2037                         else{
2038                                 if(psys->flag & PSYS_KEYED_TIME){
2039                                         prevtime = (pa->keys + k - 1)->time;
2040                                         nexttime = pa->time + pa->lifetime;
2041                                         keyedtime = kpsys->part->keyed_time;
2042                                         (pa->keys + k)->time = (1.0f - keyedtime) * prevtime + keyedtime * nexttime;
2043                                 }
2044                                 else
2045                                         (pa->keys+k)->time = pa->time + (float)k / (float)(totkeys - 1) * pa->lifetime;
2046                         }
2047                 }
2048                 if(kpsys->keyed_ob){
2049                         kob = kpsys->keyed_ob;
2050                         kpsys = BLI_findlink(&kob->particlesystem, kpsys->keyed_psys - 1);
2051                 }
2052         }
2053
2054         psys->flag |= PSYS_KEYED;
2055 }
2056 /************************************************/
2057 /*                      Reactors                                                        */
2058 /************************************************/
2059 static void push_reaction(Object* ob, ParticleSystem *psys, int pa_num, int event, ParticleKey *state)
2060 {
2061         Object *rob;
2062         ParticleSystem *rpsys;
2063         ParticleSettings *rpart;
2064         ParticleData *pa;
2065         ListBase *lb=&psys->effectors;
2066         ParticleEffectorCache *ec;
2067         ParticleReactEvent *re;
2068
2069         if(lb->first) for(ec = lb->first; ec; ec= ec->next){
2070                 if(ec->type & PSYS_EC_REACTOR){
2071                         /* all validity checks already done in add_to_effectors */
2072                         rob=ec->ob;
2073                         rpsys=BLI_findlink(&rob->particlesystem,ec->psys_nbr);
2074                         rpart=rpsys->part;
2075                         if(rpsys->part->reactevent==event){
2076                                 pa=psys->particles+pa_num;
2077                                 re= MEM_callocN(sizeof(ParticleReactEvent), "react event");
2078                                 re->event=event;
2079                                 re->pa_num = pa_num;
2080                                 re->ob = ob;
2081                                 re->psys = psys;
2082                                 re->size = pa->size;
2083                                 copy_particle_key(&re->state,state,1);
2084
2085                                 switch(event){
2086                                         case PART_EVENT_DEATH:
2087                                                 re->time=pa->dietime;
2088                                                 break;
2089                                         case PART_EVENT_COLLIDE:
2090                                                 re->time=state->time;
2091                                                 break;
2092                                         case PART_EVENT_NEAR:
2093                                                 re->time=state->time;
2094                                                 break;
2095                                 }
2096
2097                                 BLI_addtail(&rpsys->reactevents, re);
2098                         }
2099                 }
2100         }
2101 }
2102 static void react_to_events(ParticleSystem *psys, int pa_num)
2103 {
2104         ParticleSettings *part=psys->part;
2105         ParticleData *pa=psys->particles+pa_num;
2106         ParticleReactEvent *re=psys->reactevents.first;
2107         int birth=0;
2108         float dist=0.0f;
2109
2110         for(re=psys->reactevents.first; re; re=re->next){
2111                 birth=0;
2112                 if(part->from==PART_FROM_PARTICLE){
2113                         if(pa->num==re->pa_num && pa->alive==PARS_UNBORN){
2114                                 if(re->event==PART_EVENT_NEAR){
2115                                         ParticleData *tpa = re->psys->particles+re->pa_num;
2116                                         float pa_time=tpa->time + pa->foffset*tpa->lifetime;
2117                                         if(re->time >= pa_time){
2118                                                 pa->time=pa_time;
2119                                                 pa->dietime=pa->time+pa->lifetime;
2120                                         }
2121                                 }
2122                                 else{
2123                                         pa->time=re->time;
2124                                         pa->dietime=pa->time+pa->lifetime;
2125                                 }
2126                         }
2127                 }
2128                 else{
2129                         dist=VecLenf(pa->state.co, re->state.co);
2130                         if(dist <= re->size){
2131                                 if(pa->alive==PARS_UNBORN){
2132                                         pa->time=re->time;
2133                                         pa->dietime=pa->time+pa->lifetime;
2134                                         birth=1;
2135                                 }
2136                                 if(birth || part->flag&PART_REACT_MULTIPLE){
2137                                         float vec[3];
2138                                         VECSUB(vec,pa->state.co, re->state.co);
2139                                         if(birth==0)
2140                                                 VecMulf(vec,(float)pow(1.0f-dist/re->size,part->reactshape));
2141                                         VECADDFAC(pa->state.vel,pa->state.vel,vec,part->reactfac);
2142                                         VECADDFAC(pa->state.vel,pa->state.vel,re->state.vel,part->partfac);
2143                                 }
2144                                 if(birth)
2145                                         VecMulf(pa->state.vel,(float)pow(1.0f-dist/re->size,part->reactshape));
2146                         }
2147                 }
2148         }
2149 }
2150 void psys_get_reactor_target(Object *ob, ParticleSystem *psys, Object **target_ob, ParticleSystem **target_psys)
2151 {
2152         Object *tob;
2153
2154         tob=psys->target_ob;
2155         if(tob==0)
2156                 tob=ob;
2157         
2158         *target_psys=BLI_findlink(&tob->particlesystem,psys->target_psys-1);
2159         if(*target_psys)
2160                 *target_ob=tob;
2161         else
2162                 *target_ob=0;
2163 }
2164 /************************************************/
2165 /*                      Point Cache                                                     */
2166 /************************************************/
2167
2168 static void write_particles_to_cache(Object *ob, ParticleSystem *psys, int cfra)
2169 {
2170         PTCacheID pid;
2171         PTCacheFile *pf;
2172         ParticleData *pa;
2173         int i, totpart= psys->totpart;
2174
2175         if(totpart == 0)
2176                 return;
2177
2178         BKE_ptcache_id_from_particles(&pid, ob, psys);
2179         pf= BKE_ptcache_file_open(&pid, PTCACHE_FILE_WRITE, cfra);
2180         if(!pf)
2181                 return;
2182
2183         /* assuming struct consists of tightly packed floats */
2184         for(i=0, pa=psys->particles; i<totpart; i++, pa++)
2185                 BKE_ptcache_file_write_floats(pf, (float*)&pa->state, sizeof(ParticleKey)/sizeof(float));
2186         
2187         BKE_ptcache_file_close(pf);
2188 }
2189
2190 static int get_particles_from_cache(Object *ob, ParticleSystem *psys, int cfra)
2191 {
2192         PTCacheID pid;
2193         PTCacheFile *pf;
2194         ParticleData *pa;
2195         int i, totpart= psys->totpart;
2196
2197         if(totpart == 0)
2198                 return 0;
2199
2200         BKE_ptcache_id_from_particles(&pid, ob, psys);
2201         pf= BKE_ptcache_file_open(&pid, PTCACHE_FILE_READ, cfra);
2202         if(!pf)
2203                 return 0;
2204
2205         /* assuming struct consists of tightly packed floats */
2206         for(i=0, pa=psys->particles; i<totpart; i++, pa++) {
2207                 if(!BKE_ptcache_file_read_floats(pf, (float*)&pa->state, sizeof(ParticleKey)/sizeof(float))) {
2208                         BKE_ptcache_file_close(pf);
2209                         return 0;
2210                 }
2211         }
2212
2213         BKE_ptcache_file_close(pf);
2214
2215         return 1;
2216 }
2217
2218 /************************************************/
2219 /*                      Effectors                                                       */
2220 /************************************************/
2221 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)
2222 {
2223         TexResult result[4];
2224         float tex_co[3], strength, mag_vec[3];
2225         int hasrgb;
2226         if(tex==NULL) return;
2227
2228         result[0].nor = result[1].nor = result[2].nor = result[3].nor = 0;
2229
2230         strength= force_val*falloff;///(float)pow((double)distance,(double)power);
2231
2232         VECCOPY(tex_co,pa_co);
2233
2234         if(is_2d){
2235                 float fac=-Inpf(tex_co,obmat[2]);
2236                 VECADDFAC(tex_co,tex_co,obmat[2],fac);
2237         }
2238
2239         if(object){
2240                 VecSubf(tex_co,tex_co,obmat[3]);
2241                 Mat4Mul3Vecfl(obmat,tex_co);
2242         }
2243
2244         hasrgb = multitex_ext(tex, tex_co, NULL,NULL, 1, result);
2245
2246         if(hasrgb && mode==PFIELD_TEX_RGB){
2247                 mag_vec[0]= (0.5f-result->tr)*strength;
2248                 mag_vec[1]= (0.5f-result->tg)*strength;
2249                 mag_vec[2]= (0.5f-result->tb)*strength;
2250         }
2251         else{
2252                 strength/=nabla;
2253
2254                 tex_co[0]+= nabla;
2255                 multitex_ext(tex, tex_co, NULL,NULL, 1, result+1);
2256
2257                 tex_co[0]-= nabla;
2258                 tex_co[1]+= nabla;
2259                 multitex_ext(tex, tex_co, NULL,NULL, 1, result+2);
2260
2261                 tex_co[1]-= nabla;
2262                 tex_co[2]+= nabla;
2263                 multitex_ext(tex, tex_co, NULL,NULL, 1, result+3);
2264
2265                 if(mode==PFIELD_TEX_GRAD || !hasrgb){ /* if we dont have rgb fall back to grad */
2266                         mag_vec[0]= (result[0].tin-result[1].tin)*strength;
2267                         mag_vec[1]= (result[0].tin-result[2].tin)*strength;
2268                         mag_vec[2]= (result[0].tin-result[3].tin)*strength;
2269                 }
2270                 else{ /*PFIELD_TEX_CURL*/
2271                         float dbdy,dgdz,drdz,dbdx,dgdx,drdy;
2272
2273                         dbdy= result[2].tb-result[0].tb;
2274                         dgdz= result[3].tg-result[0].tg;
2275                         drdz= result[3].tr-result[0].tr;
2276                         dbdx= result[1].tb-result[0].tb;
2277                         dgdx= result[1].tg-result[0].tg;
2278                         drdy= result[2].tr-result[0].tr;
2279
2280                         mag_vec[0]=(dbdy-dgdz)*strength;
2281                         mag_vec[1]=(drdz-dbdx)*strength;
2282                         mag_vec[2]=(dgdx-drdy)*strength;
2283                 }
2284         }
2285
2286         if(is_2d){
2287                 float fac=-Inpf(mag_vec,obmat[2]);
2288                 VECADDFAC(mag_vec,mag_vec,obmat[2],fac);
2289         }
2290
2291         VecAddf(field,field,mag_vec);
2292 }
2293 static void add_to_effectors(ListBase *lb, Object *ob, Object *obsrc, ParticleSystem *psys)
2294 {
2295         ParticleEffectorCache *ec;
2296         PartDeflect *pd= ob->pd;
2297         short type=0,i;
2298
2299         if(pd && ob != obsrc){
2300                 if(pd->forcefield == PFIELD_GUIDE) {
2301                         if(ob->type==OB_CURVE) {
2302                                 Curve *cu= ob->data;
2303                                 if(cu->flag & CU_PATH) {
2304                                         if(cu->path==NULL || cu->path->data==NULL)
2305                                                 makeDispListCurveTypes(ob, 0);
2306                                         if(cu->path && cu->path->data) {
2307                                                 type |= PSYS_EC_EFFECTOR;
2308                                         }
2309                                 }
2310                         }
2311                 }
2312                 else if(pd->forcefield)
2313                 {
2314                         type |= PSYS_EC_EFFECTOR;
2315                 }
2316         }
2317         
2318         if(pd && pd->deflect)
2319                 type |= PSYS_EC_DEFLECT;
2320
2321         if(type){
2322                 ec= MEM_callocN(sizeof(ParticleEffectorCache), "effector cache");
2323                 ec->ob= ob;
2324                 ec->type=type;
2325                 ec->distances=0;
2326                 ec->locations=0;
2327                 ec->rng = rng_new(1);
2328                 rng_srandom(ec->rng, (unsigned int)(ceil(PIL_check_seconds_timer()))); // use better seed
2329                 
2330                 BLI_addtail(lb, ec);
2331         }
2332
2333         type=0;
2334
2335         /* add particles as different effectors */
2336         if(ob->particlesystem.first){
2337                 ParticleSystem *epsys=ob->particlesystem.first;
2338                 ParticleSettings *epart=0;
2339                 Object *tob;
2340
2341                 for(i=0; epsys; epsys=epsys->next,i++){
2342                         type=0;
2343                         if(epsys!=psys || (psys->part->flag & PART_SELF_EFFECT)){
2344                                 epart=epsys->part;
2345
2346                                 if((epsys->part->pd && epsys->part->pd->forcefield)
2347                                         || (epsys->part->pd2 && epsys->part->pd2->forcefield))
2348                                 {
2349                                         type=PSYS_EC_PARTICLE;
2350                                 }
2351
2352                                 if(epart->type==PART_REACTOR) {
2353                                         tob=epsys->target_ob;
2354                                         if(tob==0)
2355                                                 tob=ob;
2356                                         if(BLI_findlink(&tob->particlesystem,epsys->target_psys-1)==psys)
2357                                                 type|=PSYS_EC_REACTOR;
2358                                 }
2359
2360                                 if(type){
2361                                         ec= MEM_callocN(sizeof(ParticleEffectorCache), "effector cache");
2362                                         ec->ob= ob;
2363                                         ec->type=type;
2364                                         ec->psys_nbr=i;
2365                                         ec->rng = rng_new(1);
2366                                         rng_srandom(ec->rng, (unsigned int)(ceil(PIL_check_seconds_timer())));
2367                                         
2368                                         BLI_addtail(lb, ec);
2369                                 }
2370                         }
2371                 }
2372                                 
2373         }
2374 }
2375
2376 static void psys_init_effectors_recurs(Object *ob, Object *obsrc, ParticleSystem *psys, ListBase *listb, int level)
2377 {
2378         Group *group;
2379         GroupObject *go;
2380         unsigned int layer= obsrc->lay;
2381
2382         if(level>MAX_DUPLI_RECUR) return;
2383
2384         if(ob->lay & layer) {
2385                 if(ob->pd || ob->particlesystem.first)
2386                         add_to_effectors(listb, ob, obsrc, psys);
2387
2388                 if(ob->dup_group) {
2389                         group= ob->dup_group;
2390                         for(go= group->gobject.first; go; go= go->next)
2391                                 psys_init_effectors_recurs(go->ob, obsrc, psys, listb, level+1);
2392                 }
2393         }
2394 }
2395
2396 void psys_init_effectors(Object *obsrc, Group *group, ParticleSystem *psys)
2397 {
2398         ListBase *listb= &psys->effectors;
2399         Base *base;
2400
2401         listb->first=listb->last=0;
2402         
2403         if(group) {
2404                 GroupObject *go;
2405                 
2406                 for(go= group->gobject.first; go; go= go->next)
2407                         psys_init_effectors_recurs(go->ob, obsrc, psys, listb, 0);
2408         }
2409         else {
2410                 for(base = G.scene->base.first; base; base= base->next)
2411                         psys_init_effectors_recurs(base->object, obsrc, psys, listb, 0);
2412         }
2413 }
2414
2415 void psys_end_effectors(ParticleSystem *psys)
2416 {
2417         /* NOTE:
2418         ec->ob is not valid in here anymore! - dg
2419         */
2420         ListBase *lb=&psys->effectors;
2421         if(lb->first) {
2422                 ParticleEffectorCache *ec;
2423                 for(ec= lb->first; ec; ec= ec->next){
2424                         if(ec->distances)
2425                                 MEM_freeN(ec->distances);
2426
2427                         if(ec->locations)
2428                                 MEM_freeN(ec->locations);
2429
2430                         if(ec->face_minmax)
2431                                 MEM_freeN(ec->face_minmax);
2432
2433                         if(ec->vert_cos)
2434                                 MEM_freeN(ec->vert_cos);
2435
2436                         if(ec->tree)
2437                                 BLI_kdtree_free(ec->tree);
2438                         
2439                         if(ec->rng)
2440                                 rng_free(ec->rng);
2441                         
2442                 }
2443
2444                 BLI_freelistN(lb);
2445         }
2446 }
2447
2448 static void precalc_effectors(Object *ob, ParticleSystem *psys, ParticleSystemModifierData *psmd, float cfra)
2449 {
2450         ListBase *lb=&psys->effectors;
2451         ParticleEffectorCache *ec;
2452         ParticleSettings *part=psys->part;
2453         ParticleData *pa;
2454         float vec2[3],loc[3],*co=0;
2455         int p,totpart,totvert;
2456         
2457         for(ec= lb->first; ec; ec= ec->next) {
2458                 PartDeflect *pd= ec->ob->pd;
2459                 co = NULL;
2460                 
2461                 if(ec->type==PSYS_EC_EFFECTOR && pd->forcefield==PFIELD_GUIDE && ec->ob->type==OB_CURVE 
2462                         && part->phystype!=PART_PHYS_BOIDS) {
2463                         float vec[4];
2464
2465                         where_on_path(ec->ob, 0.0, vec, vec2);
2466
2467                         Mat4MulVecfl(ec->ob->obmat,vec);
2468                         Mat4Mul3Vecfl(ec->ob->obmat,vec2);
2469
2470                         QUATCOPY(ec->firstloc,vec);
2471                         VECCOPY(ec->firstdir,vec2);
2472
2473                         totpart=psys->totpart;
2474
2475                         if(totpart){
2476                                 ec->distances=MEM_callocN(totpart*sizeof(float),"particle distances");
2477                                 ec->locations=MEM_callocN(totpart*3*sizeof(float),"particle locations");
2478
2479                                 for(p=0,pa=psys->particles; p<totpart; p++, pa++){
2480                                         psys_particle_on_emitter(ob,psmd,part->from,pa->num,pa->num_dmcache,pa->fuv,pa->foffset,loc,0,0,0,0,0);
2481                                         Mat4MulVecfl(ob->obmat,loc);
2482                                         ec->distances[p]=VecLenf(loc,vec);
2483                                         VECSUB(loc,loc,vec);
2484                                         VECCOPY(ec->locations+3*p,loc);
2485                                 }
2486                         }
2487                 }
2488                 else if(ec->type==PSYS_EC_PARTICLE){
2489                         Object *eob = ec->ob;
2490                         ParticleSystem *epsys = BLI_findlink(&eob->particlesystem,ec->psys_nbr);
2491                         ParticleSettings *epart = epsys->part;
2492                         ParticleData *epa = epsys->particles;
2493                         int totepart = epsys->totpart;
2494
2495                         if(psys->part->phystype==PART_PHYS_BOIDS){
2496                                 ParticleData *epa;
2497                                 ParticleKey state;
2498                                 PartDeflect *pd;
2499                                 int p;
2500                                 
2501                                 pd= epart->pd;
2502                                 if(pd->forcefield==PFIELD_FORCE && totepart){
2503                                         KDTree *tree;
2504
2505                                         tree=BLI_kdtree_new(totepart);
2506                                         ec->tree=tree;
2507
2508                                         for(p=0, epa=epsys->particles; p<totepart; p++,epa++)
2509                                                 if(epa->alive==PARS_ALIVE && psys_get_particle_state(eob,epsys,p,&state,0))
2510                                                         BLI_kdtree_insert(tree, p, state.co, NULL);
2511
2512                                         BLI_kdtree_balance(tree);
2513                                 }
2514                         }
2515                 }
2516                 else if(ec->type==PSYS_EC_DEFLECT) {
2517                         CollisionModifierData *collmd = ( CollisionModifierData * ) ( modifiers_findByType ( ec->ob, eModifierType_Collision ) );
2518                         if(collmd)
2519                                 collision_move_object(collmd, 1.0, 0.0);
2520                 }
2521         }
2522 }
2523
2524
2525 /* calculate forces that all effectors apply to a particle*/
2526 void do_effectors(int pa_no, ParticleData *pa, ParticleKey *state, Object *ob, ParticleSystem *psys, float *rootco, float *force_field, float *vel,float framestep, float cfra)
2527 {
2528         Object *eob;
2529         ParticleSystem *epsys;
2530         ParticleSettings *epart;
2531         ParticleData *epa;
2532         ParticleKey estate;
2533         PartDeflect *pd;
2534         ListBase *lb=&psys->effectors;
2535         ParticleEffectorCache *ec;
2536         float distance, vec_to_part[3];
2537         float falloff, charge = 0.0f;
2538         int p;
2539
2540         /* check all effector objects for interaction */
2541         if(lb->first){
2542                 if(psys->part->pd && psys->part->pd->forcefield==PFIELD_CHARGE){
2543                         /* Only the charge of the effected particle is used for 
2544                            interaction, not fall-offs. If the fall-offs aren't the      
2545                            same this will be unphysical, but for animation this         
2546                            could be the wanted behavior. If you want physical
2547                            correctness the fall-off should be spherical 2.0 anyways.
2548                          */
2549                         charge = psys->part->pd->f_strength;
2550                 }
2551                 if(psys->part->pd2 && psys->part->pd2->forcefield==PFIELD_CHARGE){
2552                         charge += psys->part->pd2->f_strength;
2553                 }
2554                 for(ec = lb->first; ec; ec= ec->next){
2555                         eob= ec->ob;
2556                         if(ec->type & PSYS_EC_EFFECTOR){
2557                                 pd=eob->pd;
2558                                 if(psys->part->type!=PART_HAIR && psys->part->integrator)
2559                                         where_is_object_time(eob,cfra);
2560
2561                                 /* use center of object for distance calculus */
2562                                 VecSubf(vec_to_part, state->co, eob->obmat[3]);
2563                                 distance = VecLength(vec_to_part);
2564
2565                                 falloff=effector_falloff(pd,eob->obmat[2],vec_to_part);
2566
2567                                 if(falloff<=0.0f)
2568                                         ;       /* don't do anything */
2569                                 else if(pd->forcefield==PFIELD_TEXTURE) {
2570                                         do_texture_effector(pd->tex, pd->tex_mode, pd->flag&PFIELD_TEX_2D, pd->tex_nabla,
2571                                                                         pd->flag & PFIELD_TEX_OBJECT, (pd->flag & PFIELD_TEX_ROOTCO) ? rootco : state->co, eob->obmat,
2572                                                                         pd->f_strength, falloff, force_field);
2573                                 } else {
2574                                         do_physical_effector(eob, state->co, pd->forcefield,pd->f_strength,distance,
2575                                                                                 falloff,0.0,pd->f_damp,eob->obmat[2],vec_to_part,
2576                                                                                 pa->state.vel,force_field,pd->flag&PFIELD_PLANAR,ec->rng,pd->f_noise,charge,pa->size);
2577                                 }
2578                         }
2579                         if(ec->type & PSYS_EC_PARTICLE){
2580                                 int totepart, i;
2581                                 epsys= BLI_findlink(&eob->particlesystem,ec->psys_nbr);
2582                                 epart= epsys->part;
2583                                 pd=epart->pd;
2584                                 totepart= epsys->totpart;
2585                                 
2586                                 if(totepart <= 0)
2587                                         continue;
2588                                 
2589                                 if(pd && pd->forcefield==PFIELD_HARMONIC){
2590                                         /* every particle is mapped to only one harmonic effector particle */
2591                                         p= pa_no%epsys->totpart;
2592                                         totepart= p+1;
2593                                 }
2594                                 else{
2595                                         p=0;
2596                                 }
2597
2598                                 epsys->lattice=psys_get_lattice(ob,psys);
2599
2600                                 for(; p<totepart; p++){
2601                                         /* particle skips itself as effector */
2602                                         if(epsys==psys && p == pa_no) continue;
2603
2604                                         epa = epsys->particles + p;
2605                                         estate.time=-1.0;
2606                                         if(psys_get_particle_state(eob,epsys,p,&estate,0)){
2607                                                 VECSUB(vec_to_part, state->co, estate.co);
2608                                                 distance = VecLength(vec_to_part);
2609                                                 
2610                                                 for(i=0, pd = epart->pd; i<2; i++,pd = epart->pd2) {
2611                                                         if(pd==NULL || pd->forcefield==0) continue;
2612
2613                                                         falloff=effector_falloff(pd,estate.vel,vec_to_part);
2614
2615                                                         if(falloff<=0.0f)
2616                                                                 ;       /* don't do anything */
2617                                                         else
2618                                                                 do_physical_effector(eob, state->co, pd->forcefield,pd->f_strength,distance,
2619                                                                 falloff,epart->size,pd->f_damp,estate.vel,vec_to_part,
2620                                                                 state->vel,force_field,0, ec->rng, pd->f_noise,charge,pa->size);
2621                                                 }
2622                                         }
2623                                         else if(pd && pd->forcefield==PFIELD_HARMONIC && cfra-framestep <= epa->dietime && cfra>epa->dietime){
2624                                                 /* first step after key release */
2625                                                 psys_get_particle_state(eob,epsys,p,&estate,1);
2626                                                 VECADD(vel,vel,estate.vel);
2627                                                 /* TODO: add rotation handling here too */
2628                                         }
2629                                 }
2630
2631                                 if(epsys->lattice){
2632                                         end_latt_deform();
2633                                         epsys->lattice=0;
2634                                 }
2635                         }
2636                 }
2637         }
2638 }
2639
2640 /************************************************/
2641 /*                      Newtonian physics                                       */
2642 /************************************************/
2643 /* gathers all forces that effect particles and calculates a new state for the particle */
2644 static void apply_particle_forces(int pa_no, ParticleData *pa, Object *ob, ParticleSystem *psys, ParticleSettings *part, float timestep, float dfra, float cfra, ParticleKey *state)
2645 {
2646         ParticleKey states[5], tkey;
2647         float force[3],tvel[3],dx[4][3],dv[4][3];
2648         float dtime=dfra*timestep, time, pa_mass=part->mass, fac, fra=psys->cfra;
2649         int i, steps=1;
2650         
2651         /* maintain angular velocity */
2652         VECCOPY(state->ave,pa->state.ave);
2653
2654         if(part->flag & PART_SIZEMASS)
2655                 pa_mass*=pa->size;
2656
2657         switch(part->integrator){
2658                 case PART_INT_EULER:
2659                         steps=1;
2660                         break;
2661                 case PART_INT_MIDPOINT:
2662                         steps=2;
2663                         break;
2664                 case PART_INT_RK4:
2665                         steps=4;
2666                         break;
2667         }
2668
2669         copy_particle_key(states,&pa->state,1);
2670
2671         for(i=0; i<steps; i++){
2672                 force[0]=force[1]=force[2]=0.0;
2673                 tvel[0]=tvel[1]=tvel[2]=0.0;
2674                 /* add effectors */
2675                 if(part->type != PART_HAIR)
2676                         do_effectors(pa_no,pa,states+i,ob,psys,states->co,force,tvel,dfra,fra);
2677
2678                 /* calculate air-particle interaction */
2679                 if(part->dragfac!=0.0f){
2680                         fac=-part->dragfac*pa->size*pa->size*VecLength(states[i].vel);
2681                         VECADDFAC(force,force,states[i].vel,fac);
2682                 }
2683
2684                 /* brownian force */
2685                 if(part->brownfac!=0.0){
2686                         force[0]+=(BLI_frand()-0.5f)*part->brownfac;
2687                         force[1]+=(BLI_frand()-0.5f)*part->brownfac;
2688                         force[2]+=(BLI_frand()-0.5f)*part->brownfac;
2689                 }
2690
2691                 /* force to acceleration*/
2692                 VecMulf(force,1.0f/pa_mass);
2693
2694                 /* add global acceleration (gravitation) */
2695                 VECADD(force,force,part->acc);
2696                 
2697                 /* calculate next state */
2698                 VECADD(states[i].vel,states[i].vel,tvel);
2699
2700                 switch(part->integrator){
2701                         case PART_INT_EULER:
2702                                 VECADDFAC(state->co,states->co,states->vel,dtime);
2703                                 VECADDFAC(state->vel,states->vel,force,dtime);
2704                                 break;
2705                         case PART_INT_MIDPOINT:
2706                                 if(i==0){
2707                                         VECADDFAC(states[1].co,states->co,states->vel,dtime*0.5f);
2708                                         VECADDFAC(states[1].vel,states->vel,force,dtime*0.5f);
2709                                         fra=psys->cfra+0.5f*dfra;
2710                                 }
2711                                 else{
2712                                         VECADDFAC(state->co,states->co,states[1].vel,dtime);
2713                                         VECADDFAC(state->vel,states->vel,force,dtime);
2714                                 }
2715                                 break;
2716                         case PART_INT_RK4:
2717                                 switch(i){
2718                                         case 0:
2719                                                 VECCOPY(dx[0],states->vel);
2720                                                 VecMulf(dx[0],dtime);
2721                                                 VECCOPY(dv[0],force);
2722                                                 VecMulf(dv[0],dtime);
2723
2724                                                 VECADDFAC(states[1].co,states->co,dx[0],0.5f);
2725                                                 VECADDFAC(states[1].vel,states->vel,dv[0],0.5f);
2726                                                 fra=psys->cfra+0.5f*dfra;
2727                                                 break;
2728                                         case 1:
2729                                                 VECADDFAC(dx[1],states->vel,dv[0],0.5f);
2730                                                 VecMulf(dx[1],dtime);
2731                                                 VECCOPY(dv[1],force);
2732                                                 VecMulf(dv[1],dtime);
2733
2734                                                 VECADDFAC(states[2].co,states->co,dx[1],0.5f);
2735                                                 VECADDFAC(states[2].vel,states->vel,dv[1],0.5f);
2736                                                 break;
2737                                         case 2:
2738                                                 VECADDFAC(dx[2],states->vel,dv[1],0.5f);
2739                                                 VecMulf(dx[2],dtime);
2740                                                 VECCOPY(dv[2],force);
2741                                                 VecMulf(dv[2],dtime);
2742
2743                                                 VECADD(states[3].co,states->co,dx[2]);
2744                                                 VECADD(states[3].vel,states->vel,dv[2]);
2745                                                 fra=cfra;
2746                                                 break;
2747                                         case 3:
2748                                                 VECADD(dx[3],states->vel,dv[2]);
2749                                                 VecMulf(dx[3],dtime);
2750                                                 VECCOPY(dv[3],force);
2751                                                 VecMulf(dv[3],dtime);
2752
2753                                                 VECADDFAC(state->co,states->co,dx[0],1.0f/6.0f);
2754                                                 VECADDFAC(state->co,state->co,dx[1],1.0f/3.0f);
2755                                                 VECADDFAC(state->co,state->co,dx[2],1.0f/3.0f);
2756                                                 VECADDFAC(state->co,state->co,dx[3],1.0f/6.0f);
2757
2758                                                 VECADDFAC(state->vel,states->vel,dv[0],1.0f/6.0f);
2759                                                 VECADDFAC(state->vel,state->vel,dv[1],1.0f/3.0f);
2760                                                 VECADDFAC(state->vel,state->vel,dv[2],1.0f/3.0f);
2761                                                 VECADDFAC(state->vel,state->vel,dv[3],1.0f/6.0f);
2762                                 }
2763                                 break;
2764                 }
2765         }
2766
2767         /* damp affects final velocity */
2768         if(part->dampfac!=0.0)
2769                 VecMulf(state->vel,1.0f-part->dampfac);
2770
2771         /* finally we do guides */
2772         time=(cfra-pa->time)/pa->lifetime;
2773         CLAMP(time,0.0,1.0);
2774
2775         VECCOPY(tkey.co,state->co);
2776         VECCOPY(tkey.vel,state->vel);
2777         tkey.time=state->time;
2778
2779         if(part->type != PART_HAIR) {
2780                 if(do_guide(&tkey,pa_no,time,&psys->effectors)) {
2781                         VECCOPY(state->co,tkey.co);
2782                         /* guides don't produce valid velocity */
2783                         VECSUB(state->vel,tkey.co,pa->state.co);
2784                         VecMulf(state->vel,1.0f/dtime);
2785                         state->time=tkey.time;
2786                 }
2787         }
2788 }
2789 static void rotate_particle(ParticleSettings *part, ParticleData *pa, float dfra, float timestep, ParticleKey *state)
2790 {
2791         float rotfac, rot1[4], rot2[4]={1.0,0.0,0.0,0.0}, dtime=dfra*timestep;
2792
2793         if((part->flag & PART_ROT_DYN)==0){
2794                 if(part->avemode==PART_AVE_SPIN){
2795                         float angle;
2796                         float len1 = VecLength(pa->state.vel);
2797                         float len2 = VecLength(state->vel);
2798
2799                         if(len1==0.0f || len2==0.0f)
2800                                 state->ave[0]=state->ave[1]=state->ave[2]=0.0f;
2801                         else{
2802                                 Crossf(state->ave,pa->state.vel,state->vel);
2803                                 Normalize(state->ave);
2804                                 angle=Inpf(pa->state.vel,state->vel)/(len1*len2);
2805                                 VecMulf(state->ave,saacos(angle)/dtime);
2806                         }
2807
2808                         VecRotToQuat(state->vel,dtime*part->avefac,rot2);
2809                 }
2810         }
2811
2812         rotfac=VecLength(state->ave);
2813         if(rotfac==0.0){ /* QuatOne (in VecRotToQuat) doesn't give unit quat [1,0,0,0]?? */
2814                 rot1[0]=1.0;
2815                 rot1[1]=rot1[2]=rot1[3]=0;
2816         }
2817         else{
2818                 VecRotToQuat(state->ave,rotfac*dtime,rot1);
2819         }
2820         QuatMul(state->rot,rot1,pa->state.rot);
2821         QuatMul(state->rot,rot2,state->rot);
2822