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