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