- Particle-particle effectors we're quite unstable and not accurate at all. Now this...
[blender.git] / source / blender / blenkernel / intern / particle.c
1 /* particle.c
2  *
3  *
4  * $Id: particle.c $
5  *
6  * ***** BEGIN GPL LICENSE BLOCK *****
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License
10  * as published by the Free Software Foundation; either version 2
11  * of the License, or (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software Foundation,
20  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
21  *
22  * The Original Code is Copyright (C) 2007 by Janne Karhu.
23  * All rights reserved.
24  *
25  * The Original Code is: all of this file.
26  *
27  * Contributor(s): none yet.
28  *
29  * ***** END GPL LICENSE BLOCK *****
30  */
31
32 #include <stdlib.h>
33 #include <math.h>
34 #include <string.h>
35
36 #include "MEM_guardedalloc.h"
37
38 #include "DNA_scene_types.h"
39 #include "DNA_particle_types.h"
40 #include "DNA_mesh_types.h"
41 #include "DNA_meshdata_types.h"
42 #include "DNA_modifier_types.h"
43 #include "DNA_object_force.h"
44 #include "DNA_texture_types.h"
45 #include "DNA_material_types.h"
46 #include "DNA_object_types.h"
47 #include "DNA_curve_types.h"
48 #include "DNA_key_types.h"
49 #include "DNA_ipo_types.h"
50
51 #include "BLI_arithb.h"
52 #include "BLI_blenlib.h"
53 #include "BLI_dynstr.h"
54 #include "BLI_kdtree.h"
55 #include "BLI_linklist.h"
56 #include "BLI_rand.h"
57 #include "BLI_threads.h"
58
59 #include "BKE_anim.h"
60
61 #include "BKE_global.h"
62 #include "BKE_main.h"
63 #include "BKE_lattice.h"
64 #include "BKE_utildefines.h"
65 #include "BKE_displist.h"
66 #include "BKE_particle.h"
67 #include "BKE_DerivedMesh.h"
68 #include "BKE_ipo.h"
69 #include "BKE_object.h"
70 #include "BKE_softbody.h"
71 #include "BKE_material.h"
72 #include "BKE_key.h"
73 #include "BKE_library.h"
74 #include "BKE_depsgraph.h"
75 #include "BKE_bad_level_calls.h"
76 #include "BKE_modifier.h"
77 #include "BKE_mesh.h"
78 #include "BKE_cdderivedmesh.h"
79 #include "BKE_pointcache.h"
80
81 #include "blendef.h"
82 #include "RE_render_ext.h"
83
84 static void key_from_object(Object *ob, ParticleKey *key);
85 static void get_cpa_texture(DerivedMesh *dm, Material *ma, int face_index,
86                                 float *fuv, float *orco, ParticleTexture *ptex, int event);
87
88 /* few helpers for countall etc. */
89 int count_particles(ParticleSystem *psys){
90         ParticleSettings *part=psys->part;
91         ParticleData *pa;
92         int tot=0,p;
93
94         for(p=0,pa=psys->particles; p<psys->totpart; p++,pa++){
95                 if(pa->alive == PARS_KILLED);
96                 else if(pa->alive == PARS_UNBORN && (part->flag & PART_UNBORN)==0);
97                 else if(pa->alive == PARS_DEAD && (part->flag & PART_DIED)==0);
98                 else if(pa->flag & (PARS_UNEXIST+PARS_NO_DISP));
99                 else tot++;
100         }
101         return tot;
102 }
103 int count_particles_mod(ParticleSystem *psys, int totgr, int cur){
104         ParticleSettings *part=psys->part;
105         ParticleData *pa;
106         int tot=0,p;
107
108         for(p=0,pa=psys->particles; p<psys->totpart; p++,pa++){
109                 if(pa->alive == PARS_KILLED);
110                 else if(pa->alive == PARS_UNBORN && (part->flag & PART_UNBORN)==0);
111                 else if(pa->alive == PARS_DEAD && (part->flag & PART_DIED)==0);
112                 else if(pa->flag & (PARS_UNEXIST+PARS_NO_DISP));
113                 else if(p%totgr==cur) tot++;
114         }
115         return tot;
116 }
117 int psys_count_keys(ParticleSystem *psys)
118 {
119         ParticleData *pa;
120         int i, totpart=psys->totpart, totkey=0;
121
122         for(i=0, pa=psys->particles; i<totpart; i++, pa++)
123                 totkey += pa->totkey;
124
125         return totkey;
126 }
127 /* remember to free the pointer returned from this! */
128 char *psys_menu_string(Object *ob, int for_sb)
129 {
130         ParticleSystem *psys;
131         DynStr *ds;
132         char *str, num[6];
133         int i;
134
135         ds = BLI_dynstr_new();
136
137         if(for_sb)
138                 BLI_dynstr_append(ds, "|Object%x-1");
139         
140         for(i=0,psys=ob->particlesystem.first; psys; i++,psys=psys->next){
141
142                 BLI_dynstr_append(ds, "|");
143                 sprintf(num,"%i. ",i+1);
144                 BLI_dynstr_append(ds, num);
145                 BLI_dynstr_append(ds, psys->part->id.name+2);
146                 sprintf(num,"%%x%i",i+1);
147                 BLI_dynstr_append(ds, num);
148         }
149         
150         str = BLI_dynstr_get_cstring(ds);
151
152         BLI_dynstr_free(ds);
153
154         return str;
155 }
156
157 /* we allocate path cache memory in chunks instead of a big continguous
158  * chunk, windows' memory allocater fails to find big blocks of memory often */
159
160 #define PATH_CACHE_BUF_SIZE 1024
161
162 static ParticleCacheKey **psys_alloc_path_cache_buffers(ListBase *bufs, int tot, int steps)
163 {
164         LinkData *buf;
165         ParticleCacheKey **cache;
166         int i, totkey, totbufkey;
167
168         tot= MAX2(tot, 1);
169         totkey = 0;
170         cache = MEM_callocN(tot*sizeof(void*), "PathCacheArray");
171
172         while(totkey < tot) {
173                 totbufkey= MIN2(tot-totkey, PATH_CACHE_BUF_SIZE);
174                 buf= MEM_callocN(sizeof(LinkData), "PathCacheLinkData");
175                 buf->data= MEM_callocN(sizeof(ParticleCacheKey)*totbufkey*steps, "ParticleCacheKey");
176
177                 for(i=0; i<totbufkey; i++)
178                         cache[totkey+i] = ((ParticleCacheKey*)buf->data) + i*steps;
179
180                 totkey += totbufkey;
181                 BLI_addtail(bufs, buf);
182         }
183
184         return cache;
185 }
186
187 static void psys_free_path_cache_buffers(ParticleCacheKey **cache, ListBase *bufs)
188 {
189         LinkData *buf;
190
191         if(cache)
192                 MEM_freeN(cache);
193
194         for(buf= bufs->first; buf; buf=buf->next)
195                 MEM_freeN(buf->data);
196         BLI_freelistN(bufs);
197 }
198
199 /************************************************/
200 /*                      Getting stuff                                           */
201 /************************************************/
202 /* get object's active particle system safely */
203 ParticleSystem *psys_get_current(Object *ob)
204 {
205         ParticleSystem *psys;
206         if(ob==0) return 0;
207
208         for(psys=ob->particlesystem.first; psys; psys=psys->next){
209                 if(psys->flag & PSYS_CURRENT)
210                         return psys;
211         }
212         
213         return 0;
214 }
215 short psys_get_current_num(Object *ob)
216 {
217         ParticleSystem *psys;
218         short i;
219
220         if(ob==0) return 0;
221
222         for(psys=ob->particlesystem.first, i=0; psys; psys=psys->next, i++)
223                 if(psys->flag & PSYS_CURRENT)
224                         return i;
225         
226         return i;
227 }
228 /* change object's active particle system */
229 void psys_change_act(void *ob_v, void *act_v)
230 {
231         Object *ob = ob_v;
232         ParticleSystem *npsys, *psys;
233         short act = *((short*)act_v)-1;
234
235         if(act>=0){
236                 npsys=BLI_findlink(&ob->particlesystem,act);
237                 psys=psys_get_current(ob);
238
239                 if(psys)
240                         psys->flag &= ~PSYS_CURRENT;
241                 if(npsys)
242                         npsys->flag |= PSYS_CURRENT;
243         }
244 }
245 Object *psys_get_lattice(Object *ob, ParticleSystem *psys)
246 {
247         Object *lattice=0;
248         
249         if(psys_in_edit_mode(psys)==0){
250
251                 ModifierData *md = (ModifierData*)psys_get_modifier(ob,psys);
252
253                 for(; md; md=md->next){
254                         if(md->type==eModifierType_Lattice){
255                                 LatticeModifierData *lmd = (LatticeModifierData *)md;
256                                 lattice=lmd->object;
257                                 break;
258                         }
259                 }
260                 if(lattice)
261                         init_latt_deform(lattice,0);
262         }
263
264         return lattice;
265 }
266 void psys_disable_all(Object *ob)
267 {
268         ParticleSystem *psys=ob->particlesystem.first;
269
270         for(; psys; psys=psys->next)
271                 psys->flag |= PSYS_DISABLED;
272 }
273 void psys_enable_all(Object *ob)
274 {
275         ParticleSystem *psys=ob->particlesystem.first;
276
277         for(; psys; psys=psys->next)
278                 psys->flag &= ~PSYS_DISABLED;
279 }
280 int psys_ob_has_hair(Object *ob)
281 {
282         ParticleSystem *psys = ob->particlesystem.first;
283
284         for(; psys; psys=psys->next)
285                 if(psys->part->type == PART_HAIR)
286                         return 1;
287
288         return 0;
289 }
290 int psys_in_edit_mode(ParticleSystem *psys)
291 {
292         return ((G.f & G_PARTICLEEDIT) && psys==psys_get_current(OBACT) && psys->edit);
293 }
294 int psys_check_enabled(Object *ob, ParticleSystem *psys)
295 {
296         ParticleSystemModifierData *psmd;
297         Mesh *me;
298
299         if(psys->flag & PSYS_DISABLED || psys->flag & PSYS_DELETE)
300                 return 0;
301
302         if(ob->type == OB_MESH) {
303                 me= (Mesh*)ob->data;
304                 if(me->mr && me->mr->current != 1)
305                         return 0;
306         }
307
308         psmd= psys_get_modifier(ob, psys);
309         if(psys->renderdata) {
310                 if(!(psmd->modifier.mode & eModifierMode_Render))
311                         return 0;
312         }
313         else if(!(psmd->modifier.mode & eModifierMode_Realtime))
314                 return 0;
315         
316         return 1;
317 }
318
319 /************************************************/
320 /*                      Freeing stuff                                           */
321 /************************************************/
322 void psys_free_settings(ParticleSettings *part)
323 {
324         if(part->pd) {
325                 MEM_freeN(part->pd);
326                 part->pd = NULL;
327         }
328         if(part->pd2) {
329                 MEM_freeN(part->pd2);
330                 part->pd2 = NULL;
331         }
332 }
333
334 void free_hair(ParticleSystem *psys, int softbody)
335 {
336         ParticleData *pa;
337         int i, totpart=psys->totpart;
338
339         for(i=0, pa=psys->particles; i<totpart; i++, pa++) {
340                 if(pa->hair)
341                         MEM_freeN(pa->hair);
342                 pa->hair = NULL;
343         }
344
345         psys->flag &= ~PSYS_HAIR_DONE;
346
347         if(softbody && psys->soft) {
348                 sbFree(psys->soft);
349                 psys->soft = NULL;
350         }
351 }
352 void free_keyed_keys(ParticleSystem *psys)
353 {
354         if(psys->particles && psys->particles->keys)
355                 MEM_freeN(psys->particles->keys);
356 }
357 void free_child_path_cache(ParticleSystem *psys)
358 {
359         psys_free_path_cache_buffers(psys->childcache, &psys->childcachebufs);
360         psys->childcache = NULL;
361         psys->totchildcache = 0;
362 }
363 void psys_free_path_cache(ParticleSystem *psys)
364 {
365         psys_free_path_cache_buffers(psys->pathcache, &psys->pathcachebufs);
366         psys->pathcache= NULL;
367         psys->totcached= 0;
368
369         free_child_path_cache(psys);
370 }
371 void psys_free_children(ParticleSystem *psys)
372 {
373         if(psys->child) {
374                 MEM_freeN(psys->child);
375                 psys->child=0;
376                 psys->totchild=0;
377         }
378
379         free_child_path_cache(psys);
380 }
381 /* free everything */
382 void psys_free(Object *ob, ParticleSystem * psys)
383 {       
384         if(psys){
385                 int nr = 0;
386                 ParticleSystem * tpsys;
387                 
388                 if(ob->particlesystem.first == NULL && G.f & G_PARTICLEEDIT)
389                         G.f &= ~G_PARTICLEEDIT;
390
391                 psys_free_path_cache(psys);
392
393                 free_hair(psys, 1);
394
395                 free_keyed_keys(psys);
396
397                 PE_free_particle_edit(psys);
398
399                 if(psys->particles){
400                         MEM_freeN(psys->particles);
401                         psys->particles = 0;
402                         psys->totpart = 0;
403                 }
404
405                 if(psys->child){
406                         MEM_freeN(psys->child);
407                         psys->child = 0;
408                         psys->totchild = 0;
409                 }
410
411                 if(psys->effectors.first)
412                         psys_end_effectors(psys);
413                 
414                 // check if we are last non-visible particle system
415                 for(tpsys=ob->particlesystem.first; tpsys; tpsys=tpsys->next){
416                         if(tpsys->part)
417                         {
418                                 if(ELEM(tpsys->part->draw_as,PART_DRAW_OB,PART_DRAW_GR))
419                                 {
420                                         nr++;
421                                         break;
422                                 }
423                         }
424                 }
425                 // clear do-not-draw-flag
426                 if(!nr)
427                         ob->transflag &= ~OB_DUPLIPARTS;
428
429                 if(psys->part){
430                         psys->part->id.us--;            
431                         psys->part=0;
432                 }
433
434                 if(psys->reactevents.first)
435                         BLI_freelistN(&psys->reactevents);
436
437                 if(psys->pointcache)
438                         BKE_ptcache_free(psys->pointcache);
439                 
440                 MEM_freeN(psys);
441         }
442 }
443
444 /* these functions move away particle data and bring it back after
445  * rendering, to make different render settings possible without
446  * removing the previous data. this should be solved properly once */
447
448 typedef struct ParticleRenderElem {
449         int curchild, totchild, reduce;
450         float lambda, t, scalemin, scalemax;
451 } ParticleRenderElem;
452
453 typedef struct ParticleRenderData {
454         ChildParticle *child;
455         ParticleCacheKey **pathcache;
456         ParticleCacheKey **childcache;
457         int totchild, totcached, totchildcache;
458         DerivedMesh *dm;
459         int totdmvert, totdmedge, totdmface;
460
461         float mat[4][4];
462         float viewmat[4][4], winmat[4][4];
463         int winx, winy;
464
465         int dosimplify;
466         int timeoffset;
467         ParticleRenderElem *elems;
468         int *origindex;
469 } ParticleRenderData;
470
471 static float psys_render_viewport_falloff(double rate, float dist, float width)
472 {
473         return pow(rate, dist/width);
474 }
475
476 static float psys_render_projected_area(ParticleSystem *psys, float *center, float area, double vprate, float *viewport)
477 {
478         ParticleRenderData *data= psys->renderdata;
479         float co[4], view[3], ortho1[3], ortho2[3], w, dx, dy, radius;
480         
481         /* transform to view space */
482         VECCOPY(co, center);
483         co[3]= 1.0f;
484         Mat4MulVec4fl(data->viewmat, co);
485         
486         /* compute two vectors orthogonal to view vector */
487         VECCOPY(view, co);
488         Normalize(view);
489         VecOrthoBasisf(view, ortho1, ortho2);
490
491         /* compute on screen minification */
492         w= co[2]*data->winmat[2][3] + data->winmat[3][3];
493         dx= data->winx*ortho2[0]*data->winmat[0][0];
494         dy= data->winy*ortho2[1]*data->winmat[1][1];
495         w= sqrt(dx*dx + dy*dy)/w;
496
497         /* w squared because we are working with area */
498         area= area*w*w;
499
500         /* viewport of the screen test */
501
502         /* project point on screen */
503         Mat4MulVec4fl(data->winmat, co);
504         if(co[3] != 0.0f) {
505                 co[0]= 0.5f*data->winx*(1.0f + co[0]/co[3]);
506                 co[1]= 0.5f*data->winy*(1.0f + co[1]/co[3]);
507         }
508
509         /* screen space radius */
510         radius= sqrt(area/M_PI);
511
512         /* make smaller using fallof once over screen edge */
513         *viewport= 1.0f;
514
515         if(co[0]+radius < 0.0f)
516                 *viewport *= psys_render_viewport_falloff(vprate, -(co[0]+radius), data->winx);
517         else if(co[0]-radius > data->winx)
518                 *viewport *= psys_render_viewport_falloff(vprate, (co[0]-radius) - data->winx, data->winx);
519
520         if(co[1]+radius < 0.0f)
521                 *viewport *= psys_render_viewport_falloff(vprate, -(co[1]+radius), data->winy);
522         else if(co[1]-radius > data->winy)
523                 *viewport *= psys_render_viewport_falloff(vprate, (co[1]-radius) - data->winy, data->winy);
524         
525         return area;
526 }
527
528 void psys_render_set(Object *ob, ParticleSystem *psys, float viewmat[][4], float winmat[][4], int winx, int winy, int timeoffset)
529 {
530         ParticleRenderData*data;
531         ParticleSystemModifierData *psmd= psys_get_modifier(ob, psys);
532
533         if(!G.rendering)
534                 return;
535         if(psys->renderdata)
536                 return;
537
538         data= MEM_callocN(sizeof(ParticleRenderData), "ParticleRenderData");
539
540         data->child= psys->child;
541         data->totchild= psys->totchild;
542         data->pathcache= psys->pathcache;
543         data->totcached= psys->totcached;
544         data->childcache= psys->childcache;
545         data->totchildcache= psys->totchildcache;
546
547         if(psmd->dm)
548                 data->dm= CDDM_copy(psmd->dm);
549         data->totdmvert= psmd->totdmvert;
550         data->totdmedge= psmd->totdmedge;
551         data->totdmface= psmd->totdmface;
552
553         psys->child= NULL;
554         psys->pathcache= NULL;
555         psys->childcache= NULL;
556         psys->totchild= psys->totcached= psys->totchildcache= 0;
557
558         Mat4CpyMat4(data->winmat, winmat);
559         Mat4MulMat4(data->viewmat, ob->obmat, viewmat);
560         Mat4MulMat4(data->mat, data->viewmat, winmat);
561         data->winx= winx;
562         data->winy= winy;
563
564         data->timeoffset= timeoffset;
565
566         psys->renderdata= data;
567 }
568
569 void psys_render_restore(Object *ob, ParticleSystem *psys)
570 {
571         ParticleRenderData*data;
572         ParticleSystemModifierData *psmd= psys_get_modifier(ob, psys);
573
574         data= psys->renderdata;
575         if(!data)
576                 return;
577         
578         if(data->elems)
579                 MEM_freeN(data->elems);
580
581         if(psmd->dm) {
582                 psmd->dm->needsFree= 1;
583                 psmd->dm->release(psmd->dm);
584         }
585
586         psys_free_path_cache(psys);
587
588         if(psys->child){
589                 MEM_freeN(psys->child);
590                 psys->child= 0;
591                 psys->totchild= 0;
592         }
593
594         psys->child= data->child;
595         psys->totchild= data->totchild;
596         psys->pathcache= data->pathcache;
597         psys->totcached= data->totcached;
598         psys->childcache= data->childcache;
599         psys->totchildcache= data->totchildcache;
600
601         psmd->dm= data->dm;
602         psmd->totdmvert= data->totdmvert;
603         psmd->totdmedge= data->totdmedge;
604         psmd->totdmface= data->totdmface;
605         psmd->flag &= ~eParticleSystemFlag_psys_updated;
606
607         if(psmd->dm)
608                 psys_calc_dmcache(ob, psmd->dm, psys);
609
610         MEM_freeN(data);
611         psys->renderdata= NULL;
612 }
613
614 int psys_render_simplify_distribution(ParticleThreadContext *ctx, int tot)
615 {
616         DerivedMesh *dm= ctx->dm;
617         Mesh *me= (Mesh*)(ctx->ob->data);
618         MFace *mf, *mface;
619         MVert *mvert;
620         ParticleRenderData *data;
621         ParticleRenderElem *elems, *elem;
622         ParticleSettings *part= ctx->psys->part;
623         float *facearea, (*facecenter)[3], size[3], fac, powrate, scaleclamp;
624         float co1[3], co2[3], co3[3], co4[3], lambda, arearatio, t, area, viewport;
625         double vprate;
626         int *origindex, *facetotvert;
627         int a, b, totorigface, totface, newtot, skipped;
628
629         if(part->draw_as!=PART_DRAW_PATH || !(part->draw & PART_DRAW_REN_STRAND))
630                 return tot;
631         if(!ctx->psys->renderdata)
632                 return tot;
633
634         data= ctx->psys->renderdata;
635         if(data->timeoffset)
636                 return 0;
637         if(!(part->simplify_flag & PART_SIMPLIFY_ENABLE))
638                 return tot;
639
640         mvert= dm->getVertArray(dm);
641         mface= dm->getFaceArray(dm);
642         origindex= dm->getFaceDataArray(dm, CD_ORIGINDEX);
643         totface= dm->getNumFaces(dm);
644         totorigface= me->totface;
645
646         if(totface == 0 || totorigface == 0 || origindex == NULL)
647                 return tot;
648
649         facearea= MEM_callocN(sizeof(float)*totorigface, "SimplifyFaceArea");
650         facecenter= MEM_callocN(sizeof(float[3])*totorigface, "SimplifyFaceCenter");
651         facetotvert= MEM_callocN(sizeof(int)*totorigface, "SimplifyFaceArea");
652         elems= MEM_callocN(sizeof(ParticleRenderElem)*totorigface, "SimplifyFaceElem");
653
654         if(data->elems)
655                 MEM_freeN(data->elems);
656
657         data->dosimplify= 1;
658         data->elems= elems;
659         data->origindex= origindex;
660
661         /* compute number of children per original face */
662         for(a=0; a<tot; a++) {
663                 b= origindex[ctx->index[a]];
664                 if(b != -1)
665                         elems[b].totchild++;
666         }
667
668         /* compute areas and centers of original faces */
669         for(mf=mface, a=0; a<totface; a++, mf++) {
670                 b= origindex[a];
671
672                 if(b != -1) {
673                         VECCOPY(co1, mvert[mf->v1].co);
674                         VECCOPY(co2, mvert[mf->v2].co);
675                         VECCOPY(co3, mvert[mf->v3].co);
676
677                         VECADD(facecenter[b], facecenter[b], co1);
678                         VECADD(facecenter[b], facecenter[b], co2);
679                         VECADD(facecenter[b], facecenter[b], co3);
680
681                         if(mf->v4) {
682                                 VECCOPY(co4, mvert[mf->v4].co);
683                                 VECADD(facecenter[b], facecenter[b], co4);
684                                 facearea[b] += AreaQ3Dfl(co1, co2, co3, co4);
685                                 facetotvert[b] += 4;
686                         }
687                         else {
688                                 facearea[b] += AreaT3Dfl(co1, co2, co3);
689                                 facetotvert[b] += 3;
690                         }
691                 }
692         }
693
694         for(a=0; a<totorigface; a++)
695                 if(facetotvert[a] > 0)
696                         VecMulf(facecenter[a], 1.0f/facetotvert[a]);
697
698         /* for conversion from BU area / pixel area to reference screen size */
699         mesh_get_texspace(me, 0, 0, size);
700         fac= ((size[0] + size[1] + size[2])/3.0f)/part->simplify_refsize;
701         fac= fac*fac;
702
703         powrate= log(0.5f)/log(part->simplify_rate*0.5f);
704         if(part->simplify_flag & PART_SIMPLIFY_VIEWPORT)
705                 vprate= pow(1.0 - part->simplify_viewport, 5.0);
706         else
707                 vprate= 1.0;
708
709         /* set simplification parameters per original face */
710         for(a=0, elem=elems; a<totorigface; a++, elem++) {
711                 area = psys_render_projected_area(ctx->psys, facecenter[a], facearea[a], vprate, &viewport);
712                 arearatio= fac*area/facearea[a];
713
714                 if((arearatio < 1.0f || viewport < 1.0f) && elem->totchild) {
715                         /* lambda is percentage of elements to keep */
716                         lambda= (arearatio < 1.0f)? pow(arearatio, powrate): 1.0f;
717                         lambda *= viewport;
718
719                         lambda= MAX2(lambda, 1.0f/elem->totchild);
720
721                         /* compute transition region */
722                         t= part->simplify_transition;
723                         elem->t= (lambda-t < 0.0f)? lambda: (lambda+t > 1.0f)? 1.0f-lambda: t;
724                         elem->reduce= 1;
725
726                         /* scale at end and beginning of the transition region */
727                         elem->scalemax= (lambda+t < 1.0f)? 1.0f/lambda: 1.0f/(1.0f - elem->t*elem->t/t);
728                         elem->scalemin= (lambda+t < 1.0f)? 0.0f: elem->scalemax*(1.0f-elem->t/t);
729
730                         elem->scalemin= sqrt(elem->scalemin);
731                         elem->scalemax= sqrt(elem->scalemax);
732
733                         /* clamp scaling */
734                         scaleclamp= MIN2(elem->totchild, 10.0f);
735                         elem->scalemin= MIN2(scaleclamp, elem->scalemin);
736                         elem->scalemax= MIN2(scaleclamp, elem->scalemax);
737
738                         /* extend lambda to include transition */
739                         lambda= lambda + elem->t;
740                         if(lambda > 1.0f)
741                                 lambda= 1.0f;
742                 }
743                 else {
744                         lambda= arearatio;
745
746                         elem->scalemax= 1.0f; //sqrt(lambda);
747                         elem->scalemin= 1.0f; //sqrt(lambda);
748                         elem->reduce= 0;
749                 }
750
751                 elem->lambda= lambda;
752                 elem->scalemin= sqrt(elem->scalemin);
753                 elem->scalemax= sqrt(elem->scalemax);
754                 elem->curchild= 0;
755         }
756
757         MEM_freeN(facearea);
758         MEM_freeN(facecenter);
759         MEM_freeN(facetotvert);
760
761         /* move indices and set random number skipping */
762         ctx->skip= MEM_callocN(sizeof(int)*tot, "SimplificationSkip");
763
764         skipped= 0;
765         for(a=0, newtot=0; a<tot; a++) {
766                 b= origindex[ctx->index[a]];
767                 if(b != -1) {
768                         if(elems[b].curchild++ < ceil(elems[b].lambda*elems[b].totchild)) {
769                                 ctx->index[newtot]= ctx->index[a];
770                                 ctx->skip[newtot]= skipped;
771                                 skipped= 0;
772                                 newtot++;
773                         }
774                         else skipped++;
775                 }
776                 else skipped++;
777         }
778
779         for(a=0, elem=elems; a<totorigface; a++, elem++)
780                 elem->curchild= 0;
781
782         return newtot;
783 }
784
785 int psys_render_simplify_params(ParticleSystem *psys, ChildParticle *cpa, float *params)
786 {
787         ParticleRenderData *data;
788         ParticleRenderElem *elem;
789         float x, w, scale, alpha, lambda, t, scalemin, scalemax;
790         int b;
791
792         if(!(psys->renderdata && (psys->part->simplify_flag & PART_SIMPLIFY_ENABLE)))
793                 return 0;
794         
795         data= psys->renderdata;
796         if(!data->dosimplify)
797                 return 0;
798         
799         b= data->origindex[cpa->num];
800         if(b == -1)
801                 return 0;
802
803         elem= &data->elems[b];
804
805         lambda= elem->lambda;
806         t= elem->t;
807         scalemin= elem->scalemin;
808         scalemax= elem->scalemax;
809
810         if(!elem->reduce) {
811                 scale= scalemin;
812                 alpha= 1.0f;
813         }
814         else {
815                 x= (elem->curchild+0.5f)/elem->totchild;
816                 if(x < lambda-t) {
817                         scale= scalemax;
818                         alpha= 1.0f;
819                 }
820                 else if(x >= lambda+t) {
821                         scale= scalemin;
822                         alpha= 0.0f;
823                 }
824                 else {
825                         w= (lambda+t - x)/(2.0f*t);
826                         scale= scalemin + (scalemax - scalemin)*w;
827                         alpha= w;
828                 }
829         }
830
831         params[0]= scale;
832         params[1]= alpha;
833
834         elem->curchild++;
835
836         return 1;
837 }
838
839 /************************************************/
840 /*                      Interpolated Particles                          */
841 /************************************************/
842 static float interpolate_particle_value(float v1, float v2, float v3, float v4, float *w, int four)
843 {
844         float value;
845
846         value= w[0]*v1 + w[1]*v2 + w[2]*v3;
847         if(four)
848                 value += w[3]*v4;
849         
850         return value;
851 }
852 static void weighted_particle_vector(float *v1, float *v2, float *v3, float *v4, float *weights, float *vec)
853 {
854         vec[0]= weights[0]*v1[0] + weights[1]*v2[0] + weights[2]*v3[0] + weights[3]*v4[0];
855         vec[1]= weights[0]*v1[1] + weights[1]*v2[1] + weights[2]*v3[1] + weights[3]*v4[1];
856         vec[2]= weights[0]*v1[2] + weights[1]*v2[2] + weights[2]*v3[2] + weights[3]*v4[2];
857 }
858 static void interpolate_particle(short type, ParticleKey keys[4], float dt, ParticleKey *result, int velocity)
859 {
860         float t[4];
861
862         if(type<0) {
863                 VecfCubicInterpol(keys[1].co, keys[1].vel, keys[2].co, keys[2].vel, dt, result->co, result->vel);
864         }
865         else {
866                 set_four_ipo(dt, t, type);
867
868                 weighted_particle_vector(keys[0].co, keys[1].co, keys[2].co, keys[3].co, t, result->co);
869
870                 if(velocity){
871                         float temp[3];
872
873                         if(dt>0.999f){
874                                 set_four_ipo(dt-0.001f, t, type);
875                                 weighted_particle_vector(keys[0].co, keys[1].co, keys[2].co, keys[3].co, t, temp);
876                                 VECSUB(result->vel, result->co, temp);
877                         }
878                         else{
879                                 set_four_ipo(dt+0.001f, t, type);
880                                 weighted_particle_vector(keys[0].co, keys[1].co, keys[2].co, keys[3].co, t, temp);
881                                 VECSUB(result->vel, temp, result->co);
882                         }
883                 }
884         }
885 }
886
887
888
889 /************************************************/
890 /*                      Particles on a dm                                       */
891 /************************************************/
892 /* interpolate a location on a face based on face coordinates */
893 void psys_interpolate_face(MVert *mvert, MFace *mface, MTFace *tface, float (*orcodata)[3], float *w, float *vec, float *nor, float *utan, float *vtan, float *orco,float *ornor){
894         float *v1=0, *v2=0, *v3=0, *v4=0;
895         float e1[3],e2[3],s1,s2,t1,t2;
896         float *uv1, *uv2, *uv3, *uv4;
897         float n1[3], n2[3], n3[3], n4[3];
898         float tuv[4][2];
899         float *o1, *o2, *o3, *o4;
900
901         v1= (mvert+mface->v1)->co;
902         v2= (mvert+mface->v2)->co;
903         v3= (mvert+mface->v3)->co;
904         VECCOPY(n1,(mvert+mface->v1)->no);
905         VECCOPY(n2,(mvert+mface->v2)->no);
906         VECCOPY(n3,(mvert+mface->v3)->no);
907         Normalize(n1);
908         Normalize(n2);
909         Normalize(n3);
910
911         if(mface->v4) {
912                 v4= (mvert+mface->v4)->co;
913                 VECCOPY(n4,(mvert+mface->v4)->no);
914                 Normalize(n4);
915                 
916                 vec[0]= w[0]*v1[0] + w[1]*v2[0] + w[2]*v3[0] + w[3]*v4[0];
917                 vec[1]= w[0]*v1[1] + w[1]*v2[1] + w[2]*v3[1] + w[3]*v4[1];
918                 vec[2]= w[0]*v1[2] + w[1]*v2[2] + w[2]*v3[2] + w[3]*v4[2];
919
920                 if(nor){
921                         if(mface->flag & ME_SMOOTH){
922                                 nor[0]= w[0]*n1[0] + w[1]*n2[0] + w[2]*n3[0] + w[3]*n4[0];
923                                 nor[1]= w[0]*n1[1] + w[1]*n2[1] + w[2]*n3[1] + w[3]*n4[1];
924                                 nor[2]= w[0]*n1[2] + w[1]*n2[2] + w[2]*n3[2] + w[3]*n4[2];
925                         }
926                         else
927                                 CalcNormFloat4(v1,v2,v3,v4,nor);
928                 }
929         }
930         else {
931                 vec[0]= w[0]*v1[0] + w[1]*v2[0] + w[2]*v3[0];
932                 vec[1]= w[0]*v1[1] + w[1]*v2[1] + w[2]*v3[1];
933                 vec[2]= w[0]*v1[2] + w[1]*v2[2] + w[2]*v3[2];
934                 
935                 if(nor){
936                         if(mface->flag & ME_SMOOTH){
937                                 nor[0]= w[0]*n1[0] + w[1]*n2[0] + w[2]*n3[0];
938                                 nor[1]= w[0]*n1[1] + w[1]*n2[1] + w[2]*n3[1];
939                                 nor[2]= w[0]*n1[2] + w[1]*n2[2] + w[2]*n3[2];
940                         }
941                         else
942                                 CalcNormFloat(v1,v2,v3,nor);
943                 }
944         }
945         
946         /* calculate tangent vectors */
947         if(utan && vtan){
948                 if(tface){
949                         uv1= tface->uv[0];
950                         uv2= tface->uv[1];
951                         uv3= tface->uv[2];
952                         uv4= tface->uv[3];
953                 }
954                 else{
955                         uv1= tuv[0]; uv2= tuv[1]; uv3= tuv[2]; uv4= tuv[3];
956                         spheremap(v1[0], v1[1], v1[2], uv1, uv1+1);
957                         spheremap(v2[0], v2[1], v2[2], uv2, uv2+1);
958                         spheremap(v3[0], v3[1], v3[2], uv3, uv3+1);
959                         if(v4)
960                                 spheremap(v4[0], v4[1], v4[2], uv4, uv4+1);
961                 }
962
963                 if(v4){
964                         s1= uv3[0] - uv1[0];
965                         s2= uv4[0] - uv1[0];
966
967                         t1= uv3[1] - uv1[1];
968                         t2= uv4[1] - uv1[1];
969
970                         VecSubf(e1, v3, v1);
971                         VecSubf(e2, v4, v1);
972                 }
973                 else{
974                         s1= uv2[0] - uv1[0];
975                         s2= uv3[0] - uv1[0];
976
977                         t1= uv2[1] - uv1[1];
978                         t2= uv3[1] - uv1[1];
979
980                         VecSubf(e1, v2, v1);
981                         VecSubf(e2, v3, v1);
982                 }
983
984                 vtan[0] = (s1*e2[0] - s2*e1[0]);
985                 vtan[1] = (s1*e2[1] - s2*e1[1]);
986                 vtan[2] = (s1*e2[2] - s2*e1[2]);
987
988                 utan[0] = (t1*e2[0] - t2*e1[0]);
989                 utan[1] = (t1*e2[1] - t2*e1[1]);
990                 utan[2] = (t1*e2[2] - t2*e1[2]);
991         }
992
993         if(orco) {
994                 if(orcodata) {
995                         o1= orcodata[mface->v1];
996                         o2= orcodata[mface->v2];
997                         o3= orcodata[mface->v3];
998
999                         if(mface->v4) {
1000                                 o4= orcodata[mface->v4];
1001                                 orco[0]= w[0]*o1[0] + w[1]*o2[0] + w[2]*o3[0] + w[3]*o4[0];
1002                                 orco[1]= w[0]*o1[1] + w[1]*o2[1] + w[2]*o3[1] + w[3]*o4[1];
1003                                 orco[2]= w[0]*o1[2] + w[1]*o2[2] + w[2]*o3[2] + w[3]*o4[2];
1004
1005                                 if(ornor)
1006                                         CalcNormFloat4(o1, o2, o3, o4, ornor);
1007                         }
1008                         else {
1009                                 orco[0]= w[0]*o1[0] + w[1]*o2[0] + w[2]*o3[0];
1010                                 orco[1]= w[0]*o1[1] + w[1]*o2[1] + w[2]*o3[1];
1011                                 orco[2]= w[0]*o1[2] + w[1]*o2[2] + w[2]*o3[2];
1012
1013                                 if(ornor)
1014                                         CalcNormFloat(o1, o2, o3, ornor);
1015                         }
1016                 }
1017                 else {
1018                         VECCOPY(orco, vec);
1019                         if(ornor)
1020                                 VECCOPY(ornor, nor);
1021                 }
1022         }
1023 }
1024 void psys_interpolate_uvs(MTFace *tface, int quad, float *w, float *uvco)
1025 {
1026         float v10= tface->uv[0][0];
1027         float v11= tface->uv[0][1];
1028         float v20= tface->uv[1][0];
1029         float v21= tface->uv[1][1];
1030         float v30= tface->uv[2][0];
1031         float v31= tface->uv[2][1];
1032         float v40,v41;
1033
1034         if(quad) {
1035                 v40= tface->uv[3][0];
1036                 v41= tface->uv[3][1];
1037
1038                 uvco[0]= w[0]*v10 + w[1]*v20 + w[2]*v30 + w[3]*v40;
1039                 uvco[1]= w[0]*v11 + w[1]*v21 + w[2]*v31 + w[3]*v41;
1040         }
1041         else {
1042                 uvco[0]= w[0]*v10 + w[1]*v20 + w[2]*v30;
1043                 uvco[1]= w[0]*v11 + w[1]*v21 + w[2]*v31;
1044         }
1045 }
1046
1047 void psys_interpolate_mcol(MCol *mcol, int quad, float *w, MCol *mc)
1048 {
1049         char *cp, *cp1, *cp2, *cp3, *cp4;
1050
1051         cp= (char *)mc;
1052         cp1= (char *)&mcol[0];
1053         cp2= (char *)&mcol[1];
1054         cp3= (char *)&mcol[2];
1055         
1056         if(quad) {
1057                 cp4= (char *)&mcol[3];
1058
1059                 cp[0]= (int)(w[0]*cp1[0] + w[1]*cp2[0] + w[2]*cp3[0] + w[3]*cp4[0]);
1060                 cp[1]= (int)(w[0]*cp1[1] + w[1]*cp2[1] + w[2]*cp3[1] + w[3]*cp4[1]);
1061                 cp[2]= (int)(w[0]*cp1[2] + w[1]*cp2[2] + w[2]*cp3[2] + w[3]*cp4[2]);
1062                 cp[3]= (int)(w[0]*cp1[3] + w[1]*cp2[3] + w[2]*cp3[3] + w[3]*cp4[3]);
1063         }
1064         else {
1065                 cp[0]= (int)(w[0]*cp1[0] + w[1]*cp2[0] + w[2]*cp3[0]);
1066                 cp[1]= (int)(w[0]*cp1[1] + w[1]*cp2[1] + w[2]*cp3[1]);
1067                 cp[2]= (int)(w[0]*cp1[2] + w[1]*cp2[2] + w[2]*cp3[2]);
1068                 cp[3]= (int)(w[0]*cp1[3] + w[1]*cp2[3] + w[2]*cp3[3]);
1069         }
1070 }
1071
1072 float psys_interpolate_value_from_verts(DerivedMesh *dm, short from, int index, float *fw, float *values)
1073 {
1074         if(values==0 || index==-1)
1075                 return 0.0;
1076
1077         switch(from){
1078                 case PART_FROM_VERT:
1079                         return values[index];
1080                 case PART_FROM_FACE:
1081                 case PART_FROM_VOLUME:
1082                 {
1083                         MFace *mf=dm->getFaceData(dm,index,CD_MFACE);
1084                         return interpolate_particle_value(values[mf->v1],values[mf->v2],values[mf->v3],values[mf->v4],fw,mf->v4);
1085                 }
1086                         
1087         }
1088         return 0.0;
1089 }
1090
1091 /* conversion of pa->fw to origspace layer coordinates */
1092 static void psys_w_to_origspace(float *w, float *uv)
1093 {
1094         uv[0]= w[1] + w[2];
1095         uv[1]= w[2] + w[3];
1096 }
1097
1098 /* conversion of pa->fw to weights in face from origspace */
1099 static void psys_origspace_to_w(OrigSpaceFace *osface, int quad, float *w, float *neww)
1100 {
1101         float v[4][3], co[3];
1102
1103         v[0][0]= osface->uv[0][0]; v[0][1]= osface->uv[0][1]; v[0][2]= 0.0f;
1104         v[1][0]= osface->uv[1][0]; v[1][1]= osface->uv[1][1]; v[1][2]= 0.0f;
1105         v[2][0]= osface->uv[2][0]; v[2][1]= osface->uv[2][1]; v[2][2]= 0.0f;
1106
1107         psys_w_to_origspace(w, co);
1108         co[2]= 0.0f;
1109         
1110         if(quad) {
1111                 v[3][0]= osface->uv[3][0]; v[3][1]= osface->uv[3][1]; v[3][2]= 0.0f;
1112                 MeanValueWeights(v, 4, co, neww);
1113         }
1114         else {
1115                 MeanValueWeights(v, 3, co, neww);
1116                 neww[3]= 0.0f;
1117         }
1118 }
1119
1120 /* find the derived mesh face for a particle, set the mf passed.
1121 This is slow, can be optimized but only for many lookups, return the face lookup index*/
1122 int psys_particle_dm_face_lookup(Object *ob, DerivedMesh *dm, int index, float *fw, struct LinkNode *node)
1123 {
1124         Mesh *me= (Mesh*)ob->data;
1125         MFace *mface;
1126         OrigSpaceFace *osface;
1127         int *origindex;
1128         int quad, findex, totface;
1129         float uv[2], (*faceuv)[2];
1130
1131         mface = dm->getFaceDataArray(dm, CD_MFACE);
1132         origindex = dm->getFaceDataArray(dm, CD_ORIGINDEX);
1133         osface = dm->getFaceDataArray(dm, CD_ORIGSPACE);
1134
1135         totface = dm->getNumFaces(dm);
1136         
1137         if(osface==NULL || origindex==NULL) {
1138                 /* Assume we dont need osface data */
1139                 if (index <totface) {
1140                         //printf("\tNO CD_ORIGSPACE, assuming not needed\n");
1141                         return index;
1142                 } else {
1143                         printf("\tNO CD_ORIGSPACE, error out of range\n");
1144                         return DMCACHE_NOTFOUND;
1145                 }
1146         }
1147         else if(index >= me->totface)
1148                 return DMCACHE_NOTFOUND; /* index not in the original mesh */
1149
1150         psys_w_to_origspace(fw, uv);
1151         
1152         if(node) { /* we have a linked list of faces that we use, faster! */
1153                 for(;node; node=node->next) {
1154                         findex= GET_INT_FROM_POINTER(node->link);
1155                         faceuv= osface[findex].uv;
1156                         quad= mface[findex].v4;
1157
1158                         /* check that this intersects - Its possible this misses :/ -
1159                          * could also check its not between */
1160                         if(quad) {
1161                                 if(IsectPQ2Df(uv, faceuv[0], faceuv[1], faceuv[2], faceuv[3]))
1162                                         return findex;
1163                         }
1164                         else if(IsectPT2Df(uv, faceuv[0], faceuv[1], faceuv[2]))
1165                                 return findex;
1166                 }
1167         }
1168         else { /* if we have no node, try every face */
1169                 for(findex=0; findex<totface; findex++) {
1170                         if(origindex[findex] == index) {
1171                                 faceuv= osface[findex].uv;
1172                                 quad= mface[findex].v4;
1173
1174                                 /* check that this intersects - Its possible this misses :/ -
1175                                  * could also check its not between */
1176                                 if(quad) {
1177                                         if(IsectPQ2Df(uv, faceuv[0], faceuv[1], faceuv[2], faceuv[3]))
1178                                                 return findex;
1179                                 }
1180                                 else if(IsectPT2Df(uv, faceuv[0], faceuv[1], faceuv[2]))
1181                                         return findex;
1182                         }
1183                 }
1184         }
1185
1186         return DMCACHE_NOTFOUND;
1187 }
1188
1189 /* interprets particle data to get a point on a mesh in object space */
1190 #define PARTICLE_ON_DM_ERROR \
1191         { if(vec) { vec[0]=vec[1]=vec[2]=0.0; } \
1192           if(nor) { nor[0]=nor[1]=0.0; nor[2]=1.0; } \
1193           if(orco) { orco[0]=orco[1]=orco[2]=0.0; } \
1194           if(ornor) { ornor[0]=ornor[1]=0.0; ornor[2]=1.0; } \
1195           if(utan) { utan[0]=utan[1]=utan[2]=0.0; } \
1196           if(vtan) { vtan[0]=vtan[1]=vtan[2]=0.0; } }
1197
1198 void psys_particle_on_dm(Object *ob, DerivedMesh *dm, int from, int index, int index_dmcache, float *fw, float foffset, float *vec, float *nor, float *utan, float *vtan, float *orco, float *ornor)
1199 {
1200         float temp1[3];
1201         float (*orcodata)[3];
1202
1203         if(index < 0) { /* 'no dm' error has happened! */
1204                 PARTICLE_ON_DM_ERROR;
1205                 return;
1206         }
1207         orcodata= dm->getVertDataArray(dm, CD_ORCO);
1208
1209         if (dm->deformedOnly || index_dmcache == DMCACHE_ISCHILD) {
1210                 /* this works for meshes with deform verts only - constructive modifiers wont work properly*/
1211                 if(from == PART_FROM_VERT) {
1212                         if(index >= dm->getNumVerts(dm)) {
1213                                 PARTICLE_ON_DM_ERROR;
1214                                 return;
1215                         }
1216         
1217                         dm->getVertCo(dm,index,vec);
1218                         if(nor){
1219                                 dm->getVertNo(dm,index,nor);
1220                                 Normalize(nor);
1221                         }
1222                         if(orco)
1223                                 VECCOPY(orco, orcodata[index])
1224                         if(ornor) {
1225                                 dm->getVertNo(dm,index,nor);
1226                                 Normalize(nor);
1227                         }
1228                 }
1229                 else { /* PART_FROM_FACE / PART_FROM_VOLUME */
1230                         MFace *mface;
1231                         MTFace *mtface=0;
1232                         MVert *mvert;
1233                         int uv_index;
1234
1235                         if(index >= dm->getNumFaces(dm)) {
1236                                 PARTICLE_ON_DM_ERROR;
1237                                 return;
1238                         }
1239                         
1240                         mface=dm->getFaceData(dm,index,CD_MFACE);
1241                         mvert=dm->getVertDataArray(dm,CD_MVERT);
1242                         uv_index=CustomData_get_active_layer_index(&dm->faceData,CD_MTFACE);
1243
1244                         if(uv_index>=0){
1245                                 CustomDataLayer *layer=&dm->faceData.layers[uv_index];
1246                                 mtface= &((MTFace*)layer->data)[index];
1247                         }
1248
1249                         if(from==PART_FROM_VOLUME){
1250                                 psys_interpolate_face(mvert,mface,mtface,orcodata,fw,vec,temp1,utan,vtan,orco,ornor);
1251                                 if(nor)
1252                                         VECCOPY(nor,temp1);
1253                                 Normalize(temp1);
1254                                 VecMulf(temp1,-foffset);
1255                                 VECADD(vec,vec,temp1);
1256                         }
1257                         else
1258                                 psys_interpolate_face(mvert,mface,mtface,orcodata,fw,vec,nor,utan,vtan,orco,ornor);
1259                 }
1260         } else {
1261                 /* Need to support constructive modifiers, this is a bit more tricky
1262                         we need a customdata layer like UV's so we can position the particle */
1263                 
1264                 /* Only face supported at the moment */
1265                 if(ELEM(from, PART_FROM_FACE, PART_FROM_VOLUME)) {
1266                         /* find a face on the derived mesh that uses this face */
1267                         Mesh *me= (Mesh*)ob->data;
1268                         MVert *mvert;
1269                         MFace *mface;
1270                         MTFace *mtface;
1271                         OrigSpaceFace *osface;
1272                         int *origindex;
1273                         float fw_mod[4];
1274                         int i, totface;
1275                         
1276                         mvert= dm->getVertDataArray(dm,CD_MVERT);
1277
1278                         osface= dm->getFaceDataArray(dm, CD_ORIGSPACE);
1279                         origindex= dm->getFaceDataArray(dm, CD_ORIGINDEX);
1280
1281                         /* For this to work we need origindex and OrigSpace coords */
1282                         if(origindex==NULL || osface==NULL || index>=me->totface) {
1283                                 PARTICLE_ON_DM_ERROR;
1284                                 return;
1285                         }
1286                         
1287                         if (index_dmcache == DMCACHE_NOTFOUND)
1288                                 i = psys_particle_dm_face_lookup(ob, dm, index, fw, (LinkNode*)NULL);
1289                         else
1290                                 i = index_dmcache;
1291
1292                         totface = dm->getNumFaces(dm);
1293
1294                         /* Any time this happens, and the face has not been removed,
1295                         * its a BUG watch out for this error! */
1296                         if (i==-1) {
1297                                 printf("Cannot find original face %i\n", index);
1298                                 PARTICLE_ON_DM_ERROR;
1299                                 return;
1300                         }
1301                         else if(i >= totface)
1302                                 return;
1303
1304                         mface= dm->getFaceData(dm, i, CD_MFACE);
1305                         mtface= dm->getFaceData(dm, i, CD_MTFACE); 
1306                         osface += i;
1307
1308                         /* we need to modify the original weights to become weights for
1309                          * the derived mesh face */
1310                         psys_origspace_to_w(osface, mface->v4, fw, fw_mod);
1311
1312                         if(from==PART_FROM_VOLUME){
1313                                 psys_interpolate_face(mvert,mface,mtface,orcodata,fw_mod,vec,temp1,utan,vtan,orco,ornor);
1314                                 if(nor)
1315                                         VECCOPY(nor,temp1);
1316                                 Normalize(temp1);
1317                                 VecMulf(temp1,-foffset);
1318                                 VECADD(vec,vec,temp1);
1319                         }
1320                         else
1321                                 psys_interpolate_face(mvert,mface,mtface,orcodata,fw_mod,vec,nor,utan,vtan,orco,ornor);
1322                 }
1323                 else if(from == PART_FROM_VERT) {
1324                         if (index_dmcache == DMCACHE_NOTFOUND || index_dmcache > dm->getNumVerts(dm)) {
1325                                 PARTICLE_ON_DM_ERROR;
1326                                 return;
1327                         }
1328
1329                         dm->getVertCo(dm,index_dmcache,vec);
1330                         if(nor) {
1331                                 dm->getVertNo(dm,index_dmcache,nor);
1332                                 Normalize(nor);
1333                         }
1334                         if(orco)
1335                                 VECCOPY(orco, orcodata[index])
1336                         if(ornor) {
1337                                 dm->getVertNo(dm,index_dmcache,nor);
1338                                 Normalize(nor);
1339                         }
1340                         if(utan && vtan) {
1341                                 utan[0]= utan[1]= utan[2]= 0.0f;
1342                                 vtan[0]= vtan[1]= vtan[2]= 0.0f;
1343                         }
1344                 }
1345                 else {
1346                         PARTICLE_ON_DM_ERROR;
1347                 }
1348         }
1349 }
1350 #undef PARTICLE_ON_DM_ERROR
1351
1352 ParticleSystemModifierData *psys_get_modifier(Object *ob, ParticleSystem *psys)
1353 {
1354         ModifierData *md;
1355         ParticleSystemModifierData *psmd;
1356
1357         for(md=ob->modifiers.first; md; md=md->next){
1358                 if(md->type==eModifierType_ParticleSystem){
1359                         psmd= (ParticleSystemModifierData*) md;
1360                         if(psmd->psys==psys){
1361                                 return psmd;
1362                         }
1363                 }
1364         }
1365         return 0;
1366 }
1367 /************************************************/
1368 /*                      Particles on a shape                            */
1369 /************************************************/
1370 /* ready for future use */
1371 void psys_particle_on_shape(int distr, int index, float *fuv, float *vec, float *nor, float *utan, float *vtan, float *orco, float *ornor)
1372 {
1373         /* TODO */
1374         float zerovec[3]={0.0f,0.0f,0.0f};
1375         if(vec){
1376                 VECCOPY(vec,zerovec);
1377         }
1378         if(nor){
1379                 VECCOPY(nor,zerovec);
1380         }
1381         if(utan){
1382                 VECCOPY(utan,zerovec);
1383         }
1384         if(vtan){
1385                 VECCOPY(vtan,zerovec);
1386         }
1387         if(orco){
1388                 VECCOPY(orco,zerovec);
1389         }
1390         if(ornor){
1391                 VECCOPY(ornor,zerovec);
1392         }
1393 }
1394 /************************************************/
1395 /*                      Particles on emitter                            */
1396 /************************************************/
1397 void psys_particle_on_emitter(Object *ob, ParticleSystemModifierData *psmd, int from, int index, int index_dmcache, float *fuv, float foffset, float *vec, float *nor, float *utan, float *vtan, float *orco, float *ornor){
1398         if(psmd){
1399                 if(psmd->psys->part->distr==PART_DISTR_GRID && psmd->psys->part->from != PART_FROM_VERT){
1400                         if(vec){
1401                                 VECCOPY(vec,fuv);
1402                         }
1403                         return;
1404                 }
1405                 /* we cant use the num_dmcache */
1406                 psys_particle_on_dm(ob, psmd->dm,from,index,index_dmcache,fuv,foffset,vec,nor,utan,vtan,orco,ornor);
1407         }
1408         else
1409                 psys_particle_on_shape(from,index,fuv,vec,nor,utan,vtan,orco,ornor);
1410
1411 }
1412 /************************************************/
1413 /*                      Path Cache                                                      */
1414 /************************************************/
1415 static void hair_to_particle(ParticleKey *key, HairKey *hkey)
1416 {
1417         VECCOPY(key->co, hkey->co);
1418         key->time = hkey->time;
1419 }
1420 static void bp_to_particle(ParticleKey *key, BodyPoint *bp, HairKey *hkey)
1421 {
1422         VECCOPY(key->co, bp->pos);
1423         key->time = hkey->time;
1424 }
1425 static float vert_weight(MDeformVert *dvert, int group)
1426 {
1427         MDeformWeight *dw;
1428         int i;
1429         
1430         if(dvert) {
1431                 dw= dvert->dw;
1432                 for(i= dvert->totweight; i>0; i--, dw++) {
1433                         if(dw->def_nr == group) return dw->weight;
1434                         if(i==1) break; /*otherwise dw will point to somewhere it shouldn't*/
1435                 }
1436         }
1437         return 0.0;
1438 }
1439 static void do_prekink(ParticleKey *state, ParticleKey *par, float *par_rot, float time, float freq, float shape, float amplitude, short type, short axis, float obmat[][4])
1440 {
1441         float vec[3]={0.0,0.0,0.0}, q1[4]={1,0,0,0},q2[4];
1442         float t;
1443
1444         CLAMP(time,0.0,1.0);
1445
1446         if(shape!=0.0f && type!=PART_KINK_BRAID) {
1447                 if(shape<0.0f)
1448                         time= (float)pow(time, 1.0+shape);
1449                 else
1450                         time= (float)pow(time, 1.0/(1.0-shape));
1451         }
1452
1453         t=time;
1454
1455         t*=(float)M_PI*freq;
1456
1457         if(par==0) return;
1458
1459         switch(type){
1460                 case PART_KINK_CURL:
1461                         vec[axis]=1.0;
1462                         if(par_rot)
1463                                 QUATCOPY(q2,par_rot)
1464                         else
1465                                 vectoquat(par->vel,axis,(axis+1)%3, q2);
1466                         QuatMulVecf(q2,vec);
1467                         VecMulf(vec,amplitude);
1468                         VECADD(state->co,state->co,vec);
1469
1470                         VECSUB(vec,state->co,par->co);
1471
1472                         if(t!=0.0)
1473                                 VecRotToQuat(par->vel,t,q1);
1474                         
1475                         QuatMulVecf(q1,vec);
1476                         
1477                         VECADD(state->co,par->co,vec);
1478                         break;
1479                 case PART_KINK_RADIAL:
1480                         VECSUB(vec,state->co,par->co);
1481
1482                         Normalize(vec);
1483                         VecMulf(vec,amplitude*(float)sin(t));
1484
1485                         VECADD(state->co,state->co,vec);
1486                         break;
1487                 case PART_KINK_WAVE:
1488                         vec[axis]=1.0;
1489                         if(obmat)
1490                                 Mat4MulVecfl(obmat,vec);
1491
1492                         if(par_rot)
1493                                 QuatMulVecf(par_rot,vec);
1494
1495                         Projf(q1,vec,par->vel);
1496                         
1497                         VECSUB(vec,vec,q1);
1498                         Normalize(vec);
1499
1500                         VecMulf(vec,amplitude*(float)sin(t));
1501
1502                         VECADD(state->co,state->co,vec);
1503                         break;
1504                 case PART_KINK_BRAID:
1505                         if(par){
1506                                 float y_vec[3]={0.0,1.0,0.0};
1507                                 float z_vec[3]={0.0,0.0,1.0};
1508                                 float vec_from_par[3], vec_one[3], radius, state_co[3];
1509                                 float inp_y,inp_z,length;
1510                                 
1511                                 if(par_rot)
1512                                         QUATCOPY(q2,par_rot)
1513                                 else
1514                                         vectoquat(par->vel,axis,(axis+1)%3,q2);
1515                                 QuatMulVecf(q2,y_vec);
1516                                 QuatMulVecf(q2,z_vec);
1517                                 
1518                                 VECSUB(vec_from_par,state->co,par->co);
1519                                 VECCOPY(vec_one,vec_from_par);
1520                                 radius=Normalize(vec_one);
1521
1522                                 inp_y=Inpf(y_vec,vec_one);
1523                                 inp_z=Inpf(z_vec,vec_one);
1524
1525                                 if(inp_y>0.5){
1526                                         VECCOPY(state_co,y_vec);
1527
1528                                         VecMulf(y_vec,amplitude*(float)cos(t));
1529                                         VecMulf(z_vec,amplitude/2.0f*(float)sin(2.0f*t));
1530                                 }
1531                                 else if(inp_z>0.0){
1532                                         VECCOPY(state_co,z_vec);
1533                                         VecMulf(state_co,(float)sin(M_PI/3.0f));
1534                                         VECADDFAC(state_co,state_co,y_vec,-0.5f);
1535
1536                                         VecMulf(y_vec,-amplitude*(float)cos(t + M_PI/3.0f));
1537                                         VecMulf(z_vec,amplitude/2.0f*(float)cos(2.0f*t + M_PI/6.0f));
1538                                 }
1539                                 else{
1540                                         VECCOPY(state_co,z_vec);
1541                                         VecMulf(state_co,-(float)sin(M_PI/3.0f));
1542                                         VECADDFAC(state_co,state_co,y_vec,-0.5f);
1543
1544                                         VecMulf(y_vec,amplitude*(float)-sin(t+M_PI/6.0f));
1545                                         VecMulf(z_vec,amplitude/2.0f*(float)-sin(2.0f*t+M_PI/3.0f));
1546                                 }
1547
1548                                 VecMulf(state_co,amplitude);
1549                                 VECADD(state_co,state_co,par->co);
1550                                 VECSUB(vec_from_par,state->co,state_co);
1551
1552                                 length=Normalize(vec_from_par);
1553                                 VecMulf(vec_from_par,MIN2(length,amplitude/2.0f));
1554
1555                                 VECADD(state_co,par->co,y_vec);
1556                                 VECADD(state_co,state_co,z_vec);
1557                                 VECADD(state_co,state_co,vec_from_par);
1558
1559                                 shape=(2.0f*(float)M_PI)*(1.0f+shape);
1560
1561                                 if(t<shape){
1562                                         shape=t/shape;
1563                                         shape=(float)sqrt((double)shape);
1564                                         VecLerpf(state->co,state->co,state_co,shape);
1565                                 }
1566                                 else{
1567                                         VECCOPY(state->co,state_co);
1568                                 }
1569                         }
1570                         break;
1571         }
1572 }
1573 static void do_clump(ParticleKey *state, ParticleKey *par, float time, float clumpfac, float clumppow, float pa_clump)
1574 {
1575         if(par && clumpfac!=0.0){
1576                 float clump, cpow;
1577
1578                 if(clumppow<0.0)
1579                         cpow=1.0f+clumppow;
1580                 else
1581                         cpow=1.0f+9.0f*clumppow;
1582
1583                 if(clumpfac<0.0) /* clump roots instead of tips */
1584                         clump = -clumpfac*pa_clump*(float)pow(1.0-(double)time,(double)cpow);
1585                 else
1586                         clump = clumpfac*pa_clump*(float)pow((double)time,(double)cpow);
1587                 VecLerpf(state->co,state->co,par->co,clump);
1588         }
1589 }
1590 int do_guide(ParticleKey *state, int pa_num, float time, ListBase *lb)
1591 {
1592         PartDeflect *pd;
1593         ParticleEffectorCache *ec;
1594         Object *eob;
1595         Curve *cu;
1596         ParticleKey key, par;
1597
1598         float effect[3]={0.0,0.0,0.0}, distance, f_force, mindist, totforce=0.0;
1599         float guidevec[4], guidedir[3], rot2[4], temp[3], angle, pa_loc[3], pa_zero[3]={0.0f,0.0f,0.0f};
1600         float veffect[3]={0.0,0.0,0.0}, guidetime;
1601
1602         effect[0]=effect[1]=effect[2]=0.0;
1603
1604         if(lb->first){
1605                 for(ec = lb->first; ec; ec= ec->next){
1606                         eob= ec->ob;
1607                         if(ec->type & PSYS_EC_EFFECTOR){
1608                                 pd=eob->pd;
1609                                 if(pd->forcefield==PFIELD_GUIDE){
1610                                         cu = (Curve*)eob->data;
1611
1612                                         distance=ec->distances[pa_num];
1613                                         mindist=pd->f_strength;
1614
1615                                         VECCOPY(pa_loc, ec->locations+3*pa_num);
1616                                         VECCOPY(pa_zero,pa_loc);
1617                                         VECADD(pa_zero,pa_zero,ec->firstloc);
1618
1619                                         guidetime=time/(1.0-pd->free_end);
1620
1621                                         /* WARNING: bails out with continue here */
1622                                         if(((pd->flag & PFIELD_USEMAX) && distance>pd->maxdist) || guidetime>1.0f) continue;
1623
1624                                         if(guidetime>1.0f) continue;
1625
1626                                         /* calculate contribution factor for this guide */
1627                                         f_force=1.0f;
1628                                         if(distance<=mindist);
1629                                         else if(pd->flag & PFIELD_USEMAX) {
1630                                                 if(mindist>=pd->maxdist) f_force= 0.0f;
1631                                                 else if(pd->f_power!=0.0f){
1632                                                         f_force= 1.0f - (distance-mindist)/(pd->maxdist - mindist);
1633                                                         f_force = (float)pow(f_force, pd->f_power);
1634                                                 }
1635                                         }
1636                                         else if(pd->f_power!=0.0f){
1637                                                 f_force= 1.0f/(1.0f + distance-mindist);
1638                                                 f_force = (float)pow(f_force, pd->f_power);
1639                                         }
1640
1641                                         if(pd->flag & PFIELD_GUIDE_PATH_ADD)
1642                                                 where_on_path(eob, f_force*guidetime, guidevec, guidedir);
1643                                         else
1644                                                 where_on_path(eob, guidetime, guidevec, guidedir);
1645
1646                                         Mat4MulVecfl(ec->ob->obmat,guidevec);
1647                                         Mat4Mul3Vecfl(ec->ob->obmat,guidedir);
1648
1649                                         Normalize(guidedir);
1650
1651                                         if(guidetime!=0.0){
1652                                                 /* curve direction */
1653                                                 Crossf(temp, ec->firstdir, guidedir);
1654                                                 angle=Inpf(ec->firstdir,guidedir)/(VecLength(ec->firstdir));
1655                                                 angle=saacos(angle);
1656                                                 VecRotToQuat(temp,angle,rot2);
1657                                                 QuatMulVecf(rot2,pa_loc);
1658
1659                                                 /* curve tilt */
1660                                                 VecRotToQuat(guidedir,guidevec[3]-ec->firstloc[3],rot2);
1661                                                 QuatMulVecf(rot2,pa_loc);
1662
1663                                                 //vectoquat(guidedir, pd->kink_axis, (pd->kink_axis+1)%3, q);
1664                                                 //QuatMul(par.rot,rot2,q);
1665                                         }
1666                                         //else{
1667                                         //      par.rot[0]=1.0f;
1668                                         //      par.rot[1]=par.rot[2]=par.rot[3]=0.0f;
1669                                         //}
1670
1671                                         /* curve taper */
1672                                         if(cu->taperobj)
1673                                                 VecMulf(pa_loc,calc_taper(cu->taperobj,(int)(f_force*guidetime*100.0),100));
1674                                         /* TODO */
1675                                         //else{
1676                                         ///* curve size*/
1677                                         //      calc_curve_subdiv_radius(cu,cu->nurb.first,((Nurb*)cu->nurb.first)->
1678                                         //}
1679                                         par.co[0]=par.co[1]=par.co[2]=0.0f;
1680                                         VECCOPY(key.co,pa_loc);
1681                                         do_prekink(&key, &par, 0, guidetime, pd->kink_freq, pd->kink_shape, pd->kink_amp, pd->kink, pd->kink_axis, 0);
1682                                         do_clump(&key, &par, guidetime, pd->clump_fac, pd->clump_pow, 1.0f);
1683                                         VECCOPY(pa_loc,key.co);
1684
1685                                         VECADD(pa_loc,pa_loc,guidevec);
1686                                         VECSUB(pa_loc,pa_loc,pa_zero);
1687                                         VECADDFAC(effect,effect,pa_loc,f_force);
1688                                         VECADDFAC(veffect,veffect,guidedir,f_force);
1689                                         totforce+=f_force;
1690                                 }
1691                         }
1692                 }
1693
1694                 if(totforce!=0.0){
1695                         if(totforce>1.0)
1696                                 VecMulf(effect,1.0f/totforce);
1697                         CLAMP(totforce,0.0,1.0);
1698                         VECADD(effect,effect,pa_zero);
1699                         VecLerpf(state->co,state->co,effect,totforce);
1700
1701                         Normalize(veffect);
1702                         VecMulf(veffect,VecLength(state->vel));
1703                         VECCOPY(state->vel,veffect);
1704                         return 1;
1705                 }
1706         }
1707         return 0;
1708 }
1709 static void do_rough(float *loc, float t, float fac, float size, float thres, ParticleKey *state)
1710 {
1711         float rough[3];
1712         float rco[3];
1713
1714         if(thres!=0.0)
1715                 if((float)fabs((float)(-1.5+loc[0]+loc[1]+loc[2]))<1.5f*thres) return;
1716
1717         VECCOPY(rco,loc);
1718         VecMulf(rco,t);
1719         rough[0]=-1.0f+2.0f*BLI_gTurbulence(size, rco[0], rco[1], rco[2], 2,0,2);
1720         rough[1]=-1.0f+2.0f*BLI_gTurbulence(size, rco[1], rco[2], rco[0], 2,0,2);
1721         rough[2]=-1.0f+2.0f*BLI_gTurbulence(size, rco[2], rco[0], rco[1], 2,0,2);
1722         VECADDFAC(state->co,state->co,rough,fac);
1723 }
1724 static void do_rough_end(float *loc, float t, float fac, float shape, ParticleKey *state, ParticleKey *par)
1725 {
1726         float rough[3], rnor[3];
1727         float roughfac;
1728
1729         roughfac=fac*(float)pow((double)t,shape);
1730         VECCOPY(rough,loc);
1731         rough[0]=-1.0f+2.0f*rough[0];
1732         rough[1]=-1.0f+2.0f*rough[1];
1733         rough[2]=-1.0f+2.0f*rough[2];
1734         VecMulf(rough,roughfac);
1735
1736
1737         if(par){
1738                 VECCOPY(rnor,par->vel);
1739         }
1740         else{
1741                 VECCOPY(rnor,state->vel);
1742         }
1743         Normalize(rnor);
1744         Projf(rnor,rough,rnor);
1745         VECSUB(rough,rough,rnor);
1746
1747         VECADD(state->co,state->co,rough);
1748 }
1749 static void do_path_effectors(Object *ob, ParticleSystem *psys, int i, ParticleCacheKey *ca, int k, int steps, float *rootco, float effector, float dfra, float cfra, float *length, float *vec)
1750 {
1751         float force[3] = {0.0f,0.0f,0.0f}, vel[3] = {0.0f,0.0f,0.0f};
1752         ParticleKey eff_key;
1753         ParticleData *pa;
1754
1755         VECCOPY(eff_key.co,(ca-1)->co);
1756         VECCOPY(eff_key.vel,(ca-1)->vel);
1757         QUATCOPY(eff_key.rot,(ca-1)->rot);
1758
1759         pa= psys->particles+i;
1760         do_effectors(i, pa, &eff_key, ob, psys, rootco, force, vel, dfra, cfra);
1761
1762         VecMulf(force, effector*pow((float)k / (float)steps, 100.0f * psys->part->eff_hair) / (float)steps);
1763
1764         VecAddf(force, force, vec);
1765
1766         Normalize(force);
1767
1768         if(k < steps) {
1769                 VecSubf(vec, (ca+1)->co, ca->co);
1770                 *length = VecLength(vec);
1771         }
1772
1773         VECADDFAC(ca->co, (ca-1)->co, force, *length);
1774 }
1775 static int check_path_length(int k, ParticleCacheKey *keys, ParticleCacheKey *state, float max_length, float *cur_length, float length, float *dvec)
1776 {
1777         if(*cur_length + length > max_length){
1778                 VecMulf(dvec, (max_length - *cur_length) / length);
1779                 VECADD(state->co, (state - 1)->co, dvec);
1780                 keys->steps = k;
1781                 /* something over the maximum step value */
1782                 return k=100000;
1783         }
1784         else {
1785                 *cur_length+=length;
1786                 return k;
1787         }
1788 }
1789 static void offset_child(ChildParticle *cpa, ParticleKey *par, ParticleKey *child, float flat, float radius)
1790 {
1791         VECCOPY(child->co,cpa->fuv);
1792         VecMulf(child->co,radius);
1793
1794         child->co[0]*=flat;
1795
1796         VECCOPY(child->vel,par->vel);
1797
1798         QuatMulVecf(par->rot,child->co);
1799
1800         QUATCOPY(child->rot,par->rot);
1801
1802         VECADD(child->co,child->co,par->co);
1803 }
1804 float *psys_cache_vgroup(DerivedMesh *dm, ParticleSystem *psys, int vgroup)
1805 {
1806         float *vg=0;
1807
1808         if(psys->vgroup[vgroup]){
1809                 MDeformVert *dvert = dm->getVertDataArray(dm, CD_MDEFORMVERT);
1810                 if(dvert){
1811                         int totvert=dm->getNumVerts(dm), i;
1812                         vg=MEM_callocN(sizeof(float)*totvert, "vg_cache");
1813                         if(psys->vg_neg&(1<<vgroup)){
1814                                 for(i=0; i<totvert; i++)
1815                                         vg[i]=1.0f-vert_weight(dvert+i,psys->vgroup[vgroup]-1);
1816                         }
1817                         else{
1818                                 for(i=0; i<totvert; i++)
1819                                         vg[i]=vert_weight(dvert+i,psys->vgroup[vgroup]-1);
1820                         }
1821                 }
1822         }
1823         return vg;
1824 }
1825 void psys_find_parents(Object *ob, ParticleSystemModifierData *psmd, ParticleSystem *psys)
1826 {
1827         ParticleSettings *part=psys->part;
1828         KDTree *tree;
1829         ChildParticle *cpa;
1830         int p, totparent,totchild=psys->totchild;
1831         float co[3], orco[3];
1832         int from=PART_FROM_FACE;
1833         totparent=(int)(totchild*part->parents*0.3);
1834
1835         tree=BLI_kdtree_new(totparent);
1836
1837         for(p=0,cpa=psys->child; p<totparent; p++,cpa++){
1838                 psys_particle_on_emitter(ob,psmd,from,cpa->num,-1,cpa->fuv,cpa->foffset,co,0,0,0,orco,0);
1839                 BLI_kdtree_insert(tree, p, orco, NULL);
1840         }
1841
1842         BLI_kdtree_balance(tree);
1843
1844         for(; p<totchild; p++,cpa++){
1845                 psys_particle_on_emitter(ob,psmd,from,cpa->num,DMCACHE_ISCHILD,cpa->fuv,cpa->foffset,co,0,0,0,orco,0);
1846                 cpa->parent=BLI_kdtree_find_nearest(tree, orco, NULL, NULL);
1847         }
1848
1849         BLI_kdtree_free(tree);
1850 }
1851
1852 static void get_strand_normal(Material *ma, float *surfnor, float surfdist, float *nor)
1853 {
1854         float cross[3], nstrand[3], vnor[3], blend;
1855
1856         if(!((ma->mode & MA_STR_SURFDIFF) || (ma->strand_surfnor > 0.0f)))
1857                 return;
1858
1859         if(ma->mode & MA_STR_SURFDIFF) {
1860                 Crossf(cross, surfnor, nor);
1861                 Crossf(nstrand, nor, cross);
1862
1863                 blend= INPR(nstrand, surfnor);
1864                 CLAMP(blend, 0.0f, 1.0f);
1865
1866                 VecLerpf(vnor, nstrand, surfnor, blend);
1867                 Normalize(vnor);
1868         }
1869         else
1870                 VECCOPY(vnor, nor)
1871         
1872         if(ma->strand_surfnor > 0.0f) {
1873                 if(ma->strand_surfnor > surfdist) {
1874                         blend= (ma->strand_surfnor - surfdist)/ma->strand_surfnor;
1875                         VecLerpf(vnor, vnor, surfnor, blend);
1876                         Normalize(vnor);
1877                 }
1878         }
1879
1880         VECCOPY(nor, vnor);
1881 }
1882
1883 int psys_threads_init_path(ParticleThread *threads, float cfra, int editupdate)
1884 {
1885         ParticleThreadContext *ctx= threads[0].ctx;
1886         Object *ob= ctx->ob;
1887         ParticleSystem *psys= ctx->psys;
1888         ParticleSettings *part = psys->part;
1889         ParticleEditSettings *pset = &G.scene->toolsettings->particle;
1890         int totparent=0, between=0;
1891         int steps = (int)pow(2.0,(double)part->draw_step);
1892         int totchild = psys->totchild;
1893         int i, seed, totthread= threads[0].tot;
1894
1895         /*---start figuring out what is actually wanted---*/
1896         if(psys_in_edit_mode(psys))
1897                 if(psys->renderdata==0 && (psys->edit==NULL || pset->flag & PE_SHOW_CHILD)==0)
1898                         totchild=0;
1899
1900         if(totchild && part->from!=PART_FROM_PARTICLE && part->childtype==PART_CHILD_FACES){
1901                 totparent=(int)(totchild*part->parents*0.3);
1902                 /* part->parents could still be 0 so we can't test with totparent */
1903                 between=1;
1904         }
1905
1906         if(psys->renderdata)
1907                 steps=(int)pow(2.0,(double)part->ren_step);
1908         else{
1909                 totchild=(int)((float)totchild*(float)part->disp/100.0f);
1910                 totparent=MIN2(totparent,totchild);
1911         }
1912
1913         if(totchild==0) return 0;
1914
1915         /* init random number generator */
1916         if(ctx->psys->part->flag & PART_ANIM_BRANCHING)
1917                 seed= 31415926 + ctx->psys->seed + (int)cfra;
1918         else
1919                 seed= 31415926 + ctx->psys->seed;
1920         
1921         if(part->flag & PART_BRANCHING || ctx->editupdate || totchild < 10000)
1922                 totthread= 1;
1923         
1924         for(i=0; i<totthread; i++) {
1925                 threads[i].rng_path= rng_new(seed);
1926                 threads[i].tot= totthread;
1927         }
1928
1929         /* fill context values */
1930         ctx->between= between;
1931         ctx->steps= steps;
1932         ctx->totchild= totchild;
1933         ctx->totparent= totparent;
1934         ctx->cfra= cfra;
1935
1936         psys->lattice = psys_get_lattice(ob, psys);
1937
1938         /* cache all relevant vertex groups if they exist */
1939         if(part->from!=PART_FROM_PARTICLE){
1940                 ctx->vg_length = psys_cache_vgroup(ctx->dm,psys,PSYS_VG_LENGTH);
1941                 ctx->vg_clump = psys_cache_vgroup(ctx->dm,psys,PSYS_VG_CLUMP);
1942                 ctx->vg_kink = psys_cache_vgroup(ctx->dm,psys,PSYS_VG_KINK);
1943                 ctx->vg_rough1 = psys_cache_vgroup(ctx->dm,psys,PSYS_VG_ROUGH1);
1944                 ctx->vg_rough2 = psys_cache_vgroup(ctx->dm,psys,PSYS_VG_ROUGH2);
1945                 ctx->vg_roughe = psys_cache_vgroup(ctx->dm,psys,PSYS_VG_ROUGHE);
1946                 if(psys->part->flag & PART_CHILD_EFFECT)
1947                         ctx->vg_effector = psys_cache_vgroup(ctx->dm,psys,PSYS_VG_EFFECTOR);
1948         }
1949
1950         /* set correct ipo timing */
1951         if(part->flag&PART_ABS_TIME && part->ipo){
1952                 calc_ipo(part->ipo, cfra);
1953                 execute_ipo((ID *)part, part->ipo);
1954         }
1955
1956         return 1;
1957 }
1958
1959 /* note: this function must be thread safe, except for branching! */
1960 void psys_thread_create_path(ParticleThread *thread, struct ChildParticle *cpa, ParticleCacheKey *keys, int i)
1961 {
1962         ParticleThreadContext *ctx= thread->ctx;
1963         Object *ob= ctx->ob;
1964         ParticleSystem *psys = ctx->psys;
1965         ParticleSettings *part = psys->part;
1966         ParticleCacheKey **cache= psys->childcache;
1967         ParticleCacheKey **pcache= psys->pathcache;
1968         ParticleCacheKey *state, *par = NULL, *key[4];
1969         ParticleData *pa=NULL;
1970         ParticleTexture ptex;
1971         float *cpa_fuv=0;
1972         float co[3], orco[3], ornor[3], t, rough_t, cpa_1st[3], dvec[3];
1973         float branch_begin, branch_end, branch_prob, branchfac, rough_rand;
1974         float pa_rough1, pa_rough2, pa_roughe;
1975         float length, pa_length, pa_clump, pa_kink, pa_effector;
1976         float max_length = 1.0f, cur_length = 0.0f;
1977         float eff_length, eff_vec[3];
1978         int k, cpa_num, guided=0;
1979         short cpa_from;
1980
1981         if(part->flag & PART_BRANCHING) {
1982                 branch_begin=rng_getFloat(thread->rng_path);
1983                 branch_end=branch_begin+(1.0f-branch_begin)*rng_getFloat(thread->rng_path);
1984                 branch_prob=rng_getFloat(thread->rng_path);
1985                 rough_rand=rng_getFloat(thread->rng_path);
1986         }
1987         else {
1988                 branch_begin= 0.0f;
1989                 branch_end= 0.0f;
1990                 branch_prob= 0.0f;
1991                 rough_rand= 0.0f;
1992         }
1993
1994         if(i<psys->totpart){
1995                 branch_begin=0.0f;
1996                 branch_end=1.0f;
1997                 branch_prob=0.0f;
1998         }
1999
2000         if(ctx->between){
2001                 int w, needupdate;
2002                 float foffset;
2003
2004                 if(ctx->editupdate && !(part->flag & PART_BRANCHING)) {
2005                         needupdate= 0;
2006                         w= 0;
2007                         while(w<4 && cpa->pa[w]>=0) {
2008                                 if(psys->particles[cpa->pa[w]].flag & PARS_EDIT_RECALC) {
2009                                         needupdate= 1;
2010                                         break;
2011                                 }
2012                                 w++;
2013                         }
2014
2015                         if(!needupdate)
2016                                 return;
2017                         else
2018                                 memset(keys, 0, sizeof(*keys)*(ctx->steps+1));
2019                 }
2020
2021                 /* get parent paths */
2022                 w= 0;
2023                 while(w<4 && cpa->pa[w]>=0){
2024                         key[w] = pcache[cpa->pa[w]];
2025                         w++;
2026                 }
2027
2028                 /* get the original coordinates (orco) for texture usage */
2029                 cpa_num = cpa->num;
2030                 
2031                 foffset= cpa->foffset;
2032                 if(part->childtype == PART_CHILD_FACES)
2033                         foffset = -(2.0f + part->childspread);
2034                 cpa_fuv = cpa->fuv;
2035                 cpa_from = PART_FROM_FACE;
2036
2037                 psys_particle_on_emitter(ob,ctx->psmd,cpa_from,cpa_num,DMCACHE_ISCHILD,cpa->fuv,foffset,co,ornor,0,0,orco,0);
2038
2039                 /* we need to save the actual root position of the child for positioning it accurately to the surface of the emitter */
2040                 VECCOPY(cpa_1st,co);
2041                 Mat4MulVecfl(ob->obmat,cpa_1st);
2042
2043                 pa=0;
2044         }
2045         else{
2046                 if(ctx->editupdate && !(part->flag & PART_BRANCHING)) {
2047                         if(!(psys->particles[cpa->parent].flag & PARS_EDIT_RECALC))
2048                                 return;
2049
2050                         memset(keys, 0, sizeof(*keys)*(ctx->steps+1));
2051                 }
2052
2053                 /* get the parent path */
2054                 key[0]=pcache[cpa->parent];
2055
2056                 /* get the original coordinates (orco) for texture usage */
2057                 pa=psys->particles+cpa->parent;
2058
2059                 cpa_from=part->from;
2060                 cpa_num=pa->num;
2061                 cpa_fuv=pa->fuv;
2062
2063                 psys_particle_on_emitter(ob,ctx->psmd,cpa_from,cpa_num,DMCACHE_ISCHILD,cpa_fuv,pa->foffset,co,ornor,0,0,orco,0);
2064         }
2065
2066         keys->steps = ctx->steps;
2067
2068         /* correct child ipo timing */
2069         if((part->flag&PART_ABS_TIME)==0 && part->ipo){
2070                 float dsta=part->end-part->sta;
2071                 calc_ipo(part->ipo, 100.0f*(ctx->cfra-(part->sta+dsta*cpa->rand[1]))/(part->lifetime*(1.0f - part->randlife*cpa->rand[0])));
2072                 execute_ipo((ID *)part, part->ipo);
2073         }
2074
2075         /* get different child parameters from textures & vgroups */
2076         ptex.length=part->length*(1.0f - part->randlength*cpa->rand[0]);
2077         ptex.clump=1.0;
2078         ptex.kink=1.0;
2079         ptex.rough= 1.0;
2080
2081         get_cpa_texture(ctx->dm,ctx->ma,cpa_num,cpa_fuv,orco,&ptex,
2082                 MAP_PA_LENGTH|MAP_PA_CLUMP|MAP_PA_KINK|MAP_PA_ROUGH);
2083         
2084         pa_length=ptex.length;
2085         pa_clump=ptex.clump;
2086         pa_kink=ptex.kink;
2087         pa_rough1=ptex.rough;
2088         pa_rough2=ptex.rough;
2089         pa_roughe=ptex.rough;
2090         pa_effector= 1.0f;
2091
2092         if(ctx->vg_length)
2093                 pa_length*=psys_interpolate_value_from_verts(ctx->dm,cpa_from,cpa_num,cpa_fuv,ctx->vg_length);
2094         if(ctx->vg_clump)
2095                 pa_clump*=psys_interpolate_value_from_verts(ctx->dm,cpa_from,cpa_num,cpa_fuv,ctx->vg_clump);
2096         if(ctx->vg_kink)
2097                 pa_kink*=psys_interpolate_value_from_verts(ctx->dm,cpa_from,cpa_num,cpa_fuv,ctx->vg_kink);
2098         if(ctx->vg_rough1)
2099                 pa_rough1*=psys_interpolate_value_from_verts(ctx->dm,cpa_from,cpa_num,cpa_fuv,ctx->vg_rough1);
2100         if(ctx->vg_rough2)
2101                 pa_rough2*=psys_interpolate_value_from_verts(ctx->dm,cpa_from,cpa_num,cpa_fuv,ctx->vg_rough2);
2102         if(ctx->vg_roughe)
2103                 pa_roughe*=psys_interpolate_value_from_verts(ctx->dm,cpa_from,cpa_num,cpa_fuv,ctx->vg_roughe);
2104         if(ctx->vg_effector)
2105                 pa_effector*=psys_interpolate_value_from_verts(ctx->dm,cpa_from,cpa_num,cpa_fuv,ctx->vg_effector);
2106
2107         /* create the child path */
2108         for(k=0,state=keys; k<=ctx->steps; k++,state++){
2109                 if(ctx->between){
2110                         int w=0;
2111
2112                         state->co[0] = state->co[1] = state->co[2] = 0.0f;
2113                         state->vel[0] = state->vel[1] = state->vel[2] = 0.0f;
2114                         state->rot[0] = state->rot[1] = state->rot[2] = state->rot[3] = 0.0f;
2115
2116                         //QUATCOPY(state->rot,key[0]->rot);
2117
2118                         /* child position is the weighted sum of parent positions */
2119                         while(w<4 && cpa->pa[w]>=0){
2120                                 state->co[0] += cpa->w[w] * key[w]->co[0];
2121                                 state->co[1] += cpa->w[w] * key[w]->co[1];
2122                                 state->co[2] += cpa->w[w] * key[w]->co[2];
2123
2124                                 state->vel[0] += cpa->w[w] * key[w]->vel[0];
2125                                 state->vel[1] += cpa->w[w] * key[w]->vel[1];
2126                                 state->vel[2] += cpa->w[w] * key[w]->vel[2];
2127                                 key[w]++;
2128                                 w++;
2129                         }
2130                         if(k==0){
2131                                 /* calculate the offset between actual child root position and first position interpolated from parents */
2132                                 VECSUB(cpa_1st,cpa_1st,state->co);
2133                         }
2134                         /* apply offset for correct positioning */
2135                         VECADD(state->co,state->co,cpa_1st);
2136                 }
2137                 else{
2138                         /* offset the child from the parent position */
2139                         offset_child(cpa, (ParticleKey*)key[0], (ParticleKey*)state, part->childflat, part->childrad);
2140
2141                         key[0]++;
2142                 }
2143         }
2144
2145         /* apply effectors */
2146         if(part->flag & PART_CHILD_EFFECT) {
2147                 for(k=0,state=keys; k<=ctx->steps; k++,state++) {
2148                         if(k) {
2149                                 do_path_effectors(ob, psys, cpa->pa[0], state, k, ctx->steps, keys->co, pa_effector, 0.0f, ctx->cfra, &eff_length, eff_vec);
2150                         }
2151                         else {
2152                                 VecSubf(eff_vec,(state+1)->co,state->co);
2153                                 eff_length= VecLength(eff_vec);
2154                         }
2155                 }
2156         }
2157
2158         for(k=0,state=keys; k<=ctx->steps; k++,state++){
2159                 t=(float)k/(float)ctx->steps;
2160
2161                 if(ctx->totparent){
2162                         if(i>=ctx->totparent)
2163                                 /* this is not threadsafe, but should only happen for
2164                                  * branching particles particles, which are not threaded */
2165                                 par = cache[cpa->parent] + k;
2166                         else
2167                                 par=0;
2168                 }
2169                 else if(cpa->parent>=0){
2170                         par=pcache[cpa->parent]+k;
2171                 }
2172
2173                 /* apply different deformations to the child path */
2174                 if(part->flag & PART_CHILD_EFFECT)
2175                         /* state is safe to cast, since only co and vel are used */
2176                         guided = do_guide((ParticleKey*)state, cpa->parent, t, &(psys->effectors));
2177
2178                 if(guided==0){
2179                         if(part->kink)
2180                                 do_prekink((ParticleKey*)state, (ParticleKey*)par, par->rot, t,
2181                                 part->kink_freq * pa_kink, part->kink_shape, part->kink_amp, part->kink, part->kink_axis, ob->obmat);
2182                                         
2183                         do_clump((ParticleKey*)state, (ParticleKey*)par, t, part->clumpfac, part->clumppow, pa_clump);
2184                 }
2185
2186                 if(part->flag & PART_BRANCHING && ctx->between == 0 && part->flag & PART_ANIM_BRANCHING)
2187                         rough_t = t * rough_rand;
2188                 else
2189                         rough_t = t;
2190
2191                 if(part->rough1 != 0.0 && pa_rough1 != 0.0)
2192                         do_rough(orco, rough_t, pa_rough1*part->rough1, part->rough1_size, 0.0, (ParticleKey*)state);
2193
2194                 if(part->rough2 != 0.0 && pa_rough2 != 0.0)
2195                         do_rough(cpa->rand, rough_t, pa_rough2*part->rough2, part->rough2_size, part->rough2_thres, (ParticleKey*)state);
2196
2197                 if(part->rough_end != 0.0 && pa_roughe != 0.0)
2198                         do_rough_end(cpa->rand, rough_t, pa_roughe*part->rough_end, part->rough_end_shape, (ParticleKey*)state, (ParticleKey*)par);
2199
2200                 if(part->flag & PART_BRANCHING && ctx->between==0){
2201                         if(branch_prob > part->branch_thres){
2202                                 branchfac=0.0f;
2203                         }
2204                         else{
2205                                 if(part->flag & PART_SYMM_BRANCHING){
2206                                         if(t < branch_begin || t > branch_end)
2207                                                 branchfac=0.0f;
2208                                         else{
2209                                                 if((t-branch_begin)/(branch_end-branch_begin)<0.5)
2210                                                         branchfac=2.0f*(t-branch_begin)/(branch_end-branch_begin);
2211                                                 else
2212                                                         branchfac=2.0f*(branch_end-t)/(branch_end-branch_begin);
2213
2214                                                 CLAMP(branchfac,0.0f,1.0f);
2215                                         }
2216                                 }
2217                                 else{
2218                                         if(t < branch_begin){
2219                                                 branchfac=0.0f;
2220                                         }
2221                                         else{
2222                                                 branchfac=(t-branch_begin)/((1.0f-branch_begin)*0.5f);
2223                                                 CLAMP(branchfac,0.0f,1.0f);
2224                                         }
2225                                 }
2226                         }
2227
2228                         if(i<psys->totpart)
2229                                 VecLerpf(state->co, (pcache[i] + k)->co, state->co, branchfac);
2230                         else
2231                                 /* this is not threadsafe, but should only happen for
2232                                  * branching particles particles, which are not threaded */
2233                                 VecLerpf(state->co, (cache[i - psys->totpart] + k)->co, state->co, branchfac);
2234                 }
2235
2236                 /* we have to correct velocity because of kink & clump */
2237                 if(k>1){
2238                         VECSUB((state-1)->vel,state->co,(state-2)->co);
2239                         VecMulf((state-1)->vel,0.5);
2240
2241                         if(ctx->ma && (part->draw & PART_DRAW_MAT_COL))
2242                                 get_strand_normal(ctx->ma, ornor, cur_length, (state-1)->vel);
2243                 }
2244
2245                 /* check if path needs to be cut before actual end of data points */
2246                 if(k){
2247                         VECSUB(dvec,state->co,(state-1)->co);
2248                         if(part->flag&PART_ABS_LENGTH)
2249                                 length=VecLength(dvec);
2250                         else
2251                                 length=1.0f/(float)ctx->steps;
2252
2253                         k=check_path_length(k,keys,state,max_length,&cur_length,length,dvec);
2254                 }
2255                 else{
2256                         /* initialize length calculation */
2257                         if(part->flag&PART_ABS_LENGTH)
2258                                 max_length= part->abslength*pa_length;
2259                         else
2260                                 max_length= pa_length;
2261
2262                         cur_length= 0.0f;
2263                 }
2264
2265                 if(ctx->ma && (part->draw & PART_DRAW_MAT_COL)) {
2266                         VECCOPY(state->col, &ctx->ma->r)
2267                         get_strand_normal(ctx->ma, ornor, cur_length, state->vel);
2268                 }
2269         }
2270 }
2271
2272 void *exec_child_path_cache(void *data)
2273 {
2274         ParticleThread *thread= (ParticleThread*)data;
2275         ParticleThreadContext *ctx= thread->ctx;
2276         ParticleSystem *psys= ctx->psys;
2277         ParticleCacheKey **cache= psys->childcache;
2278         ChildParticle *cpa;
2279         int i, totchild= ctx->totchild;
2280         
2281         cpa= psys->child + thread->num;
2282         for(i=thread->num; i<totchild; i+=thread->tot, cpa+=thread->tot)
2283                 psys_thread_create_path(thread, cpa, cache[i], i);
2284
2285         return 0;
2286 }
2287
2288 void psys_cache_child_paths(Object *ob, ParticleSystem *psys, float cfra, int editupdate)
2289 {
2290         ParticleSettings *part = psys->part;
2291         ParticleThread *pthreads;
2292         ParticleThreadContext *ctx;
2293         ParticleCacheKey **cache;
2294         ListBase threads;
2295         int i, totchild, totparent, totthread;
2296
2297         pthreads= psys_threads_create(ob, psys);
2298
2299         if(!psys_threads_init_path(pthreads, cfra, editupdate)) {
2300                 psys_threads_free(pthreads);
2301                 return;
2302         }
2303
2304         ctx= pthreads[0].ctx;
2305         totchild= ctx->totchild;
2306         totparent= ctx->totparent;
2307
2308         if(editupdate && psys->childcache && !(part->flag & PART_BRANCHING) && totchild == psys->totchildcache) {
2309                 cache = psys->childcache;
2310         }
2311         else {
2312                 /* clear out old and create new empty path cache */
2313                 free_child_path_cache(psys);
2314                 psys->childcache= psys_alloc_path_cache_buffers(&psys->childcachebufs, totchild, ctx->steps+1);
2315                 psys->totchildcache = totchild;
2316         }
2317
2318         totthread= pthreads[0].tot;
2319
2320         if(totthread > 1) {
2321                 BLI_init_threads(&threads, exec_child_path_cache, totthread);
2322
2323                 for(i=0; i<totthread; i++)
2324                         BLI_insert_thread(&threads, &pthreads[i]);
2325
2326                 BLI_end_threads(&threads);
2327         }
2328         else
2329                 exec_child_path_cache(&pthreads[0]);
2330
2331         psys_threads_free(pthreads);
2332 }
2333
2334 /* Calculates paths ready for drawing/rendering.                                                                        */
2335 /* -Usefull for making use of opengl vertex arrays for super fast strand drawing.       */
2336 /* -Makes child strands possible and creates them too into the cache.                           */
2337 /* -Cached path data is also used to determine cut position for the editmode tool.      */
2338 void psys_cache_paths(Object *ob, ParticleSystem *psys, float cfra, int editupdate)
2339 {
2340         ParticleCacheKey *ca, **cache=psys->pathcache;
2341         ParticleSystemModifierData *psmd = psys_get_modifier(ob, psys);
2342         ParticleEditSettings *pset = &G.scene->toolsettings->particle;
2343         ParticleSettings *part = psys->part;
2344         
2345         ParticleData *pa;
2346         ParticleKey keys[4], result, *kkey[2] = {NULL, NULL};
2347         HairKey *hkey[2] = {NULL, NULL};
2348
2349         ParticleEdit *edit = 0;
2350         ParticleEditKey *ekey = 0;
2351
2352         SoftBody *soft = 0;
2353         BodyPoint *bp[2] = {NULL, NULL};
2354         
2355         Material *ma;
2356         
2357         float birthtime = 0.0, dietime = 0.0;
2358         float t, time = 0.0, keytime = 0.0, dfra = 1.0, frs_sec = G.scene->r.frs_sec;
2359         float col[3] = {0.5f, 0.5f, 0.5f};
2360         float prev_tangent[3], hairmat[4][4];
2361         int k,i;
2362         int steps = (int)pow(2.0, (double)psys->part->draw_step);
2363         int totpart = psys->totpart;
2364         char nosel[4], sel[4];
2365         float sel_col[3];
2366         float nosel_col[3];
2367         float length, vec[3];
2368         float *vg_effector= NULL, effector=0.0f;
2369         float *vg_length= NULL, pa_length=1.0f, max_length=1.0f, cur_length=0.0f;
2370         float len, dvec[3];
2371
2372         /* we don't have anything valid to create paths from so let's quit here */
2373         if((psys->flag & PSYS_HAIR_DONE)==0 && (psys->flag & PSYS_KEYED)==0)
2374                 return;
2375
2376         if(psys->renderdata)
2377                 steps = (int)pow(2.0, (double)psys->part->ren_step);
2378         else if(psys_in_edit_mode(psys)){
2379                 edit=psys->edit;
2380                 
2381                 //timed = edit->draw_timed;
2382
2383                 PE_get_colors(sel,nosel);
2384                 if(pset->brushtype == PE_BRUSH_WEIGHT){
2385                         sel_col[0] = sel_col[1] = sel_col[2] = 1.0f;
2386                         nosel_col[0] = nosel_col[1] = nosel_col[2] = 0.0f;
2387                 }
2388                 else{
2389                         sel_col[0] = (float)sel[0] / 255.0f;
2390                         sel_col[1] = (float)sel[1] / 255.0f;
2391                         sel_col[2] = (float)sel[2] / 255.0f;
2392                         nosel_col[0] = (float)nosel[0] / 255.0f;
2393                         nosel_col[1] = (float)nosel[1] / 255.0f;
2394                         nosel_col[2] = (float)nosel[2] / 255.0f;
2395                 }
2396         }
2397
2398         if(editupdate && psys->pathcache && totpart == psys->totcached) {
2399                 cache = psys->pathcache;
2400         }
2401         else {
2402                 /* clear out old and create new empty path cache */
2403                 psys_free_path_cache(psys);
2404                 cache= psys_alloc_path_cache_buffers(&psys->pathcachebufs, totpart, steps+1);
2405                 psys->pathcache= cache;
2406         }
2407
2408         if(edit==NULL && psys->soft && psys->softflag & OB_SB_ENABLE) {
2409                 soft = psys->soft;
2410                 if(!soft->bpoint)
2411                         soft= NULL;
2412         }
2413         
2414         psys->lattice = psys_get_lattice(ob, psys);
2415         ma= give_current_material(ob, psys->part->omat);
2416         if(ma && (psys->part->draw & PART_DRAW_MAT_COL))
2417                 VECCOPY(col, &ma->r)
2418         
2419         if(psys->part->from!=PART_FROM_PARTICLE) {
2420                 if(!(psys->part->flag & PART_CHILD_EFFECT))
2421                         vg_effector = psys_cache_vgroup(psmd->dm, psys, PSYS_VG_EFFECTOR);
2422                 
2423                 if(!edit && !psys->totchild)
2424                         vg_length = psys_cache_vgroup(psmd->dm, psys, PSYS_VG_LENGTH);
2425         }
2426
2427         /*---first main loop: create all actual particles' paths---*/
2428         for(i=0,pa=psys->particles; i<totpart; i++, pa++){
2429                 if(psys && edit==NULL && (pa->flag & PARS_NO_DISP || pa->flag & PARS_UNEXIST)) {
2430                         if(soft)
2431                                 bp[0] += pa->totkey; /* TODO use of initialized value? */
2432                         continue;
2433                 }
2434
2435                 if(editupdate && !(pa->flag & PARS_EDIT_RECALC)) continue;
2436                 else memset(cache[i], 0, sizeof(*cache[i])*(steps+1));
2437
2438                 if(!edit && !psys->totchild) {
2439                         pa_length = part->length * (1.0f - part->randlength*pa->r_ave[0]);
2440                         if(vg_length)
2441                                 pa_length *= psys_interpolate_value_from_verts(psmd->dm,part->from,pa->num,pa->fuv,vg_length);
2442                 }
2443
2444                 cache[i]->steps = steps;
2445
2446                 if(edit)
2447                         ekey = edit->keys[i];
2448
2449                 /*--get the first data points--*/
2450                 if(psys->flag & PSYS_KEYED) {
2451                         kkey[0] = pa->keys;
2452                         kkey[1] = kkey[0] + 1;
2453
2454                         birthtime = kkey[0]->time;
2455                         dietime = kkey[0][pa->totkey-1].time;
2456                 }
2457                 else {
2458                         hkey[0] = pa->hair;
2459                         hkey[1] = hkey[0] + 1;
2460
2461                         birthtime = hkey[0]->time;
2462                         dietime = hkey[0][pa->totkey-1].time;
2463
2464                         psys_mat_hair_to_global(ob, psmd->dm, psys->part->from, pa, hairmat);
2465                 }
2466
2467                 if(soft){
2468                         bp[0] = soft->bpoint + pa->bpi;
2469                         bp[1] = bp[0] + 1;
2470                 }
2471
2472                 /*--interpolate actual path from data points--*/
2473                 for(k=0, ca=cache[i]; k<=steps; k++, ca++){
2474                         time = (float)k / (float)steps;
2475
2476                         t = birthtime + time * (dietime - birthtime);
2477
2478                         if(psys->flag & PSYS_KEYED) {
2479                                 while(kkey[1]->time < t) {
2480                                         kkey[1]++;
2481                                 }
2482
2483                                 kkey[0] = kkey[1] - 1;                          
2484                         }
2485                         else {
2486                                 while(hkey[1]->time < t) {
2487                                         hkey[1]++;
2488                                         bp[1]++;
2489                                 }
2490
2491                                 hkey[0] = hkey[1] - 1;
2492                         }
2493
2494                         if(soft) {
2495                                 bp[0] = bp[1] - 1;
2496                                 bp_to_particle(keys + 1, bp[0], hkey[0]);
2497                                 bp_to_particle(keys + 2, bp[1], hkey[1]);
2498                         }
2499                         else if(psys->flag & PSYS_KEYED) {
2500                                 memcpy(keys + 1, kkey[0], sizeof(ParticleKey));
2501                                 memcpy(keys + 2, kkey[1], sizeof(ParticleKey));
2502                         }
2503                         else {
2504                                 hair_to_particle(keys + 1, hkey[0]);
2505                                 hair_to_particle(keys + 2, hkey[1]);
2506                         }
2507
2508
2509                         if((psys->flag & PSYS_KEYED)==0) {
2510                                 if(soft) {
2511                                         if(hkey[0] != pa->hair)
2512                                                 bp_to_particle(keys, bp[0] - 1, hkey[0] - 1);
2513                                         else
2514                                                 bp_to_particle(keys, bp[0], hkey[0]);
2515                                 }
2516                                 else {
2517                                         if(hkey[0] != pa->hair)
2518                                                 hair_to_particle(keys, hkey[0] - 1);
2519                                         else
2520                                                 hair_to_particle(keys, hkey[0]);
2521                                 }
2522
2523                                 if(soft) {
2524                                         if(hkey[1] != pa->hair + pa->totkey - 1)
2525                                                 bp_to_particle(keys + 3, bp[1] + 1, hkey[1] + 1);
2526                                         else
2527                                                 bp_to_particle(keys + 3, bp[1], hkey[1]);
2528                                 }
2529                                 else {
2530                                         if(hkey[1] != pa->hair + pa->totkey - 1)
2531                                                 hair_to_particle(keys + 3, hkey[1] + 1);
2532                                         else
2533                                                 hair_to_particle(keys + 3, hkey[1]);
2534                                 }
2535                         }
2536
2537                         dfra = keys[2].time - keys[1].time;
2538
2539                         keytime = (t - keys[1].time) / dfra;
2540
2541                         /* convert velocity to timestep size */
2542                         if(psys->flag & PSYS_KEYED){
2543                                 VecMulf(keys[1].vel, dfra / frs_sec);
2544                                 VecMulf(keys[2].vel, dfra / frs_sec);
2545                         }
2546
2547                         /* now we should have in chronologiacl order k1<=k2<=t<=k3<=k4 with keytime between [0,1]->[k2,k3] (k1 & k4 used for cardinal & bspline interpolation)*/
2548                         interpolate_particle((psys->flag & PSYS_KEYED) ? -1 /* signal for cubic interpolation */
2549                                 : ((psys->part->flag & PART_HAIR_BSPLINE) ? KEY_BSPLINE : KEY_CARDINAL)
2550                                 ,keys, keytime, &result, 0);
2551
2552                         /* the velocity needs to be converted back from cubic interpolation */
2553                         if(psys->flag & PSYS_KEYED){
2554                                 VecMulf(result.vel, frs_sec / dfra);
2555                         }
2556                         else if(soft==NULL) { /* softbody and keyed are allready in global space */
2557                                 Mat4MulVecfl(hairmat, result.co);
2558                         }
2559
2560                         VECCOPY(ca->co, result.co);
2561
2562                         /* selection coloring in edit mode */
2563                         if(edit){
2564                                 if(pset->brushtype==PE_BRUSH_WEIGHT){
2565                                         if(k==steps)
2566                                                 VecLerpf(ca->col, nosel_col, sel_col, hkey[0]->weight);
2567                                         else
2568                                                 VecLerpf(ca->col, nosel_col, sel_col,
2569                                                 (1.0f - keytime) * hkey[0]->weight + keytime * hkey[1]->weight);
2570                                 }
2571                                 else{
2572                                         if((ekey + (hkey[0] - pa->hair))->flag & PEK_SELECT){
2573                                                 if((ekey + (hkey[1] - pa->hair))->flag & PEK_SELECT){
2574                                                         VECCOPY(ca->col, sel_col);
2575                                                 }
2576                                                 else{
2577                                                         VecLerpf(ca->col, sel_col, nosel_col, keytime);
2578                                                 }
2579                                         }
2580                                         else{
2581                                                 if((ekey + (hkey[1] - pa->hair))->flag & PEK_SELECT){
2582                                                         VecLerpf(ca->col, nosel_col, sel_col, keytime);
2583                                                 }
2584                                                 else{
2585                                                         VECCOPY(ca->col, nosel_col);
2586                                                 }
2587                                         }
2588                                 }
2589                         }
2590                         else{
2591                                 VECCOPY(ca->col, col);
2592                         }
2593                 }
2594                 
2595                 /*--modify paths--*/
2596
2597                 VecSubf(vec,(cache[i]+1)->co,cache[i]->co);
2598                 length = VecLength(vec);
2599
2600                 effector= 1.0f;
2601                 if(vg_effector)
2602                         effector*= psys_interpolate_value_from_verts(psmd->dm,psys->part->from,pa->num,pa->fuv,vg_effector);
2603
2604                 for(k=0, ca=cache[i]; k<=steps; k++, ca++) {
2605                         /* apply effectors */
2606                         if(!(psys->part->flag & PART_CHILD_EFFECT) && edit==0 && k)
2607                                 do_path_effectors(ob, psys, i, ca, k, steps, cache[i]->co, effector, dfra, cfra, &length, vec);
2608
2609                         /* apply guide curves to path data */
2610                         if(edit==0 && psys->effectors.first && (psys->part->flag & PART_CHILD_EFFECT)==0)
2611                                 /* ca is safe to cast, since only co and vel are used */
2612                                 do_guide((ParticleKey*)ca, i, (float)k/(float)steps, &psys->effectors);
2613
2614                         /* apply lattice */
2615                         if(psys->lattice && edit==0)
2616                                 calc_latt_deform(ca->co, 1.0f);
2617
2618                         /* figure out rotation */
2619                         
2620                         if(k) {
2621                                 float cosangle, angle, tangent[3], normal[3], q[4];
2622
2623                                 if(k == 1) {
2624                                         VECSUB(tangent, ca->co, (ca - 1)->co);
2625
2626                                         vectoquat(tangent, OB_POSX, OB_POSZ, (ca-1)->rot);
2627
2628                                         VECCOPY(prev_tangent, tangent);
2629                                         Normalize(prev_tangent);
2630                                 }
2631                                 else {
2632                                         VECSUB(tangent, ca->co, (ca - 1)->co);
2633                                         Normalize(tangent);
2634
2635                                         cosangle= Inpf(tangent, prev_tangent);
2636
2637                                         /* note we do the comparison on cosangle instead of
2638                                          * angle, since floating point accuracy makes it give
2639                                          * different results across platforms */
2640                                         if(cosangle > 0.999999f) {
2641                                                 QUATCOPY((ca - 1)->rot, (ca - 2)->rot);
2642                                         }
2643                                         else {
2644                                                 angle= saacos(cosangle);
2645                                                 Crossf(normal, prev_tangent, tangent);
2646                                                 VecRotToQuat(normal, angle, q);
2647                                                 QuatMul((ca - 1)->rot, q, (ca - 2)->rot);
2648                                         }
2649
2650                                         VECCOPY(prev_tangent, tangent);
2651                                 }
2652
2653                                 if(k == steps)
2654                                         QUATCOPY(ca->rot, (ca - 1)->rot);
2655                         }
2656
2657                         
2658                         /* set velocity */
2659
2660                         if(k){
2661                                 VECSUB(ca->vel, ca->co, (ca-1)->co);
2662
2663                                 if(k==1) {
2664                                         VECCOPY((ca-1)->vel, ca->vel);
2665                                 }
2666
2667                         }
2668
2669                         if(!edit && !psys->totchild) {
2670                                 /* check if path needs to be cut before actual end of data points */
2671                                 if(k){
2672                                         VECSUB(dvec,ca->co,(ca-1)->co);
2673                                         if(part->flag&PART_ABS_LENGTH)
2674                                                 len=VecLength(dvec);
2675                                         else
2676                                                 len=1.0f/(float)steps;
2677
2678                                         k=check_path_length(k,cache[i],ca,max_length,&cur_length,len,dvec);
2679                                 }
2680                                 else{
2681                                         /* initialize length calculation */
2682                                         if(part->flag&PART_ABS_LENGTH)
2683                                                 max_length= part->abslength*pa_length;
2684                                         else
2685                                                 max_length= pa_length;
2686
2687                                         cur_length= 0.0f;
2688                                 }
2689                         }
2690                 }
2691         }
2692
2693         psys->totcached = totpart;
2694
2695         if(psys && psys->lattice){
2696                 end_latt_deform();
2697                 psys->lattice=0;
2698         }
2699
2700         if(vg_effector)
2701                 MEM_freeN(vg_effector);
2702
2703         if(vg_length)
2704                 MEM_freeN(vg_length);
2705 }
2706 /************************************************/
2707 /*                      Particle Key handling                           */
2708 /************************************************/
2709 void copy_particle_key(ParticleKey *to, ParticleKey *from, int time){
2710         if(time){
2711                 memcpy(to,from,sizeof(ParticleKey));
2712         }
2713         else{
2714                 float to_time=to->time;
2715                 memcpy(to,from,sizeof(ParticleKey));
2716                 to->time=to_time;
2717         }
2718         /*
2719         VECCOPY(to->co,from->co);
2720         VECCOPY(to->vel,from->vel);
2721         QUATCOPY(to->rot,from->rot);
2722         if(time)
2723                 to->time=from->time;
2724         to->flag=from->flag;
2725         to->sbw=from->sbw;
2726         */
2727 }
2728 void psys_get_from_key(ParticleKey *key, float *loc, float *vel, float *rot, float *time){
2729         if(loc) VECCOPY(loc,key->co);
2730         if(vel) VECCOPY(vel,key->vel);
2731         if(rot) QUATCOPY(rot,key->rot);
2732         if(time) *time=key->time;
2733 }
2734 /*-------changing particle keys from space to another-------*/
2735 void psys_key_to_object(Object *ob, ParticleKey *key, float imat[][4]){
2736         float q[4], imat2[4][4];
2737
2738         if(imat==0){
2739                 Mat4Invert(imat2,ob->obmat);
2740                 imat=imat2;
2741         }
2742
2743         VECADD(key->vel,key->vel,key->co);
2744
2745         Mat4MulVecfl(imat,key->co);
2746         Mat4MulVecfl(imat,key->vel);
2747         Mat4ToQuat(imat,q);
2748
2749         VECSUB(key->vel,key->vel,key->co);
2750         QuatMul(key->rot,q,key->rot);
2751 }
2752 static void key_from_object(Object *ob, ParticleKey *key){
2753         float q[4];
2754
2755         VECADD(key->vel,key->vel,key->co);
2756
2757         Mat4MulVecfl(ob->obmat,key->co);
2758         Mat4MulVecfl(ob->obmat,key->vel);
2759         Mat4ToQuat(ob->obmat,q);
2760
2761         VECSUB(key->vel,key->vel,key->co);
2762         QuatMul(key->rot,q,key->rot);
2763 }
2764
2765 static void triatomat(float *v1, float *v2, float *v3, float (*uv)[2], float mat[][4])
2766 {
2767         float det, w1, w2, d1[2], d2[2];
2768
2769         memset(mat, 0, sizeof(float)*4*4);
2770         mat[3][3]= 1.0f;
2771
2772         /* first axis is the normal */
2773         CalcNormFloat(v1, v2, v3, mat[2]);
2774
2775         /* second axis along (1, 0) in uv space */
2776         if(uv) {
2777                 d1[0]= uv[1][0] - uv[0][0];
2778                 d1[1]= uv[1][1] - uv[0][1];
2779                 d2[0]= uv[2][0] - uv[0][0];
2780                 d2[1]= uv[2][1] - uv[0][1];
2781
2782                 det = d2[0]*d1[1] - d2[1]*d1[0];
2783
2784                 if(det != 0.0f) {
2785                         det= 1.0f/det;
2786                         w1= -d2[1]*det;
2787                         w2= d1[1]*det;
2788
2789                         mat[1][0]= w1*(v2[0] - v1[0]) + w2*(v3[0] - v1[0]);
2790                         mat[1][1]= w1*(v2[1] - v1[1]) + w2*(v3[1] - v1[1]);
2791                         mat[1][2]= w1*(v2[2] - v1[2]) + w2*(v3[2] - v1[2]);
2792                         Normalize(mat[1]);
2793                 }
2794                 else
2795                         mat[1][0]= mat[1][1]= mat[1][2]= 0.0f;
2796         }
2797         else {
2798                 VecSubf(mat[1], v2, v1);
2799                 Normalize(mat[1]);
2800         }
2801         
2802         /* third as a cross product */
2803         Crossf(mat[0], mat[1], mat[2]);
2804 }
2805
2806 static void psys_face_mat(Object *ob, DerivedMesh *dm, ParticleData *pa, float mat[][4], int orco)
2807 {
2808         float v[3][3];
2809         MFace *mface;
2810         OrigSpaceFace *osface;
2811         float (*orcodata)[3];
2812
2813         int i = pa->num_dmcache==DMCACHE_NOTFOUND ? pa->num : pa->num_dmcache;
2814         
2815         if (i==-1 || i >= dm->getNumFaces(dm)) { Mat4One(mat); return; }
2816
2817         mface=dm->getFaceData(dm,i,CD_MFACE);
2818         osface=dm->getFaceData(dm,i,CD_ORIGSPACE);
2819         
2820         if(orco && (orcodata=dm->getVertDataArray(dm, CD_ORCO))) {
2821                 VECCOPY(v[0], orcodata[mface->v1]);
2822                 VECCOPY(v[1], orcodata[mface->v2]);
2823                 VECCOPY(v[2], orcodata[mface->v3]);
2824
2825                 /* ugly hack to use non-transformed orcos, since only those
2826                  * give symmetric results for mirroring in particle mode */
2827                 transform_mesh_orco_verts(ob->data, v, 3, 1);
2828         }
2829         else {
2830                 dm->getVertCo(dm,mface->v1,v[0]);
2831                 dm->getVertCo(dm,mface->v2,v[1]);
2832                 dm->getVertCo(dm,mface->v3,v[2]);
2833         }
2834
2835         triatomat(v[0], v[1], v[2], (osface)? osface->uv: NULL, mat);
2836 }
2837
2838 void psys_mat_hair_to_object(Object *ob, DerivedMesh *dm, short from, ParticleData *pa, float hairmat[][4])
2839 {
2840         float vec[3];
2841
2842         psys_face_mat(0, dm, pa, hairmat, 0);
2843         psys_particle_on_dm(ob, dm, from, pa->num, pa->num_dmcache, pa->fuv, pa->foffset, vec, 0, 0, 0, 0, 0);
2844         VECCOPY(hairmat[3],vec);
2845 }
2846
2847 void psys_mat_hair_to_orco(Object *ob, DerivedMesh *dm, short from, ParticleData *pa, float hairmat[][4])
2848 {
2849         float vec[3], orco[3];
2850
2851         psys_face_mat(ob, dm, pa, hairmat, 1);
2852         psys_particle_on_dm(ob, dm, from, pa->num, pa->num_dmcache, pa->fuv, pa->foffset, vec, 0, 0, 0, orco, 0);
2853
2854         /* see psys_face_mat for why this function is called */
2855         transform_mesh_orco_verts(ob->data, &orco, 1, 1);
2856         VECCOPY(hairmat[3],orco);
2857 }
2858
2859 /*
2860 void psys_key_to_geometry(DerivedMesh *dm, ParticleData *pa, ParticleKey *key)
2861 {
2862         float q[4], v1[3], v2[3], v3[3];
2863
2864         dm->getVertCo(dm,pa->verts[0],v1);
2865         dm->getVertCo(dm,pa->verts[1],v2);
2866         dm->getVertCo(dm,pa->verts[2],v3);
2867
2868         triatoquat(v1, v2, v3, q);
2869
2870         QuatInv(q);
2871
2872         VECSUB(key->co,key->co,v1);
2873
2874         VECADD(key->vel,key->vel,key->co);
2875
2876         QuatMulVecf(q, key->co);
2877         QuatMulVecf(q, key->vel);
2878         
2879         VECSUB(key->vel,key->vel,key->co);
2880
2881         QuatMul(key->rot,q,key->rot);
2882 }
2883
2884 void psys_key_from_geometry(DerivedMesh *dm, ParticleData *pa, ParticleKey *key)
2885 {
2886         float q[4], v1[3], v2[3], v3[3];
2887
2888         dm->getVertCo(dm,pa->verts[0],v1);
2889         dm->getVertCo(dm,pa->verts[1],v2);
2890         dm->getVertCo(dm,pa->verts[2],v3);
2891
2892         triatoquat(v1, v2, v3, q);
2893
2894         VECADD(key->vel,key->vel,key->co);
2895
2896         QuatMulVecf(q, key->co);
2897         QuatMulVecf(q, key->vel);
2898         
2899         VECSUB(key->vel,key->vel,key->co);
2900
2901         VECADD(key->co,key->co,v1);
2902
2903         QuatMul(key->rot,q,key->rot);
2904 }
2905 */
2906
2907 void psys_vec_rot_to_face(DerivedMesh *dm, ParticleData *pa, float *vec)//to_geometry(DerivedMesh *dm, ParticleData *pa, float *vec)
2908 {
2909         float mat[4][4];
2910
2911         psys_face_mat(0, dm, pa, mat, 0);
2912         Mat4Transp(mat); /* cheap inverse for rotation matrix */
2913         Mat4Mul3Vecfl(mat, vec);
2914 }
2915
2916 /* unused */
2917 #if 0
2918 static void psys_vec_rot_from_face(DerivedMesh *dm, ParticleData *pa, float *vec)//from_geometry(DerivedMesh *dm, ParticleData *pa, float *vec)
2919 {
2920         float q[4], v1[3], v2[3], v3[3];
2921         /*
2922         dm->getVertCo(dm,pa->verts[0],v1);
2923         dm->getVertCo(dm,pa->verts[1],v2);
2924         dm->getVertCo(dm,pa->verts[2],v3);
2925         */
2926         /* replace with this */
2927         MFace *mface;
2928         int i; // = psys_particle_dm_face_lookup(dm, pa->num, pa->fuv, pa->foffset, (LinkNode*)NULL);
2929         i = pa->num_dmcache==DMCACHE_NOTFOUND ? pa->num : pa->num_dmcache;
2930         if (i==-1 || i >= dm->getNumFaces(dm)) { vec[0] = vec[1] = 0; vec[2] = 1; return; }
2931         mface=dm->getFaceData(dm,i,CD_MFACE);
2932         
2933         dm->getVertCo(dm,mface->v1,v1);
2934         dm->getVertCo(dm,mface->v2,v2);
2935         dm->getVertCo(dm,mface->v3,v3);
2936         /* done */
2937         
2938         triatoquat(v1, v2, v3, q);
2939
2940         QuatMulVecf(q, vec);
2941
2942         //VECADD(vec,vec,v1);
2943 }
2944 #endif
2945
2946 void psys_mat_hair_to_global(Object *ob, DerivedMesh *dm, short from, ParticleData *pa, float hairmat[][4])
2947 {
2948         float facemat[4][4];
2949
2950         psys_mat_hair_to_object(ob, dm, from, pa, facemat);
2951
2952         Mat4MulMat4(hairmat, facemat, ob->obmat);
2953 }
2954
2955 /************************************************/
2956 /*                      ParticleSettings handling                       */
2957 /************************************************/
2958 static void default_particle_settings(ParticleSettings *part)
2959 {
2960         int i;
2961
2962         part->type= PART_EMITTER;
2963         part->distr= PART_DISTR_JIT;
2964         part->draw_as=PART_DRAW_DOT;
2965         part->bb_uv_split=1;
2966         part->bb_align=PART_BB_VIEW;
2967         part->bb_split_offset=PART_BB_OFF_LINEAR;
2968         part->flag=PART_REACT_MULTIPLE|PART_HAIR_GEOMETRY;
2969
2970         part->sta= 1.0;
2971         part->end= 100.0;
2972         part->lifetime= 50.0;
2973         part->jitfac= 1.0;
2974         part->totpart= 1000;
2975         part->grid_res= 10;
2976         part->timetweak= 1.0;
2977         part->keyed_time= 0.5;
2978         //part->userjit;
2979         
2980         part->integrator= PART_INT_MIDPOINT;
2981         part->phystype= PART_PHYS_NEWTON;
2982         part->hair_step= 5;
2983         part->keys_step= 5;
2984         part->draw_step= 2;
2985         part->ren_step= 3;
2986         part->adapt_angle= 5;
2987         part->adapt_pix= 3;
2988         part->kink_axis= 2;
2989         part->reactevent= PART_EVENT_DEATH;
2990         part->disp=100;
2991         part->from= PART_FROM_FACE;
2992         part->length= 1.0;
2993         part->nbetween= 4;
2994         part->boidneighbours= 5;
2995
2996         part->max_vel = 10.0f;
2997         part->average_vel = 0.3f;
2998         part->max_tan_acc = 0.2f;
2999         part->max_lat_acc = 1.0f;
3000
3001         part->reactshape=1.0f;
3002
3003         part->mass=1.0;
3004         part->size=1.0;
3005         part->childsize=1.0;
3006
3007         part->child_nbr=10;
3008         part->ren_child_nbr=100;
3009         part->childrad=0.2f;
3010         part->childflat=0.0f;
3011         part->clumppow=0.0f;
3012         part->kink_amp=0.2f;
3013         part->kink_freq=2.0;
3014
3015         part->rough1_size=1.0;
3016         part->rough2_size=1.0;
3017         part->rough_end_shape=1.0;
3018
3019         part->draw_line[0]=0.5;
3020
3021         part->banking=1.0;
3022         part->max_bank=1.0;
3023
3024         for(i=0; i<BOID_TOT_RULES; i++){
3025                 part->boidrule[i]=(char)i;
3026                 part->boidfac[i]=0.5;
3027         }
3028
3029         part->ipo = NULL;
3030
3031         part->simplify_refsize= 1920;
3032         part->simplify_rate= 1.0f;
3033         part->simplify_transition= 0.1f;
3034         part->simplify_viewport= 0.8;
3035 }
3036
3037
3038 ParticleSettings *psys_new_settings(char *name, Main *main)
3039 {
3040         ParticleSettings *part;
3041
3042         part= alloc_libblock(&main->particle, ID_PA, name);
3043         
3044         default_particle_settings(part);
3045
3046         return part;
3047 }
3048
3049 ParticleSettings *psys_copy_settings(ParticleSettings *part)
3050 {
3051         ParticleSettings *partn;
3052         
3053         partn= copy_libblock(part);
3054         if(partn->pd) partn->pd= MEM_dupallocN(part->pd);
3055         if(partn->pd2) partn->pd2= MEM_dupallocN(part->pd2);
3056         
3057         return partn;
3058 }
3059
3060 void make_local_particlesettings(ParticleSettings *part)
3061 {
3062         Object *ob;
3063         ParticleSettings *par;
3064         int local=0, lib=0;
3065
3066         /* - only lib users: do nothing
3067             * - only local users: set flag
3068             * - mixed: make copy
3069             */
3070         
3071         if(part->id.lib==0) return;
3072         if(part->id.us==1) {
3073                 part->id.lib= 0;
3074                 part->id.flag= LIB_LOCAL;
3075                 new_id(0, (ID *)part, 0);
3076                 return;
3077         }
3078         
3079         /* test objects */
3080         ob= G.main->object.first;
3081         while(ob) {
3082                 ParticleSystem *psys=ob->particlesystem.first;
3083                 for(; psys; psys=psys->next){
3084                         if(psys->part==part) {
3085                                 if(ob->id.lib) lib= 1;
3086                                 else local= 1;
3087                         }
3088                 }
3089                 ob= ob->id.next;
3090         }
3091         
3092         if(local && lib==0) {
3093                 part->id.lib= 0;
3094                 part->id.flag= LIB_LOCAL;
3095                 new_id(0, (ID *)part, 0);
3096         }
3097         else if(local && lib) {
3098                 
3099                 par= psys_copy_settings(part);
3100                 par->id.us= 0;
3101                 
3102                 /* do objects */
3103                 ob= G.main->object.first;
3104                 while(ob) {
3105                         ParticleSystem *psys=ob->particlesystem.first;
3106                         for(; psys; psys=psys->next){
3107                                 if(psys->part==part && ob->id.lib==0) {
3108                                         psys->part= par;
3109                                         par->id.us++;
3110                                         part->id.us--;
3111                                 }
3112                         }
3113                         ob= ob->id.next;
3114                 }
3115         }
3116 }
3117
3118 /* should be integrated to depgraph signals */
3119 void psys_flush_settings(ParticleSettings *part, int event, int hair_recalc)
3120 {
3121         Base *base;
3122         Object *ob, *tob;
3123         ParticleSystem *psys;
3124         int flush;
3125
3126         /* update all that have same particle settings */
3127         for(base = G.scene->base.first; base; base= base->next) {
3128                 if(base->object->particlesystem.first) {