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