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