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