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