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