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