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