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