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