Fix part of #20090: boolean modifier would lose link to object
[blender.git] / source / blender / blenkernel / intern / particle_system.c
1 /* particle_system.c
2  *
3  *
4  * $Id$
5  *
6  * ***** BEGIN GPL LICENSE BLOCK *****
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License
10  * as published by the Free Software Foundation; either version 2
11  * of the License, or (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software Foundation,
20  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
21  *
22  * The Original Code is Copyright (C) 2007 by Janne Karhu.
23  * All rights reserved.
24  *
25  * The Original Code is: all of this file.
26  *
27  * Contributor(s): none yet.
28  *
29  * ***** END GPL LICENSE BLOCK *****
30  */
31
32 #include "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(psys->edit && psys->free_edit) {
176                 psys->free_edit(psys->edit);
177                 psys->edit = NULL;
178                 psys->free_edit = NULL;
179         }
180
181         if(new_totpart<0) {
182                 if(part->distr==PART_DISTR_GRID  && part->from != PART_FROM_VERT) {
183                         totpart= part->grid_res;
184                         totpart*=totpart*totpart;
185                 }
186                 else
187                         totpart=part->totpart;
188         }
189         else
190                 totpart=new_totpart;
191
192         if(totpart && totpart != psys->totpart) {
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
1060                         return 0;
1061                 }
1062         }
1063         else{
1064                 dm= CDDM_from_mesh((Mesh*)ob->data, ob);
1065
1066                 /* special handling of grid distribution */
1067                 if(part->distr==PART_DISTR_GRID && from != PART_FROM_VERT){
1068                         distribute_particles_in_grid(dm,psys);
1069                         dm->release(dm);
1070                         return 0;
1071                 }
1072
1073                 /* we need orco for consistent distributions */
1074                 DM_add_vert_layer(dm, CD_ORCO, CD_ASSIGN, get_mesh_orco_verts(ob));
1075
1076                 distr=part->distr;
1077                 pa=psys->particles;
1078                 if(from==PART_FROM_VERT){
1079                         MVert *mv= dm->getVertDataArray(dm, CD_MVERT);
1080                         float (*orcodata)[3]= dm->getVertDataArray(dm, CD_ORCO);
1081                         int totvert = dm->getNumVerts(dm);
1082
1083                         tree=BLI_kdtree_new(totvert);
1084
1085                         for(p=0; p<totvert; p++){
1086                                 if(orcodata) {
1087                                         VECCOPY(co,orcodata[p])
1088                                         transform_mesh_orco_verts((Mesh*)ob->data, &co, 1, 1);
1089                                 }
1090                                 else
1091                                         VECCOPY(co,mv[p].co)
1092                                 BLI_kdtree_insert(tree,p,co,NULL);
1093                         }
1094
1095                         BLI_kdtree_balance(tree);
1096                 }
1097         }
1098
1099         /* 1. */
1100         switch(from){
1101                 case PART_FROM_VERT:
1102                         tot = dm->getNumVerts(dm);
1103                         break;
1104                 case PART_FROM_VOLUME:
1105                 case PART_FROM_FACE:
1106                         tot = dm->getNumFaces(dm);
1107                         break;
1108                 case PART_FROM_PARTICLE:
1109                         if(psys->target_ob)
1110                                 tob=psys->target_ob;
1111                         else
1112                                 tob=ob;
1113
1114                         if((tpsys=BLI_findlink(&tob->particlesystem,psys->target_psys-1))){
1115                                 tpars=tpsys->particles;
1116                                 tot=tpsys->totpart;
1117                         }
1118                         break;
1119         }
1120
1121         if(tot==0){
1122                 no_distr=1;
1123                 if(children){
1124                         if(G.f & G_DEBUG)
1125                                 fprintf(stderr,"Particle child distribution error: Nothing to emit from!\n");
1126                         if(psys->child) {
1127                                 for(p=0,cpa=psys->child; p<totpart; p++,cpa++){
1128                                         cpa->fuv[0]=cpa->fuv[1]=cpa->fuv[2]=cpa->fuv[3]= 0.0;
1129                                         cpa->foffset= 0.0f;
1130                                         cpa->parent=0;
1131                                         cpa->pa[0]=cpa->pa[1]=cpa->pa[2]=cpa->pa[3]=0;
1132                                         cpa->num= -1;
1133                                 }
1134                         }
1135                 }
1136                 else {
1137                         if(G.f & G_DEBUG)
1138                                 fprintf(stderr,"Particle distribution error: Nothing to emit from!\n");
1139                         for(p=0,pa=psys->particles; p<totpart; p++,pa++){
1140                                 pa->fuv[0]=pa->fuv[1]=pa->fuv[2]= pa->fuv[3]= 0.0;
1141                                 pa->foffset= 0.0f;
1142                                 pa->num= -1;
1143                         }
1144                 }
1145
1146                 if(dm != finaldm) dm->release(dm);
1147                 return 0;
1148         }
1149
1150         /* 2. */
1151
1152         weight=MEM_callocN(sizeof(float)*tot, "particle_distribution_weights");
1153         index=MEM_callocN(sizeof(int)*totpart, "particle_distribution_indexes");
1154         sum=MEM_callocN(sizeof(float)*(tot+1), "particle_distribution_sum");
1155         jitoff=MEM_callocN(sizeof(float)*tot, "particle_distribution_jitoff");
1156
1157         /* 2.1 */
1158         if((part->flag&PART_EDISTR || children) && ELEM(from,PART_FROM_PARTICLE,PART_FROM_VERT)==0){
1159                 MVert *v1, *v2, *v3, *v4;
1160                 float totarea=0.0, co1[3], co2[3], co3[3], co4[3];
1161                 float (*orcodata)[3];
1162                 
1163                 orcodata= dm->getVertDataArray(dm, CD_ORCO);
1164
1165                 for(i=0; i<tot; i++){
1166                         MFace *mf=dm->getFaceData(dm,i,CD_MFACE);
1167
1168                         if(orcodata) {
1169                                 VECCOPY(co1, orcodata[mf->v1]);
1170                                 VECCOPY(co2, orcodata[mf->v2]);
1171                                 VECCOPY(co3, orcodata[mf->v3]);
1172                                 transform_mesh_orco_verts((Mesh*)ob->data, &co1, 1, 1);
1173                                 transform_mesh_orco_verts((Mesh*)ob->data, &co2, 1, 1);
1174                                 transform_mesh_orco_verts((Mesh*)ob->data, &co3, 1, 1);
1175                         }
1176                         else {
1177                                 v1= (MVert*)dm->getVertData(dm,mf->v1,CD_MVERT);
1178                                 v2= (MVert*)dm->getVertData(dm,mf->v2,CD_MVERT);
1179                                 v3= (MVert*)dm->getVertData(dm,mf->v3,CD_MVERT);
1180                                 VECCOPY(co1, v1->co);
1181                                 VECCOPY(co2, v2->co);
1182                                 VECCOPY(co3, v3->co);
1183                         }
1184
1185                         if (mf->v4){
1186                                 if(orcodata) {
1187                                         VECCOPY(co4, orcodata[mf->v4]);
1188                                         transform_mesh_orco_verts((Mesh*)ob->data, &co4, 1, 1);
1189                                 }
1190                                 else {
1191                                         v4= (MVert*)dm->getVertData(dm,mf->v4,CD_MVERT);
1192                                         VECCOPY(co4, v4->co);
1193                                 }
1194                                 cur= area_quad_v3(co1, co2, co3, co4);
1195                         }
1196                         else
1197                                 cur= area_tri_v3(co1, co2, co3);
1198                         
1199                         if(cur>maxweight)
1200                                 maxweight=cur;
1201
1202                         weight[i]= cur;
1203                         totarea+=cur;
1204                 }
1205
1206                 for(i=0; i<tot; i++)
1207                         weight[i] /= totarea;
1208
1209                 maxweight /= totarea;
1210         }
1211         else if(from==PART_FROM_PARTICLE){
1212                 float val=(float)tot/(float)totpart;
1213                 for(i=0; i<tot; i++)
1214                         weight[i]=val;
1215                 maxweight=val;
1216         }
1217         else{
1218                 float min=1.0f/(float)(MIN2(tot,totpart));
1219                 for(i=0; i<tot; i++)
1220                         weight[i]=min;
1221                 maxweight=min;
1222         }
1223
1224         /* 2.2 */
1225         if(ELEM3(from,PART_FROM_VERT,PART_FROM_FACE,PART_FROM_VOLUME)){
1226                 float *vweight= psys_cache_vgroup(dm,psys,PSYS_VG_DENSITY);
1227
1228                 if(vweight){
1229                         if(from==PART_FROM_VERT) {
1230                                 for(i=0;i<tot; i++)
1231                                         weight[i]*=vweight[i];
1232                         }
1233                         else { /* PART_FROM_FACE / PART_FROM_VOLUME */
1234                                 for(i=0;i<tot; i++){
1235                                         MFace *mf=dm->getFaceData(dm,i,CD_MFACE);
1236                                         tweight = vweight[mf->v1] + vweight[mf->v2] + vweight[mf->v3];
1237                                 
1238                                         if(mf->v4) {
1239                                                 tweight += vweight[mf->v4];
1240                                                 tweight /= 4.0;
1241                                         }
1242                                         else {
1243                                                 tweight /= 3.0;
1244                                         }
1245
1246                                         weight[i]*=tweight;
1247                                 }
1248                         }
1249                         MEM_freeN(vweight);
1250                 }
1251         }
1252
1253         /* 3. */
1254         totweight= 0.0f;
1255         for(i=0;i<tot; i++)
1256                 totweight += weight[i];
1257
1258         if(totweight > 0.0f)
1259                 totweight= 1.0f/totweight;
1260
1261         sum[0]= 0.0f;
1262         for(i=0;i<tot; i++)
1263                 sum[i+1]= sum[i]+weight[i]*totweight;
1264         
1265         if((part->flag&PART_TRAND) || (part->simplify_flag&PART_SIMPLIFY_ENABLE)) {
1266                 float pos;
1267
1268                 for(p=0; p<totpart; p++) {
1269                         pos= BLI_frand();
1270                         index[p]= binary_search_distribution(sum, tot, pos);
1271                         index[p]= MIN2(tot-1, index[p]);
1272                         jitoff[index[p]]= pos;
1273                 }
1274         }
1275         else {
1276                 double step, pos;
1277                 
1278                 step= (totpart <= 1)? 0.5: 1.0/(totpart-1);
1279                 pos= 1e-16f; /* tiny offset to avoid zero weight face */
1280                 i= 0;
1281
1282                 for(p=0; p<totpart; p++, pos+=step) {
1283                         while((i < tot) && (pos > sum[i+1]))
1284                                 i++;
1285
1286                         index[p]= MIN2(tot-1, i);
1287
1288                         /* avoid zero weight face */
1289                         if(p == totpart-1 && weight[index[p]] == 0.0f)
1290                                 index[p]= index[p-1];
1291
1292                         jitoff[index[p]]= pos;
1293                 }
1294         }
1295
1296         MEM_freeN(sum);
1297
1298         /* for hair, sort by origindex, allows optimizations in rendering */
1299         /* however with virtual parents the children need to be in random order */
1300         if(part->type == PART_HAIR && !(part->childtype==PART_CHILD_FACES && part->parents!=0.0)) {
1301                 if(from != PART_FROM_PARTICLE) {
1302                         COMPARE_ORIG_INDEX = NULL;
1303
1304                         if(from == PART_FROM_VERT) {
1305                                 if(dm->numVertData)
1306                                         COMPARE_ORIG_INDEX= dm->getVertDataArray(dm, CD_ORIGINDEX);
1307                         }
1308                         else {
1309                                 if(dm->numFaceData)
1310                                         COMPARE_ORIG_INDEX= dm->getFaceDataArray(dm, CD_ORIGINDEX);
1311                         }
1312
1313                         if(COMPARE_ORIG_INDEX) {
1314                                 qsort(index, totpart, sizeof(int), compare_orig_index);
1315                                 COMPARE_ORIG_INDEX = NULL;
1316                         }
1317                 }
1318         }
1319
1320         /* weights are no longer used except for FROM_PARTICLE, which needs them zeroed for indexing */
1321         if(from==PART_FROM_PARTICLE){
1322                 for(i=0; i<tot; i++)
1323                         weight[i]=0.0f;
1324         }
1325
1326         /* 4. */
1327         if(distr==PART_DISTR_JIT && ELEM(from,PART_FROM_FACE,PART_FROM_VOLUME)) {
1328                 jitlevel= part->userjit;
1329                 
1330                 if(jitlevel == 0) {
1331                         jitlevel= totpart/tot;
1332                         if(part->flag & PART_EDISTR) jitlevel*= 2;      /* looks better in general, not very scietific */
1333                         if(jitlevel<3) jitlevel= 3;
1334                 }
1335                 
1336                 jit= MEM_callocN((2+ jitlevel*2)*sizeof(float), "jit");
1337
1338                 /* for small amounts of particles we use regular jitter since it looks
1339                  * a bit better, for larger amounts we switch to hammersley sequence 
1340                  * because it is much faster */
1341                 if(jitlevel < 25)
1342                         init_mv_jit(jit, jitlevel, psys->seed, part->jitfac);
1343                 else
1344                         hammersley_create(jit, jitlevel+1, psys->seed, part->jitfac);
1345                 BLI_array_randomize(jit, 2*sizeof(float), jitlevel, psys->seed); /* for custom jit or even distribution */
1346         }
1347
1348         /* 5. */
1349         ctx->tree= tree;
1350         ctx->seams= seams;
1351         ctx->totseam= totseam;
1352         ctx->sim.psys= psys;
1353         ctx->index= index;
1354         ctx->jit= jit;
1355         ctx->jitlevel= jitlevel;
1356         ctx->jitoff= jitoff;
1357         ctx->weight= weight;
1358         ctx->maxweight= maxweight;
1359         ctx->from= (children)? PART_FROM_CHILD: from;
1360         ctx->cfrom= cfrom;
1361         ctx->distr= distr;
1362         ctx->dm= dm;
1363         ctx->tpars= tpars;
1364
1365         if(children) {
1366                 totpart= psys_render_simplify_distribution(ctx, totpart);
1367                 alloc_child_particles(psys, totpart);
1368         }
1369
1370         if(!children || psys->totchild < 10000)
1371                 totthread= 1;
1372         
1373         seed= 31415926 + ctx->sim.psys->seed;
1374         for(i=0; i<totthread; i++) {
1375                 threads[i].rng= rng_new(seed);
1376                 threads[i].tot= totthread;
1377         }
1378
1379         return 1;
1380 }
1381
1382 static void distribute_particles_on_dm(ParticleSimulationData *sim, int from)
1383 {
1384         DerivedMesh *finaldm = sim->psmd->dm;
1385         ListBase threads;
1386         ParticleThread *pthreads;
1387         ParticleThreadContext *ctx;
1388         int i, totthread;
1389
1390         pthreads= psys_threads_create(sim);
1391
1392         if(!psys_threads_init_distribution(pthreads, sim->scene, finaldm, from)) {
1393                 psys_threads_free(pthreads);
1394                 return;
1395         }
1396
1397         totthread= pthreads[0].tot;
1398         if(totthread > 1) {
1399                 BLI_init_threads(&threads, exec_distribution, totthread);
1400
1401                 for(i=0; i<totthread; i++)
1402                         BLI_insert_thread(&threads, &pthreads[i]);
1403
1404                 BLI_end_threads(&threads);
1405         }
1406         else
1407                 exec_distribution(&pthreads[0]);
1408
1409         psys_calc_dmcache(sim->ob, finaldm, sim->psys);
1410
1411         ctx= pthreads[0].ctx;
1412         if(ctx->dm != finaldm)
1413                 ctx->dm->release(ctx->dm);
1414
1415         psys_threads_free(pthreads);
1416 }
1417
1418 /* ready for future use, to emit particles without geometry */
1419 static void distribute_particles_on_shape(ParticleSimulationData *sim, int from)
1420 {
1421         ParticleSystem *psys = sim->psys;
1422         PARTICLE_P;
1423
1424         fprintf(stderr,"Shape emission not yet possible!\n");
1425
1426         LOOP_PARTICLES {
1427                 pa->fuv[0]=pa->fuv[1]=pa->fuv[2]=pa->fuv[3]= 0.0;
1428                 pa->foffset= 0.0f;
1429                 pa->num= -1;
1430         }
1431 }
1432 static void distribute_particles(ParticleSimulationData *sim, int from)
1433 {
1434         PARTICLE_PSMD;
1435         int distr_error=0;
1436
1437         if(psmd){
1438                 if(psmd->dm)
1439                         distribute_particles_on_dm(sim, from);
1440                 else
1441                         distr_error=1;
1442         }
1443         else
1444                 distribute_particles_on_shape(sim, from);
1445
1446         if(distr_error){
1447                 ParticleSystem *psys = sim->psys;
1448                 PARTICLE_P;
1449
1450                 fprintf(stderr,"Particle distribution error!\n");
1451
1452                 LOOP_PARTICLES {
1453                         pa->fuv[0]=pa->fuv[1]=pa->fuv[2]=pa->fuv[3]= 0.0;
1454                         pa->foffset= 0.0f;
1455                         pa->num= -1;
1456                 }
1457         }
1458 }
1459
1460 /* threaded child particle distribution and path caching */
1461 ParticleThread *psys_threads_create(ParticleSimulationData *sim)
1462 {
1463         ParticleThread *threads;
1464         ParticleThreadContext *ctx;
1465         int i, totthread;
1466
1467         if(sim->scene->r.mode & R_FIXED_THREADS)
1468                 totthread= sim->scene->r.threads;
1469         else
1470                 totthread= BLI_system_thread_count();
1471         
1472         threads= MEM_callocN(sizeof(ParticleThread)*totthread, "ParticleThread");
1473         ctx= MEM_callocN(sizeof(ParticleThreadContext), "ParticleThreadContext");
1474
1475         ctx->sim = *sim;
1476         ctx->dm= ctx->sim.psmd->dm;
1477         ctx->ma= give_current_material(sim->ob, sim->psys->part->omat);
1478
1479         memset(threads, 0, sizeof(ParticleThread)*totthread);
1480
1481         for(i=0; i<totthread; i++) {
1482                 threads[i].ctx= ctx;
1483                 threads[i].num= i;
1484                 threads[i].tot= totthread;
1485         }
1486
1487         return threads;
1488 }
1489
1490 void psys_threads_free(ParticleThread *threads)
1491 {
1492         ParticleThreadContext *ctx= threads[0].ctx;
1493         int i, totthread= threads[0].tot;
1494
1495         /* path caching */
1496         if(ctx->vg_length)
1497                 MEM_freeN(ctx->vg_length);
1498         if(ctx->vg_clump)
1499                 MEM_freeN(ctx->vg_clump);
1500         if(ctx->vg_kink)
1501                 MEM_freeN(ctx->vg_kink);
1502         if(ctx->vg_rough1)
1503                 MEM_freeN(ctx->vg_rough1);
1504         if(ctx->vg_rough2)
1505                 MEM_freeN(ctx->vg_rough2);
1506         if(ctx->vg_roughe)
1507                 MEM_freeN(ctx->vg_roughe);
1508
1509         if(ctx->sim.psys->lattice){
1510                 end_latt_deform(ctx->sim.psys->lattice);
1511                 ctx->sim.psys->lattice= NULL;
1512         }
1513
1514         /* distribution */
1515         if(ctx->jit) MEM_freeN(ctx->jit);
1516         if(ctx->jitoff) MEM_freeN(ctx->jitoff);
1517         if(ctx->weight) MEM_freeN(ctx->weight);
1518         if(ctx->index) MEM_freeN(ctx->index);
1519         if(ctx->skip) MEM_freeN(ctx->skip);
1520         if(ctx->seams) MEM_freeN(ctx->seams);
1521         //if(ctx->vertpart) MEM_freeN(ctx->vertpart);
1522         BLI_kdtree_free(ctx->tree);
1523
1524         /* threads */
1525         for(i=0; i<totthread; i++) {
1526                 if(threads[i].rng)
1527                         rng_free(threads[i].rng);
1528                 if(threads[i].rng_path)
1529                         rng_free(threads[i].rng_path);
1530         }
1531
1532         MEM_freeN(ctx);
1533         MEM_freeN(threads);
1534 }
1535
1536 /* set particle parameters that don't change during particle's life */
1537 void initialize_particle(ParticleSimulationData *sim, ParticleData *pa, int p)
1538 {
1539         ParticleSettings *part = sim->psys->part;
1540         ParticleTexture ptex;
1541         Material *ma=0;
1542         //IpoCurve *icu=0; // XXX old animation system
1543         int totpart;
1544
1545         totpart=sim->psys->totpart;
1546
1547         ptex.life=ptex.size=ptex.exist=ptex.length=1.0;
1548         ptex.time=(float)p/(float)totpart;
1549
1550         BLI_srandom(sim->psys->seed + p + 125);
1551
1552         if(part->from!=PART_FROM_PARTICLE && part->type!=PART_FLUID){
1553                 ma=give_current_material(sim->ob,part->omat);
1554
1555                 /* TODO: needs some work to make most blendtypes generally usefull */
1556                 psys_get_texture(sim,ma,pa,&ptex,MAP_PA_INIT);
1557         }
1558         
1559         pa->lifetime= part->lifetime*ptex.life;
1560
1561         if(part->type==PART_HAIR)
1562                 pa->time= 0.0f;
1563         //else if(part->type==PART_REACTOR && (part->flag&PART_REACT_STA_END)==0)
1564         //      pa->time= 300000.0f;    /* max frame */
1565         else{
1566                 //icu=find_ipocurve(psys->part->ipo,PART_EMIT_TIME);
1567                 //if(icu){
1568                 //      calc_icu(icu,100*ptex.time);
1569                 //      ptex.time=icu->curval;
1570                 //}
1571
1572                 pa->time= part->sta + (part->end - part->sta)*ptex.time;
1573         }
1574
1575
1576         if(part->type==PART_HAIR){
1577                 pa->lifetime=100.0f;
1578         }
1579         else{
1580 #if 0 // XXX old animation system
1581                 icu=find_ipocurve(psys->part->ipo,PART_EMIT_LIFE);
1582                 if(icu){
1583                         calc_icu(icu,100*ptex.time);
1584                         pa->lifetime*=icu->curval;
1585                 }
1586 #endif // XXX old animation system
1587
1588                 if(part->randlife!=0.0)
1589                         pa->lifetime*= 1.0f - part->randlife * BLI_frand();
1590         }
1591
1592         pa->dietime= pa->time+pa->lifetime;
1593
1594         if(part->type!=PART_HAIR && part->distr!=PART_DISTR_GRID && part->from != PART_FROM_VERT){
1595                 if(ptex.exist < BLI_frand())
1596                         pa->flag |= PARS_UNEXIST;
1597                 else
1598                         pa->flag &= ~PARS_UNEXIST;
1599         }
1600
1601         pa->hair_index=0;
1602         /* we can't reset to -1 anymore since we've figured out correct index in distribute_particles */
1603         /* usage other than straight after distribute has to handle this index by itself - jahka*/
1604         //pa->num_dmcache = DMCACHE_NOTFOUND; /* assume we dont have a derived mesh face */
1605 }
1606 static void initialize_all_particles(ParticleSimulationData *sim)
1607 {
1608         //IpoCurve *icu=0; // XXX old animation system
1609         ParticleSystem *psys = sim->psys;
1610         PARTICLE_P;
1611
1612         LOOP_PARTICLES
1613                 initialize_particle(sim, pa, p);
1614         
1615         if(psys->part->type != PART_FLUID) {
1616 #if 0 // XXX old animation system
1617                 icu=find_ipocurve(psys->part->ipo,PART_EMIT_FREQ);
1618                 if(icu){
1619                         float time=psys->part->sta, end=psys->part->end;
1620                         float v1, v2, a=0.0f, t1,t2, d;
1621
1622                         p=0;
1623                         pa=psys->particles;
1624
1625
1626                         calc_icu(icu,time);
1627                         v1=icu->curval;
1628                         if(v1<0.0f) v1=0.0f;
1629
1630                         calc_icu(icu,time+1.0f);
1631                         v2=icu->curval;
1632                         if(v2<0.0f) v2=0.0f;
1633
1634                         for(p=0, pa=psys->particles; p<totpart && time<end; p++, pa++){
1635                                 while(a+0.5f*(v1+v2) < (float)(p+1) && time<end){
1636                                         a+=0.5f*(v1+v2);
1637                                         v1=v2;
1638                                         time++;
1639                                         calc_icu(icu,time+1.0f);
1640                                         v2=icu->curval;
1641                                 }
1642                                 if(time<end){
1643                                         if(v1==v2){
1644                                                 pa->time=time+((float)(p+1)-a)/v1;
1645                                         }
1646                                         else{
1647                                                 d=(float)sqrt(v1*v1-2.0f*(v2-v1)*(a-(float)(p+1)));
1648                                                 t1=(-v1+d)/(v2-v1);
1649                                                 t2=(-v1-d)/(v2-v1);
1650
1651                                                 /* the root between 0-1 is the correct one */
1652                                                 if(t1>0.0f && t1<=1.0f)
1653                                                         pa->time=time+t1;
1654                                                 else
1655                                                         pa->time=time+t2;
1656                                         }
1657                                 }
1658
1659                                 pa->dietime = pa->time+pa->lifetime;
1660                                 pa->flag &= ~PARS_UNEXIST;
1661                         }
1662                         for(; p<totpart; p++, pa++){
1663                                 pa->flag |= PARS_UNEXIST;
1664                         }
1665                 }
1666 #endif // XXX old animation system
1667         }
1668 }
1669 /* sets particle to the emitter surface with initial velocity & rotation */
1670 void reset_particle(ParticleSimulationData *sim, ParticleData *pa, float dtime, float cfra)
1671 {
1672         Object *ob = sim->ob;
1673         ParticleSystem *psys = sim->psys;
1674         ParticleSettings *part;
1675         ParticleTexture ptex;
1676         ParticleKey state;
1677         //IpoCurve *icu=0; // XXX old animation system
1678         float fac, phasefac, nor[3]={0,0,0},loc[3],vel[3]={0.0,0.0,0.0},rot[4],q2[4];
1679         float r_vel[3],r_ave[3],r_rot[4],vec[3],p_vel[3]={0.0,0.0,0.0};
1680         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};
1681         float q_phase[4], r_phase;
1682         int p = pa - psys->particles;
1683         part=psys->part;
1684
1685         ptex.ivel=1.0;
1686
1687         /* we need to get every random even if they're not used so that they don't effect eachother */
1688         r_vel[0] = 2.0f * (PSYS_FRAND(p + 10) - 0.5f);
1689         r_vel[1] = 2.0f * (PSYS_FRAND(p + 11) - 0.5f);
1690         r_vel[2] = 2.0f * (PSYS_FRAND(p + 12) - 0.5f);
1691
1692         r_ave[0] = 2.0f * (PSYS_FRAND(p + 13) - 0.5f);
1693         r_ave[1] = 2.0f * (PSYS_FRAND(p + 14) - 0.5f);
1694         r_ave[2] = 2.0f * (PSYS_FRAND(p + 15) - 0.5f);
1695
1696         r_rot[0] = 2.0f * (PSYS_FRAND(p + 16) - 0.5f);
1697         r_rot[1] = 2.0f * (PSYS_FRAND(p + 17) - 0.5f);
1698         r_rot[2] = 2.0f * (PSYS_FRAND(p + 18) - 0.5f);
1699         r_rot[3] = 2.0f * (PSYS_FRAND(p + 19) - 0.5f);
1700         normalize_qt(r_rot);
1701
1702         r_phase = PSYS_FRAND(p + 20);
1703         
1704         if(part->from==PART_FROM_PARTICLE){
1705                 ParticleSimulationData tsim = {sim->scene, psys->target_ob ? psys->target_ob : ob, NULL, NULL};
1706                 float speed;
1707
1708                 tsim.psys = BLI_findlink(&tsim.ob->particlesystem, sim->psys->target_psys-1);
1709
1710                 state.time = pa->time;
1711                 if(pa->num == -1)
1712                         memset(&state, 0, sizeof(state));
1713                 else
1714                         psys_get_particle_state(&tsim, pa->num, &state, 1);
1715                 psys_get_from_key(&state, loc, nor, rot, 0);
1716
1717                 mul_qt_v3(rot, vtan);
1718                 mul_qt_v3(rot, utan);
1719
1720                 VECCOPY(p_vel, state.vel);
1721                 speed=normalize_v3(p_vel);
1722                 mul_v3_fl(p_vel, dot_v3v3(r_vel, p_vel));
1723                 VECSUB(p_vel, r_vel, p_vel);
1724                 normalize_v3(p_vel);
1725                 mul_v3_fl(p_vel, speed);
1726
1727                 VECCOPY(pa->fuv, loc); /* abusing pa->fuv (not used for "from particle") for storing emit location */
1728         }
1729         else{
1730                 /* get precise emitter matrix if particle is born */
1731                 if(part->type!=PART_HAIR && pa->time < cfra && pa->time >= sim->psys->cfra) {
1732                         /* we have to force RECALC_ANIM here since where_is_objec_time only does drivers */
1733                         BKE_animsys_evaluate_animdata(&sim->ob->id, sim->ob->adt, pa->time, ADT_RECALC_ANIM);
1734                         where_is_object_time(sim->scene, sim->ob, pa->time);
1735                 }
1736
1737                 /* get birth location from object               */
1738                 if(part->tanfac!=0.0)
1739                         psys_particle_on_emitter(sim->psmd, part->from,pa->num, pa->num_dmcache, pa->fuv,pa->foffset,loc,nor,utan,vtan,0,0);
1740                 else
1741                         psys_particle_on_emitter(sim->psmd, part->from,pa->num, pa->num_dmcache, pa->fuv,pa->foffset,loc,nor,0,0,0,0);
1742                 
1743                 /* get possible textural influence */
1744                 psys_get_texture(sim, give_current_material(sim->ob,part->omat), pa, &ptex, MAP_PA_IVEL);
1745
1746                 //if(vg_vel && pa->num != -1)
1747                 //      ptex.ivel*=psys_particle_value_from_verts(sim->psmd->dm,part->from,pa,vg_vel);
1748
1749                 /* particles live in global space so    */
1750                 /* let's convert:                                               */
1751                 /* -location                                                    */
1752                 mul_m4_v3(ob->obmat,loc);
1753                 
1754                 /* -normal                                                              */
1755                 mul_mat3_m4_v3(ob->obmat,nor);
1756                 normalize_v3(nor);
1757
1758                 /* -tangent                                                             */
1759                 if(part->tanfac!=0.0){
1760                         //float phase=vg_rot?2.0f*(psys_particle_value_from_verts(sim->psmd->dm,part->from,pa,vg_rot)-0.5f):0.0f;
1761                         float phase=0.0f;
1762                         mul_v3_fl(vtan,-(float)cos(M_PI*(part->tanphase+phase)));
1763                         fac=-(float)sin(M_PI*(part->tanphase+phase));
1764                         VECADDFAC(vtan,vtan,utan,fac);
1765
1766                         mul_mat3_m4_v3(ob->obmat,vtan);
1767
1768                         VECCOPY(utan,nor);
1769                         mul_v3_fl(utan,dot_v3v3(vtan,nor));
1770                         VECSUB(vtan,vtan,utan);
1771                         
1772                         normalize_v3(vtan);
1773                 }
1774                 
1775
1776                 /* -velocity                                                    */
1777                 if(part->randfac!=0.0){
1778                         mul_mat3_m4_v3(ob->obmat,r_vel);
1779                         normalize_v3(r_vel);
1780                 }
1781
1782                 /* -angular velocity                                    */
1783                 if(part->avemode==PART_AVE_RAND){
1784                         mul_mat3_m4_v3(ob->obmat,r_ave);
1785                         normalize_v3(r_ave);
1786                 }
1787                 
1788                 /* -rotation                                                    */
1789                 if(part->randrotfac != 0.0f){
1790                         mat4_to_quat(rot,ob->obmat);
1791                         mul_qt_qtqt(r_rot,r_rot,rot);
1792                 }
1793         }
1794
1795         if(part->phystype==PART_PHYS_BOIDS && pa->boid) {
1796                 BoidParticle *bpa = pa->boid;
1797                 float dvec[3], q[4], mat[3][3];
1798
1799                 VECCOPY(pa->state.co,loc);
1800
1801                 /* boids don't get any initial velocity  */
1802                 pa->state.vel[0]=pa->state.vel[1]=pa->state.vel[2]=0.0f;
1803
1804                 /* boids store direction in ave */
1805                 if(fabs(nor[2])==1.0f) {
1806                         sub_v3_v3v3(pa->state.ave, loc, ob->obmat[3]);
1807                         normalize_v3(pa->state.ave);
1808                 }
1809                 else {
1810                         VECCOPY(pa->state.ave, nor);
1811                 }
1812                 /* and gravity in r_ve */
1813                 bpa->gravity[0] = bpa->gravity[1] = 0.0f;
1814                 bpa->gravity[2] = -1.0f;
1815                 if((sim->scene->physics_settings.flag & PHYS_GLOBAL_GRAVITY)
1816                         && sim->scene->physics_settings.gravity[2]!=0.0f)
1817                         bpa->gravity[2] = sim->scene->physics_settings.gravity[2];
1818
1819                 /* calculate rotation matrix */
1820                 project_v3_v3v3(dvec, r_vel, pa->state.ave);
1821                 sub_v3_v3v3(mat[0], pa->state.ave, dvec);
1822                 normalize_v3(mat[0]);
1823                 VECCOPY(mat[2], r_vel);
1824                 mul_v3_fl(mat[2], -1.0f);
1825                 normalize_v3(mat[2]);
1826                 cross_v3_v3v3(mat[1], mat[2], mat[0]);
1827                 
1828                 /* apply rotation */
1829                 mat3_to_quat_is_ok( q,mat);
1830                 copy_qt_qt(pa->state.rot, q);
1831
1832                 bpa->data.health = part->boids->health;
1833                 bpa->data.mode = eBoidMode_InAir;
1834                 bpa->data.state_id = ((BoidState*)part->boids->states.first)->id;
1835                 bpa->data.acc[0]=bpa->data.acc[1]=bpa->data.acc[2]=0.0f;
1836         }
1837         else {
1838                 /* conversion done so now we apply new: */
1839                 /* -velocity from:                                              */
1840
1841                 /*              *reactions                                              */
1842                 if(dtime>0.0f){
1843                         VECSUB(vel,pa->state.vel,pa->prev_state.vel);
1844                 }
1845
1846                 /*              *emitter velocity                               */
1847                 if(dtime!=0.0 && part->obfac!=0.0){
1848                         VECSUB(vel,loc,pa->state.co);
1849                         mul_v3_fl(vel,part->obfac/dtime);
1850                 }
1851                 
1852                 /*              *emitter normal                                 */
1853                 if(part->normfac!=0.0)
1854                         VECADDFAC(vel,vel,nor,part->normfac);
1855                 
1856                 /*              *emitter tangent                                */
1857                 if(sim->psmd && part->tanfac!=0.0)
1858                         VECADDFAC(vel,vel,vtan,part->tanfac);
1859                         //VECADDFAC(vel,vel,vtan,part->tanfac*(vg_tan?psys_particle_value_from_verts(sim->psmd->dm,part->from,pa,vg_tan):1.0f));
1860
1861                 /*              *emitter object orientation             */
1862                 if(part->ob_vel[0]!=0.0) {
1863                         VECCOPY(vec, ob->obmat[0]);
1864                         normalize_v3(vec);
1865                         VECADDFAC(vel, vel, vec, part->ob_vel[0]);
1866                 }
1867                 if(part->ob_vel[1]!=0.0) {
1868                         VECCOPY(vec, ob->obmat[1]);
1869                         normalize_v3(vec);
1870                         VECADDFAC(vel, vel, vec, part->ob_vel[1]);
1871                 }
1872                 if(part->ob_vel[2]!=0.0) {
1873                         VECCOPY(vec, ob->obmat[2]);
1874                         normalize_v3(vec);
1875                         VECADDFAC(vel, vel, vec, part->ob_vel[2]);
1876                 }
1877
1878                 /*              *texture                                                */
1879                 /* TODO */
1880
1881                 /*              *random                                                 */
1882                 if(part->randfac!=0.0)
1883                         VECADDFAC(vel,vel,r_vel,part->randfac);
1884
1885                 /*              *particle                                               */
1886                 if(part->partfac!=0.0)
1887                         VECADDFAC(vel,vel,p_vel,part->partfac);
1888
1889                 //icu=find_ipocurve(psys->part->ipo,PART_EMIT_VEL);
1890                 //if(icu){
1891                 //      calc_icu(icu,100*((pa->time-part->sta)/(part->end-part->sta)));
1892                 //      ptex.ivel*=icu->curval;
1893                 //}
1894
1895                 mul_v3_fl(vel,ptex.ivel);
1896                 
1897                 VECCOPY(pa->state.vel,vel);
1898
1899                 /* -location from emitter                               */
1900                 VECCOPY(pa->state.co,loc);
1901
1902                 /* -rotation                                                    */
1903                 pa->state.rot[0]=1.0;
1904                 pa->state.rot[1]=pa->state.rot[2]=pa->state.rot[3]=0.0;
1905
1906                 if(part->rotmode){
1907                         /* create vector into which rotation is aligned */
1908                         switch(part->rotmode){
1909                                 case PART_ROT_NOR:
1910                                         copy_v3_v3(rot_vec, nor);
1911                                         break;
1912                                 case PART_ROT_VEL:
1913                                         copy_v3_v3(rot_vec, vel);
1914                                         break;
1915                                 case PART_ROT_GLOB_X:
1916                                 case PART_ROT_GLOB_Y:
1917                                 case PART_ROT_GLOB_Z:
1918                                         rot_vec[part->rotmode - PART_ROT_GLOB_X] = 1.0f;
1919                                         break;
1920                                 case PART_ROT_OB_X:
1921                                 case PART_ROT_OB_Y:
1922                                 case PART_ROT_OB_Z:
1923                                         copy_v3_v3(rot_vec, ob->obmat[part->rotmode - PART_ROT_OB_X]);
1924                                         break;
1925                         }
1926                         
1927                         /* create rotation quat */
1928                         negate_v3(rot_vec);
1929                         vec_to_quat( q2,rot_vec, OB_POSX, OB_POSZ);
1930
1931                         /* randomize rotation quat */
1932                         if(part->randrotfac!=0.0f)
1933                                 interp_qt_qtqt(rot, q2, r_rot, part->randrotfac);
1934                         else
1935                                 copy_qt_qt(rot,q2);
1936
1937                         /* rotation phase */
1938                         phasefac = part->phasefac;
1939                         if(part->randphasefac != 0.0f)
1940                                 phasefac += part->randphasefac * r_phase;
1941                         axis_angle_to_quat( q_phase,x_vec, phasefac*(float)M_PI);
1942
1943                         /* combine base rotation & phase */
1944                         mul_qt_qtqt(pa->state.rot, rot, q_phase);
1945                 }
1946
1947                 /* -angular velocity                                    */
1948
1949                 pa->state.ave[0] = pa->state.ave[1] = pa->state.ave[2] = 0.0;
1950
1951                 if(part->avemode){
1952                         switch(part->avemode){
1953                                 case PART_AVE_SPIN:
1954                                         VECCOPY(pa->state.ave,vel);
1955                                         break;
1956                                 case PART_AVE_RAND:
1957                                         VECCOPY(pa->state.ave,r_ave);
1958                                         break;
1959                         }
1960                         normalize_v3(pa->state.ave);
1961                         mul_v3_fl(pa->state.ave,part->avefac);
1962
1963                         //icu=find_ipocurve(psys->part->ipo,PART_EMIT_AVE);
1964                         //if(icu){
1965                         //      calc_icu(icu,100*((pa->time-part->sta)/(part->end-part->sta)));
1966                         //      mul_v3_fl(pa->state.ave,icu->curval);
1967                         //}
1968                 }
1969         }
1970
1971         pa->dietime = pa->time + pa->lifetime;
1972
1973         if(pa->time > cfra)
1974                 pa->alive = PARS_UNBORN;
1975         else if(pa->dietime <= cfra)
1976                 pa->alive = PARS_DEAD;
1977         else
1978                 pa->alive = PARS_ALIVE;
1979
1980         pa->state.time = cfra;
1981 }
1982 static void reset_all_particles(ParticleSimulationData *sim, float dtime, float cfra, int from)
1983 {
1984         ParticleData *pa;
1985         int p, totpart=sim->psys->totpart;
1986         //float *vg_vel=psys_cache_vgroup(sim->psmd->dm,sim->psys,PSYS_VG_VEL);
1987         //float *vg_tan=psys_cache_vgroup(sim->psmd->dm,sim->psys,PSYS_VG_TAN);
1988         //float *vg_rot=psys_cache_vgroup(sim->psmd->dm,sim->psys,PSYS_VG_ROT);
1989         
1990         for(p=from, pa=sim->psys->particles+from; p<totpart; p++, pa++)
1991                 reset_particle(sim, pa, dtime, cfra);
1992
1993         //if(vg_vel)
1994         //      MEM_freeN(vg_vel);
1995 }
1996 /************************************************/
1997 /*                      Particle targets                                        */
1998 /************************************************/
1999 ParticleSystem *psys_get_target_system(Object *ob, ParticleTarget *pt)
2000 {
2001         ParticleSystem *psys = NULL;
2002
2003         if(pt->ob == NULL || pt->ob == ob)
2004                 psys = BLI_findlink(&ob->particlesystem, pt->psys-1);
2005         else
2006                 psys = BLI_findlink(&pt->ob->particlesystem, pt->psys-1);
2007
2008         if(psys)
2009                 pt->flag |= PTARGET_VALID;
2010         else
2011                 pt->flag &= ~PTARGET_VALID;
2012
2013         return psys;
2014 }
2015 /************************************************/
2016 /*                      Keyed particles                                         */
2017 /************************************************/
2018 /* Counts valid keyed targets */
2019 void psys_count_keyed_targets(ParticleSimulationData *sim)
2020 {
2021         ParticleSystem *psys = sim->psys, *kpsys;
2022         ParticleTarget *pt = psys->targets.first;
2023         int keys_valid = 1;
2024         psys->totkeyed = 0;
2025
2026         for(; pt; pt=pt->next) {
2027                 kpsys = psys_get_target_system(sim->ob, pt);
2028
2029                 if(kpsys && kpsys->totpart) {
2030                         psys->totkeyed += keys_valid;
2031                         if(psys->flag & PSYS_KEYED_TIMING && pt->duration != 0.0f)
2032                                 psys->totkeyed += 1;
2033                 }
2034                 else {
2035                         keys_valid = 0;
2036                 }
2037         }
2038
2039         psys->totkeyed *= psys->flag & PSYS_KEYED_TIMING ? 1 : psys->part->keyed_loops;
2040 }
2041
2042 static void set_keyed_keys(ParticleSimulationData *sim)
2043 {
2044         ParticleSystem *psys = sim->psys;
2045         ParticleSimulationData ksim = {sim->scene, NULL, NULL, NULL};
2046         ParticleTarget *pt;
2047         PARTICLE_P;
2048         ParticleKey *key;
2049         int totpart = psys->totpart, k, totkeys = psys->totkeyed;
2050
2051         /* no proper targets so let's clear and bail out */
2052         if(psys->totkeyed==0) {
2053                 free_keyed_keys(psys);
2054                 psys->flag &= ~PSYS_KEYED;
2055                 return;
2056         }
2057
2058         if(totpart && psys->particles->totkey != totkeys) {
2059                 free_keyed_keys(psys);
2060                 
2061                 key = MEM_callocN(totpart*totkeys*sizeof(ParticleKey), "Keyed keys");
2062                 
2063                 LOOP_PARTICLES {
2064                         pa->keys = key;
2065                         pa->totkey = totkeys;
2066                         key += totkeys;
2067                 }
2068         }
2069         
2070         psys->flag &= ~PSYS_KEYED;
2071
2072
2073         pt = psys->targets.first;
2074         for(k=0; k<totkeys; k++) {
2075                 ksim.ob = pt->ob ? pt->ob : sim->ob;
2076                 ksim.psys = BLI_findlink(&ksim.ob->particlesystem, pt->psys - 1);
2077
2078                 LOOP_PARTICLES {
2079                         key = pa->keys + k;
2080                         key->time = -1.0; /* use current time */
2081
2082                         psys_get_particle_state(&ksim, p%ksim.psys->totpart, key, 1);
2083
2084                         if(psys->flag & PSYS_KEYED_TIMING){
2085                                 key->time = pa->time + pt->time;
2086                                 if(pt->duration != 0.0f && k+1 < totkeys) {
2087                                         copy_particle_key(key+1, key, 1);
2088                                         (key+1)->time = pa->time + pt->time + pt->duration;
2089                                 }
2090                         }
2091                         else if(totkeys > 1)
2092                                 key->time = pa->time + (float)k / (float)(totkeys - 1) * pa->lifetime;
2093                         else
2094                                 key->time = pa->time;
2095                 }
2096
2097                 if(psys->flag & PSYS_KEYED_TIMING && pt->duration!=0.0f)
2098                         k++;
2099
2100                 pt = (pt->next && pt->next->flag & PTARGET_VALID)? pt->next : psys->targets.first;
2101         }
2102
2103         psys->flag |= PSYS_KEYED;
2104 }
2105 /************************************************/
2106 /*                      Reactors                                                        */
2107 /************************************************/
2108 //static void push_reaction(ParticleSimulationData *sim, int pa_num, int event, ParticleKey *state)
2109 //{
2110 //      Object *rob;
2111 //      ParticleSystem *rpsys;
2112 //      ParticleSettings *rpart;
2113 //      ParticleData *pa;
2114 //      ListBase *lb=&sim->psys->effectors;
2115 //      ParticleEffectorCache *ec;
2116 //      ParticleReactEvent *re;
2117 //
2118 //      if(lb->first) for(ec = lb->first; ec; ec= ec->next){
2119 //              if(ec->type & PSYS_EC_REACTOR){
2120 //                      /* all validity checks already done in add_to_effectors */
2121 //                      rob=ec->ob;
2122 //                      rpsys=BLI_findlink(&rob->particlesystem,ec->psys_nbr);
2123 //                      rpart=rpsys->part;
2124 //                      if(rpsys->part->reactevent==event){
2125 //                              pa=sim->psys->particles+pa_num;
2126 //                              re= MEM_callocN(sizeof(ParticleReactEvent), "react event");
2127 //                              re->event=event;
2128 //                              re->pa_num = pa_num;
2129 //                              re->ob = sim->ob;
2130 //                              re->psys = sim->psys;
2131 //                              re->size = pa->size;
2132 //                              copy_particle_key(&re->state,state,1);
2133 //
2134 //                              switch(event){
2135 //                                      case PART_EVENT_DEATH:
2136 //                                              re->time=pa->dietime;
2137 //                                              break;
2138 //                                      case PART_EVENT_COLLIDE:
2139 //                                              re->time=state->time;
2140 //                                              break;
2141 //                                      case PART_EVENT_NEAR:
2142 //                                              re->time=state->time;
2143 //                                              break;
2144 //                              }
2145 //
2146 //                              BLI_addtail(&rpsys->reactevents, re);
2147 //                      }
2148 //              }
2149 //      }
2150 //}
2151 //static void react_to_events(ParticleSystem *psys, int pa_num)
2152 //{
2153 //      ParticleSettings *part=psys->part;
2154 //      ParticleData *pa=psys->particles+pa_num;
2155 //      ParticleReactEvent *re=psys->reactevents.first;
2156 //      int birth=0;
2157 //      float dist=0.0f;
2158 //
2159 //      for(re=psys->reactevents.first; re; re=re->next){
2160 //              birth=0;
2161 //              if(part->from==PART_FROM_PARTICLE){
2162 //                      if(pa->num==re->pa_num && pa->alive==PARS_UNBORN){
2163 //                              if(re->event==PART_EVENT_NEAR){
2164 //                                      ParticleData *tpa = re->psys->particles+re->pa_num;
2165 //                                      float pa_time=tpa->time + pa->foffset*tpa->lifetime;
2166 //                                      if(re->time >= pa_time){
2167 //                                              pa->time=pa_time;
2168 //                                              pa->dietime=pa->time+pa->lifetime;
2169 //                                      }
2170 //                              }
2171 //                              else{
2172 //                                      pa->time=re->time;
2173 //                                      pa->dietime=pa->time+pa->lifetime;
2174 //                              }
2175 //                      }
2176 //              }
2177 //              else{
2178 //                      dist=len_v3v3(pa->state.co, re->state.co);
2179 //                      if(dist <= re->size){
2180 //                              if(pa->alive==PARS_UNBORN){
2181 //                                      pa->time=re->time;
2182 //                                      pa->dietime=pa->time+pa->lifetime;
2183 //                                      birth=1;
2184 //                              }
2185 //                              if(birth || part->flag&PART_REACT_MULTIPLE){
2186 //                                      float vec[3];
2187 //                                      VECSUB(vec,pa->state.co, re->state.co);
2188 //                                      if(birth==0)
2189 //                                              mul_v3_fl(vec,(float)pow(1.0f-dist/re->size,part->reactshape));
2190 //                                      VECADDFAC(pa->state.vel,pa->state.vel,vec,part->reactfac);
2191 //                                      VECADDFAC(pa->state.vel,pa->state.vel,re->state.vel,part->partfac);
2192 //                              }
2193 //                              if(birth)
2194 //                                      mul_v3_fl(pa->state.vel,(float)pow(1.0f-dist/re->size,part->reactshape));
2195 //                      }
2196 //              }
2197 //      }
2198 //}
2199 //void psys_get_reactor_target(ParticleSimulationData *sim, Object **target_ob, ParticleSystem **target_psys)
2200 //{
2201 //      Object *tob;
2202 //
2203 //      tob = sim->psys->target_ob ? sim->psys->target_ob : sim->ob;
2204 //      
2205 //      *target_psys = BLI_findlink(&tob->particlesystem, sim->psys->target_psys-1);
2206 //      if(*target_psys)
2207 //              *target_ob=tob;
2208 //      else
2209 //              *target_ob=0;
2210 //}
2211 /************************************************/
2212 /*                      Point Cache                                                     */
2213 /************************************************/
2214 void psys_make_temp_pointcache(Object *ob, ParticleSystem *psys)
2215 {
2216         PointCache *cache = psys->pointcache;
2217         PTCacheID pid;
2218
2219         if((cache->flag & PTCACHE_DISK_CACHE)==0 || cache->mem_cache.first)
2220                 return;
2221
2222         BKE_ptcache_id_from_particles(&pid, ob, psys);
2223
2224         BKE_ptcache_disk_to_mem(&pid);
2225 }
2226 static void psys_clear_temp_pointcache(ParticleSystem *psys)
2227 {
2228         if((psys->pointcache->flag & PTCACHE_DISK_CACHE)==0)
2229                 return;
2230
2231         BKE_ptcache_free_mem(&psys->pointcache->mem_cache);
2232 }
2233 void psys_get_pointcache_start_end(Scene *scene, ParticleSystem *psys, int *sfra, int *efra)
2234 {
2235         ParticleSettings *part = psys->part;
2236
2237         *sfra = MAX2(1, (int)part->sta);
2238         *efra = MIN2((int)(part->end + part->lifetime + 1.0), scene->r.efra);
2239 }
2240
2241 /************************************************/
2242 /*                      Effectors                                                       */
2243 /************************************************/
2244 void psys_update_particle_tree(ParticleSystem *psys, float cfra)
2245 {
2246         if(psys) {
2247                 PARTICLE_P;
2248
2249                 if(!psys->tree || psys->tree_frame != cfra) {
2250                         
2251                         BLI_kdtree_free(psys->tree);
2252
2253                         psys->tree = BLI_kdtree_new(psys->totpart);
2254                         
2255                         LOOP_SHOWN_PARTICLES {
2256                                 if(pa->alive == PARS_ALIVE) {
2257                                         if(pa->state.time == cfra)
2258                                                 BLI_kdtree_insert(psys->tree, p, pa->prev_state.co, NULL);
2259                                         else
2260                                                 BLI_kdtree_insert(psys->tree, p, pa->state.co, NULL);
2261                                 }
2262                         }
2263                         BLI_kdtree_balance(psys->tree);
2264
2265                         psys->tree_frame = psys->cfra;
2266                 }
2267         }
2268 }
2269
2270 static void psys_update_effectors(ParticleSimulationData *sim)
2271 {
2272         pdEndEffectors(&sim->psys->effectors);
2273         sim->psys->effectors = pdInitEffectors(sim->scene, sim->ob, sim->psys, sim->psys->part->effector_weights);
2274         precalc_guides(sim, sim->psys->effectors);
2275 }
2276
2277 /************************************************/
2278 /*                      Newtonian physics                                       */
2279 /************************************************/
2280 /* gathers all forces that effect particles and calculates a new state for the particle */
2281 static void apply_particle_forces(ParticleSimulationData *sim, int p, float dfra, float cfra)
2282 {
2283         ParticleSettings *part = sim->psys->part;
2284         ParticleData *pa = sim->psys->particles + p;
2285         EffectedPoint epoint;
2286         ParticleKey states[5], tkey;
2287         float timestep = psys_get_timestep(sim);
2288         float force[3],impulse[3],dx[4][3],dv[4][3],oldpos[3];
2289         float dtime=dfra*timestep, time, pa_mass=part->mass, fac, fra=sim->psys->cfra;
2290         int i, steps=1;
2291         
2292         /* maintain angular velocity */
2293         VECCOPY(pa->state.ave,pa->prev_state.ave);
2294         VECCOPY(oldpos,pa->state.co);
2295
2296         if(part->flag & PART_SIZEMASS)
2297                 pa_mass*=pa->size;
2298
2299         switch(part->integrator){
2300                 case PART_INT_EULER:
2301                         steps=1;
2302                         break;
2303                 case PART_INT_MIDPOINT:
2304                         steps=2;
2305                         break;
2306                 case PART_INT_RK4:
2307                         steps=4;
2308                         break;
2309                 case PART_INT_VERLET:
2310                         steps=1;
2311                         break;
2312         }
2313
2314         copy_particle_key(states,&pa->state,1);
2315
2316         for(i=0; i<steps; i++){
2317                 force[0]=force[1]=force[2]=0.0;
2318                 impulse[0]=impulse[1]=impulse[2]=0.0;
2319                 /* add effectors */
2320                 pd_point_from_particle(sim, pa, states+i, &epoint);
2321                 if(part->type != PART_HAIR || part->effector_weights->flag & EFF_WEIGHT_DO_HAIR)
2322                         pdDoEffectors(sim->psys->effectors, sim->colliders, part->effector_weights, &epoint, force, impulse);
2323
2324                 /* calculate air-particle interaction */
2325                 if(part->dragfac!=0.0f){
2326                         fac=-part->dragfac*pa->size*pa->size*len_v3(states[i].vel);
2327                         VECADDFAC(force,force,states[i].vel,fac);
2328                 }
2329
2330                 /* brownian force */
2331                 if(part->brownfac!=0.0){
2332                         force[0]+=(BLI_frand()-0.5f)*part->brownfac;
2333                         force[1]+=(BLI_frand()-0.5f)*part->brownfac;
2334                         force[2]+=(BLI_frand()-0.5f)*part->brownfac;
2335                 }
2336
2337                 /* force to acceleration*/
2338                 mul_v3_fl(force,1.0f/pa_mass);
2339
2340                 /* add global acceleration (gravitation) */
2341                 if(psys_uses_gravity(sim)
2342                         /* normal gravity is too strong for hair so it's disabled by default */
2343                         && (part->type != PART_HAIR || part->effector_weights->flag & EFF_WEIGHT_DO_HAIR)) {
2344                         float gravity[3];
2345                         VECCOPY(gravity, sim->scene->physics_settings.gravity);
2346                         mul_v3_fl(gravity, part->effector_weights->global_gravity);
2347                         VECADD(force,force,gravity);
2348                 }
2349                 
2350                 /* calculate next state */
2351                 VECADD(states[i].vel,states[i].vel,impulse);
2352
2353                 switch(part->integrator){
2354                         case PART_INT_EULER:
2355                                 VECADDFAC(pa->state.co,states->co,states->vel,dtime);
2356                                 VECADDFAC(pa->state.vel,states->vel,force,dtime);
2357                                 break;
2358                         case PART_INT_MIDPOINT:
2359                                 if(i==0){
2360                                         VECADDFAC(states[1].co,states->co,states->vel,dtime*0.5f);
2361                                         VECADDFAC(states[1].vel,states->vel,force,dtime*0.5f);
2362                                         fra=sim->psys->cfra+0.5f*dfra;
2363                                 }
2364                                 else{
2365                                         VECADDFAC(pa->state.co,states->co,states[1].vel,dtime);
2366                                         VECADDFAC(pa->state.vel,states->vel,force,dtime);
2367                                 }
2368                                 break;
2369                         case PART_INT_RK4:
2370                                 switch(i){
2371                                         case 0:
2372                                                 VECCOPY(dx[0],states->vel);
2373                                                 mul_v3_fl(dx[0],dtime);
2374                                                 VECCOPY(dv[0],force);
2375                                                 mul_v3_fl(dv[0],dtime);
2376
2377                                                 VECADDFAC(states[1].co,states->co,dx[0],0.5f);
2378                                                 VECADDFAC(states[1].vel,states->vel,dv[0],0.5f);
2379                                                 fra=sim->psys->cfra+0.5f*dfra;
2380                                                 break;
2381                                         case 1:
2382                                                 VECADDFAC(dx[1],states->vel,dv[0],0.5f);
2383                                                 mul_v3_fl(dx[1],dtime);
2384                                                 VECCOPY(dv[1],force);
2385                                                 mul_v3_fl(dv[1],dtime);
2386
2387                                                 VECADDFAC(states[2].co,states->co,dx[1],0.5f);
2388                                                 VECADDFAC(states[2].vel,states->vel,dv[1],0.5f);
2389                                                 break;
2390                                         case 2:
2391                                                 VECADDFAC(dx[2],states->vel,dv[1],0.5f);
2392                                                 mul_v3_fl(dx[2],dtime);
2393                                                 VECCOPY(dv[2],force);
2394                                                 mul_v3_fl(dv[2],dtime);
2395
2396                                                 VECADD(states[3].co,states->co,dx[2]);
2397                                                 VECADD(states[3].vel,states->vel,dv[2]);
2398                                                 fra=cfra;
2399                                                 break;
2400                                         case 3:
2401                                                 VECADD(dx[3],states->vel,dv[2]);
2402                                                 mul_v3_fl(dx[3],dtime);
2403                                                 VECCOPY(dv[3],force);
2404                                                 mul_v3_fl(dv[3],dtime);
2405
2406                                                 VECADDFAC(pa->state.co,states->co,dx[0],1.0f/6.0f);
2407                                                 VECADDFAC(pa->state.co,pa->state.co,dx[1],1.0f/3.0f);
2408                                                 VECADDFAC(pa->state.co,pa->state.co,dx[2],1.0f/3.0f);
2409                                                 VECADDFAC(pa->state.co,pa->state.co,dx[3],1.0f/6.0f);
2410
2411                                                 VECADDFAC(pa->state.vel,states->vel,dv[0],1.0f/6.0f);
2412                                                 VECADDFAC(pa->state.vel,pa->state.vel,dv[1],1.0f/3.0f);
2413                                                 VECADDFAC(pa->state.vel,pa->state.vel,dv[2],1.0f/3.0f);
2414                                                 VECADDFAC(pa->state.vel,pa->state.vel,dv[3],1.0f/6.0f);
2415                                 }
2416                                 break;
2417                         case PART_INT_VERLET:   /* Verlet integration */
2418                                 VECADDFAC(pa->state.vel,pa->state.vel,force,dtime);
2419                                 VECADDFAC(pa->state.co,pa->state.co,pa->state.vel,dtime);
2420
2421                                 VECSUB(pa->state.vel,pa->state.co,oldpos);
2422                                 mul_v3_fl(pa->state.vel,1.0f/dtime);
2423                                 break;
2424                 }
2425         }
2426
2427         /* damp affects final velocity */
2428         if(part->dampfac!=0.0)
2429                 mul_v3_fl(pa->state.vel,1.0f-part->dampfac);
2430
2431         VECCOPY(pa->state.ave, states->ave);
2432
2433         /* finally we do guides */
2434         time=(cfra-pa->time)/pa->lifetime;
2435         CLAMP(time,0.0,1.0);
2436
2437         VECCOPY(tkey.co,pa->state.co);
2438         VECCOPY(tkey.vel,pa->state.vel);
2439         tkey.time=pa->state.time;
2440
2441         if(part->type != PART_HAIR) {
2442                 if(do_guides(sim->psys->effectors, &tkey, p, time)) {
2443                         VECCOPY(pa->state.co,tkey.co);
2444                         /* guides don't produce valid velocity */
2445                         VECSUB(pa->state.vel,tkey.co,pa->prev_state.co);
2446                         mul_v3_fl(pa->state.vel,1.0f/dtime);
2447                         pa->state.time=tkey.time;
2448                 }
2449         }
2450 }
2451 static void rotate_particle(ParticleSettings *part, ParticleData *pa, float dfra, float timestep)
2452 {
2453         float rotfac, rot1[4], rot2[4]={1.0,0.0,0.0,0.0}, dtime=dfra*timestep;
2454
2455         if((part->flag & PART_ROT_DYN)==0){
2456                 if(part->avemode==PART_AVE_SPIN){
2457                         float angle;
2458                         float len1 = len_v3(pa->prev_state.vel);
2459                         float len2 = len_v3(pa->state.vel);
2460
2461                         if(len1==0.0f || len2==0.0f)
2462                                 pa->state.ave[0]=pa->state.ave[1]=pa->state.ave[2]=0.0f;
2463                         else{
2464                                 cross_v3_v3v3(pa->state.ave,pa->prev_state.vel,pa->state.vel);
2465                                 normalize_v3(pa->state.ave);
2466                                 angle=dot_v3v3(pa->prev_state.vel,pa->state.vel)/(len1*len2);
2467                                 mul_v3_fl(pa->state.ave,saacos(angle)/dtime);
2468                         }
2469
2470                         axis_angle_to_quat(rot2,pa->state.vel,dtime*part->avefac);
2471                 }
2472         }
2473
2474         rotfac=len_v3(pa->state.ave);
2475         if(rotfac==0.0){ /* unit_qt(in VecRotToQuat) doesn't give unit quat [1,0,0,0]?? */
2476                 rot1[0]=1.0;
2477                 rot1[1]=rot1[2]=rot1[3]=0;
2478         }
2479         else{
2480                 axis_angle_to_quat(rot1,pa->state.ave,rotfac*dtime);
2481         }
2482         mul_qt_qtqt(pa->state.rot,rot1,pa->prev_state.rot);
2483         mul_qt_qtqt(pa->state.rot,rot2,pa->state.rot);
2484
2485         /* keep rotation quat in good health */
2486         normalize_qt(pa->state.rot);
2487 }
2488
2489 /* convert from triangle barycentric weights to quad mean value weights */
2490 static void intersect_dm_quad_weights(float *v1, float *v2, float *v3, float *v4, float *w)
2491 {
2492         float co[3], vert[4][3];
2493
2494         VECCOPY(vert[0], v1);
2495         VECCOPY(vert[1], v2);
2496         VECCOPY(vert[2], v3);
2497         VECCOPY(vert[3], v4);
2498
2499         co[0]= v1[0]*w[0] + v2[0]*w[1] + v3[0]*w[2] + v4[0]*w[3];
2500         co[1]= v1[1]*w[0] + v2[1]*w[1] + v3[1]*w[2] + v4[1]*w[3];
2501         co[2]= v1[2]*w[0] + v2[2]*w[1] + v3[2]*w[2] + v4[2]*w[3];
2502
2503         interp_weights_poly_v3( w,vert, 4, co);
2504 }
2505
2506 /* check intersection with a derivedmesh */
2507 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,
2508                                                   float *face_minmax, float *pa_minmax, float radius, float *ipoint)
2509 {
2510         MFace *mface=0;
2511         MVert *mvert=0;
2512         int i, totface, intersect=0;
2513         float cur_d, cur_uv[2], v1[3], v2[3], v3[3], v4[3], min[3], max[3], p_min[3],p_max[3];
2514         float cur_ipoint[3];
2515         
2516         if(dm==0){
2517                 psys_disable_all(ob);
2518
2519                 dm=mesh_get_derived_final(scene, ob, 0);
2520                 if(dm==0)
2521                         dm=mesh_get_derived_deform(scene, ob, 0);
2522
2523                 psys_enable_all(ob);
2524
2525                 if(dm==0)
2526                         return 0;
2527         }
2528
2529         
2530
2531         if(pa_minmax==0){
2532                 INIT_MINMAX(p_min,p_max);
2533                 DO_MINMAX(co1,p_min,p_max);
2534                 DO_MINMAX(co2,p_min,p_max);
2535         }
2536         else{
2537                 VECCOPY(p_min,pa_minmax);
2538                 VECCOPY(p_max,pa_minmax+3);
2539         }
2540
2541         totface=dm->getNumFaces(dm);
2542         mface=dm->getFaceDataArray(dm,CD_MFACE);
2543         mvert=dm->getVertDataArray(dm,CD_MVERT);
2544         
2545         /* lets intersect the faces */
2546         for(i=0; i<totface; i++,mface++){
2547                 if(vert_cos){
2548                         VECCOPY(v1,vert_cos+3*mface->v1);
2549                         VECCOPY(v2,vert_cos+3*mface->v2);
2550                         VECCOPY(v3,vert_cos+3*mface->v3);
2551                         if(mface->v4)
2552                                 VECCOPY(v4,vert_cos+3*mface->v4)
2553                 }
2554                 else{
2555                         VECCOPY(v1,mvert[mface->v1].co);
2556                         VECCOPY(v2,mvert[mface->v2].co);
2557                         VECCOPY(v3,mvert[mface->v3].co);
2558                         if(mface->v4)
2559                                 VECCOPY(v4,mvert[mface->v4].co)
2560                 }
2561
2562                 if(face_minmax==0){
2563                         INIT_MINMAX(min,max);
2564                         DO_MINMAX(v1,min,max);
2565                         DO_MINMAX(v2,min,max);
2566                         DO_MINMAX(v3,min,max);
2567                         if(mface->v4)
2568                                 DO_MINMAX(v4,min,max)
2569                         if(isect_aabb_aabb_v3(min,max,p_min,p_max)==0)
2570                                 continue;
2571                 }
2572                 else{
2573                         VECCOPY(min, face_minmax+6*i);
2574                         VECCOPY(max, face_minmax+6*i+3);
2575                         if(isect_aabb_aabb_v3(min,max,p_min,p_max)==0)
2576                                 continue;
2577                 }
2578
2579                 if(radius>0.0f){
2580                         if(isect_sweeping_sphere_tri_v3(co1, co2, radius, v2, v3, v1, &cur_d, cur_ipoint)){
2581                                 if(cur_d<*min_d){
2582                                         *min_d=cur_d;
2583                                         VECCOPY(ipoint,cur_ipoint);
2584                                         *min_face=i;
2585                                         intersect=1;
2586                                 }
2587                         }
2588                         if(mface->v4){
2589                                 if(isect_sweeping_sphere_tri_v3(co1, co2, radius, v4, v1, v3, &cur_d, cur_ipoint)){
2590                                         if(cur_d<*min_d){
2591                                                 *min_d=cur_d;
2592                                                 VECCOPY(ipoint,cur_ipoint);
2593                                                 *min_face=i;
2594                                                 intersect=1;
2595                                         }
2596                                 }
2597                         }
2598                 }
2599                 else{
2600                         if(isect_line_tri_v3(co1, co2, v1, v2, v3, &cur_d, cur_uv)){
2601                                 if(cur_d<*min_d){
2602                                         *min_d=cur_d;
2603                                         min_w[0]= 1.0 - cur_uv[0] - cur_uv[1];
2604                                         min_w[1]= cur_uv[0];
2605                                         min_w[2]= cur_uv[1];
2606                                         min_w[3]= 0.0f;
2607                                         if(mface->v4)
2608                                                 intersect_dm_quad_weights(v1, v2, v3, v4, min_w);
2609                                         *min_face=i;
2610                                         intersect=1;
2611                                 }
2612                         }
2613                         if(mface->v4){
2614                                 if(isect_line_tri_v3(co1, co2, v1, v3, v4, &cur_d, cur_uv)){
2615                                         if(cur_d<*min_d){
2616                                                 *min_d=cur_d;
2617                                                 min_w[0]= 1.0 - cur_uv[0] - cur_uv[1];
2618                                                 min_w[1]= 0.0f;
2619                                                 min_w[2]= cur_uv[0];
2620                                                 min_w[3]= cur_uv[1];
2621                                                 intersect_dm_quad_weights(v1, v2, v3, v4, min_w);
2622                                                 *min_face=i;
2623                                                 intersect=1;
2624                                         }
2625                                 }
2626                         }
2627                 }
2628         }
2629         return intersect;
2630 }
2631
2632 void particle_intersect_face(void *userdata, int index, const BVHTreeRay *ray, BVHTreeRayHit *hit)
2633 {
2634         ParticleCollision *col = (ParticleCollision *) userdata;
2635         MFace *face = col->md->mfaces + index;
2636         MVert *x = col->md->x;
2637         MVert *v = col->md->current_v;
2638         float vel[3], co1[3], co2[3], uv[2], ipoint[3], temp[3], t;
2639
2640         float *t0, *t1, *t2, *t3;
2641         t0 = x[ face->v1 ].co;
2642         t1 = x[ face->v2 ].co;
2643         t2 = x[ face->v3 ].co;
2644         t3 = face->v4 ? x[ face->v4].co : NULL;
2645
2646         /* calculate average velocity of face */
2647         VECCOPY(vel, v[ face->v1 ].co);
2648         VECADD(vel, vel, v[ face->v2 ].co);
2649         VECADD(vel, vel, v[ face->v3 ].co);
2650         mul_v3_fl(vel, 0.33334f);
2651
2652         /* substract face velocity, in other words convert to 
2653            a coordinate system where only the particle moves */
2654         VECADDFAC(co1, col->co1, vel, -col->t);
2655         VECSUB(co2, col->co2, vel);
2656
2657         do
2658         {       
2659                 if(ray->radius == 0.0f) {
2660                         if(isect_line_tri_v3(co1, co2, t0, t1, t2, &t, uv)) {
2661                                 if(t >= 0.0f && t < hit->dist/col->ray_len) {
2662                                         hit->dist = col->ray_len * t;
2663                                         hit->index = index;
2664
2665                                         /* calculate normal that's facing the particle */
2666                                         normal_tri_v3( col->nor,t0, t1, t2);
2667                                         VECSUB(temp, co2, co1);
2668                                         if(dot_v3v3(col->nor, temp) > 0.0f)
2669                                                 negate_v3(col->nor);
2670
2671                                         VECCOPY(col->vel,vel);
2672
2673                                         col->hit_ob = col->ob;
2674                                         col->hit_md = col->md;
2675                                 }
2676                         }
2677                 }
2678                 else {
2679                         if(isect_sweeping_sphere_tri_v3(co1, co2, ray->radius, t0, t1, t2, &t, ipoint)) {
2680                                 if(t >=0.0f && t < hit->dist/col->ray_len) {
2681                                         hit->dist = col->ray_len * t;
2682                                         hit->index = index;
2683
2684                                         interp_v3_v3v3(temp, co1, co2, t);
2685                                         
2686                                         VECSUB(col->nor, temp, ipoint);
2687                                         normalize_v3(col->nor);
2688
2689                                         VECCOPY(col->vel,vel);
2690
2691                                         col->hit_ob = col->ob;
2692                                         col->hit_md = col->md;
2693                                 }
2694                         }
2695                 }
2696
2697                 t1 = t2;
2698                 t2 = t3;
2699                 t3 = NULL;
2700
2701         } while(t2);
2702 }
2703 /* particle - mesh collision code */
2704 /* in addition to basic point to surface collisions handles friction & damping,*/
2705 /* angular momentum <-> linear momentum and swept sphere - mesh collisions */
2706 /* 1. check for all possible deflectors for closest intersection on particle path */
2707 /* 2. if deflection was found kill the particle or calculate new coordinates */
2708 static void deflect_particle(ParticleSimulationData *sim, int p, float dfra, float cfra){
2709         Object *ground_ob = NULL;
2710         ParticleSettings *part = sim->psys->part;
2711         ParticleData *pa = sim->psys->particles + p;
2712         ParticleCollision col;
2713         ColliderCache *coll;
2714         BVHTreeRayHit hit;
2715         float ray_dir[3], zerovec[3]={0.0,0.0,0.0};
2716         float radius = ((part->flag & PART_SIZE_DEFL)?pa->size:0.0f), boid_z = 0.0f;
2717         float timestep = psys_get_timestep(sim);
2718         int deflections=0, max_deflections=10;
2719
2720         VECCOPY(col.co1, pa->prev_state.co);
2721         VECCOPY(col.co2, pa->state.co);
2722         col.t = 0.0f;
2723
2724         /* override for boids */
2725         if(part->phystype == PART_PHYS_BOIDS) {
2726                 BoidParticle *bpa = pa->boid;
2727                 radius = pa->size;
2728                 boid_z = pa->state.co[2];
2729                 ground_ob = bpa->ground;
2730         }
2731
2732         /* 10 iterations to catch multiple deflections */
2733         if(sim->colliders) while(deflections < max_deflections){
2734                 /* 1. */
2735
2736                 VECSUB(ray_dir, col.co2, col.co1);
2737                 hit.index = -1;
2738                 hit.dist = col.ray_len = len_v3(ray_dir);
2739
2740                 /* even if particle is stationary we want to check for moving colliders */
2741                 /* if hit.dist is zero the bvhtree_ray_cast will just ignore everything */
2742                 if(hit.dist == 0.0f)
2743                         hit.dist = col.ray_len = 0.000001f;
2744
2745                 for(coll = sim->colliders->first; coll; coll=coll->next){
2746                         /* for boids: don't check with current ground object */
2747                         if(coll->ob == ground_ob)
2748                                 continue;
2749
2750                         /* particles should not collide with emitter at birth */
2751                         if(coll->ob == sim->ob && pa->time < cfra && pa->time >= sim->psys->cfra)
2752                                 continue;
2753
2754                         col.ob = coll->ob;
2755                         col.md = coll->collmd;
2756
2757                         if(col.md && col.md->bvhtree)
2758                                 BLI_bvhtree_ray_cast(col.md->bvhtree, col.co1, ray_dir, radius, &hit, particle_intersect_face, &col);
2759                 }
2760
2761                 /* 2. */
2762                 if(hit.index>=0) {
2763                         PartDeflect *pd = col.hit_ob->pd;
2764                         int through = (BLI_frand() < pd->pdef_perm) ? 1 : 0;
2765                         float co[3]; /* point of collision */
2766                         float vec[3]; /* movement through collision */
2767                         float t = hit.dist/col.ray_len; /* time of collision between this iteration */
2768                         float dt = col.t + t * (1.0f - col.t); /* time of collision between frame change*/
2769
2770                         interp_v3_v3v3(co, col.co1, col.co2, t);
2771                         VECSUB(vec, col.co2, col.co1);
2772
2773                         mul_v3_fl(col.vel, 1.0f-col.t);
2774
2775                         /* particle dies in collision */
2776                         if(through == 0 && (part->flag & PART_DIE_ON_COL || pd->flag & PDEFLE_KILL_PART)) {
2777                                 pa->alive = PARS_DYING;
2778                                 pa->dietime = pa->state.time + (cfra - pa->state.time) * dt;
2779                                 
2780                                 /* we have to add this for dying particles too so that reactors work correctly */
2781                                 VECADDFAC(co, co, col.nor, (through ? -0.0001f : 0.0001f));
2782
2783                                 VECCOPY(pa->state.co, co);
2784                                 interp_v3_v3v3(pa->state.vel, pa->prev_state.vel, pa->state.vel, dt);
2785                                 interp_qt_qtqt(pa->state.rot, pa->prev_state.rot, pa->state.rot, dt);
2786                                 interp_v3_v3v3(pa->state.ave, pa->prev_state.ave, pa->state.ave, dt);
2787
2788                                 /* particle is dead so we don't need to calculate further */
2789                                 deflections=max_deflections;
2790                         }
2791                         else {
2792                                 float nor_vec[3], tan_vec[3], tan_vel[3], vel[3];
2793                                 float damp, frict;
2794                                 float inp, inp_v;
2795                                 
2796                                 /* get damping & friction factors */
2797                                 damp = pd->pdef_damp + pd->pdef_rdamp * 2 * (BLI_frand() - 0.5f);
2798                                 CLAMP(damp,0.0,1.0);
2799
2800                                 frict = pd->pdef_frict + pd->pdef_rfrict * 2 * (BLI_frand() - 0.5f);
2801                                 CLAMP(frict,0.0,1.0);
2802
2803                                 /* treat normal & tangent components separately */
2804                                 inp = dot_v3v3(col.nor, vec);
2805                                 inp_v = dot_v3v3(col.nor, col.vel);
2806
2807                                 VECADDFAC(tan_vec, vec, col.nor, -inp);
2808                                 VECADDFAC(tan_vel, col.vel, col.nor, -inp_v);
2809                                 if((part->flag & PART_ROT_DYN)==0)
2810                                         interp_v3_v3v3(tan_vec, tan_vec, tan_vel, frict);
2811
2812                                 VECCOPY(nor_vec, col.nor);
2813                                 inp *= 1.0f - damp;
2814
2815                                 if(through)
2816                                         inp_v *= damp;
2817
2818                                 /* special case for object hitting the particle from behind */
2819                                 if(through==0 && ((inp_v>0 && inp>0 && inp_v>inp) || (inp_v<0 && inp<0 && inp_v<inp)))
2820                                         mul_v3_fl(nor_vec, inp_v);
2821                                 else
2822                                         mul_v3_fl(nor_vec, inp_v + (through ? 1.0f : -1.0f) * inp);
2823
2824                                 /* angular <-> linear velocity - slightly more physical and looks even nicer than before */
2825                                 if(part->flag & PART_ROT_DYN) {
2826                                         float surface_vel[3], rot_vel[3], friction[3], dave[3], dvel[3];
2827
2828                                         /* apparent velocity along collision surface */
2829                                         VECSUB(surface_vel, tan_vec, tan_vel);
2830
2831                                         /* direction of rolling friction */
2832                                         cross_v3_v3v3(rot_vel, pa->state.ave, col.nor);
2833                                         /* convert to current dt */
2834                                         mul_v3_fl(rot_vel, (timestep*dfra) * (1.0f - col.t));
2835                                         mul_v3_fl(rot_vel, pa->size);
2836
2837                                         /* apply sliding friction */
2838                                         VECSUB(surface_vel, surface_vel, rot_vel);
2839                                         VECCOPY(friction, surface_vel);
2840
2841                                         mul_v3_fl(surface_vel, 1.0 - frict);
2842                                         mul_v3_fl(friction, frict);
2843
2844                                         /* sliding changes angular velocity */
2845                                         cross_v3_v3v3(dave, col.nor, friction);
2846                                         mul_v3_fl(dave, 1.0f/MAX2(pa->size, 0.001));
2847
2848                                         /* we assume rolling friction is around 0.01 of sliding friction */
2849                                         mul_v3_fl(rot_vel, 1.0 - frict*0.01);
2850
2851                                         /* change in angular velocity has to be added to the linear velocity too */
2852                                         cross_v3_v3v3(dvel, dave, col.nor);
2853                                         mul_v3_fl(dvel, pa->size);
2854                                         VECADD(rot_vel, rot_vel, dvel);
2855
2856                                         VECADD(surface_vel, surface_vel, rot_vel);
2857                                         VECADD(tan_vec, surface_vel, tan_vel);
2858
2859                                         /* convert back to normal time */
2860                                         mul_v3_fl(dave, 1.0f/MAX2((timestep*dfra) * (1.0f - col.t), 0.00001));
2861
2862                                         mul_v3_fl(pa->state.ave, 1.0 - frict*0.01);
2863                                         VECADD(pa->state.ave, pa->state.ave, dave);
2864                                 }
2865
2866                                 /* combine components together again */
2867                                 VECADD(vec, nor_vec, tan_vec);
2868
2869                                 /* calculate velocity from collision vector */
2870                                 VECCOPY(vel, vec);
2871                                 mul_v3_fl(vel, 1.0f/MAX2((timestep*dfra) * (1.0f - col.t), 0.00001));
2872
2873                                 /* make sure we don't hit the current face again */</