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