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