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