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