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