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