General particle bug fixes + few small goodies
[blender.git] / source / blender / blenkernel / intern / effect.c
1 /*  effect.c
2  * 
3  * 
4  * $Id$
5  *
6  * ***** BEGIN GPL LICENSE BLOCK *****
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License
10  * as published by the Free Software Foundation; either version 2
11  * of the License, or (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software Foundation,
20  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
21  *
22  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
23  * All rights reserved.
24  *
25  * The Original Code is: all of this file.
26  *
27  * Contributor(s): none yet.
28  *
29  * ***** END GPL LICENSE BLOCK *****
30  */
31
32 #include "BLI_storage.h" /* _LARGEFILE_SOURCE */
33
34 #include <math.h>
35 #include <stdlib.h>
36
37 #include "MEM_guardedalloc.h"
38
39 #include "DNA_curve_types.h"
40 #include "DNA_effect_types.h"
41 #include "DNA_group_types.h"
42 #include "DNA_ipo_types.h"
43 #include "DNA_key_types.h"
44 #include "DNA_lattice_types.h"
45 #include "DNA_listBase.h"
46 #include "DNA_mesh_types.h"
47 #include "DNA_meshdata_types.h"
48 #include "DNA_material_types.h"
49 #include "DNA_object_types.h"
50 #include "DNA_object_force.h"
51 #include "DNA_particle_types.h"
52 #include "DNA_texture_types.h"
53 #include "DNA_scene_types.h"
54
55 #include "BLI_arithb.h"
56 #include "BLI_blenlib.h"
57 #include "BLI_jitter.h"
58 #include "BLI_listbase.h"
59 #include "BLI_noise.h"
60 #include "BLI_rand.h"
61
62 #include "PIL_time.h"
63
64 #include "BKE_action.h"
65 #include "BKE_anim.h"           /* needed for where_on_path */
66 #include "BKE_armature.h"
67 #include "BKE_blender.h"
68 #include "BKE_collision.h"
69 #include "BKE_constraint.h"
70 #include "BKE_deform.h"
71 #include "BKE_depsgraph.h"
72 #include "BKE_displist.h"
73 #include "BKE_DerivedMesh.h"
74 #include "BKE_cdderivedmesh.h"
75 #include "BKE_effect.h"
76 #include "BKE_global.h"
77 #include "BKE_group.h"
78 #include "BKE_ipo.h"
79 #include "BKE_key.h"
80 #include "BKE_lattice.h"
81 #include "BKE_mesh.h"
82 #include "BKE_material.h"
83 #include "BKE_main.h"
84 #include "BKE_modifier.h"
85 #include "BKE_object.h"
86 #include "BKE_particle.h"
87 #include "BKE_scene.h"
88 #include "BKE_screen.h"
89 #include "BKE_utildefines.h"
90
91 #include "RE_render_ext.h"
92 #include "RE_shader_ext.h"
93
94 /* fluid sim particle import */
95 #ifndef DISABLE_ELBEEM
96 #include "DNA_object_fluidsim.h"
97 #include "LBM_fluidsim.h"
98 #include <zlib.h>
99 #include <string.h>
100 #endif // DISABLE_ELBEEM
101
102 //XXX #include "BIF_screen.h"
103
104 EffectorWeights *BKE_add_effector_weights(Group *group)
105 {
106         EffectorWeights *weights = MEM_callocN(sizeof(EffectorWeights), "EffectorWeights");
107         int i;
108
109         for(i=0; i<NUM_PFIELD_TYPES; i++)
110                 weights->weight[i] = 1.0f;
111
112         weights->global_gravity = 1.0f;
113
114         weights->group = group;
115
116         return weights;
117 }
118 PartDeflect *object_add_collision_fields(int type)
119 {
120         PartDeflect *pd;
121
122         pd= MEM_callocN(sizeof(PartDeflect), "PartDeflect");
123
124         pd->forcefield = type;
125         pd->pdef_sbdamp = 0.1f;
126         pd->pdef_sbift  = 0.2f;
127         pd->pdef_sboft  = 0.02f;
128         pd->seed = ((unsigned int)(ceil(PIL_check_seconds_timer()))+1) % 128;
129         pd->f_strength = 1.0f;
130         pd->f_damp = 1.0f;
131         pd->f_size = 1.0f;
132
133         /* set sensible defaults based on type */
134         switch(type) {
135                 case PFIELD_VORTEX:
136                         pd->shape = PFIELD_SHAPE_PLANE;
137                         break;
138                 case PFIELD_WIND:
139                         pd->shape = PFIELD_SHAPE_PLANE;
140                         pd->f_flow = 1.0f; /* realistic wind behavior */
141                         break;
142         }
143         pd->flag = PFIELD_DO_LOCATION|PFIELD_DO_ROTATION;
144
145         return pd;
146 }
147
148 /* temporal struct, used for reading return of mesh_get_mapped_verts_nors() */
149
150 typedef struct VeNoCo {
151         float co[3], no[3];
152 } VeNoCo;
153
154 /* ***************** PARTICLES ***************** */
155
156 /* deprecated, only keep this for readfile.c */
157 PartEff *give_parteff(Object *ob)
158 {
159         PartEff *paf;
160         
161         paf= ob->effect.first;
162         while(paf) {
163                 if(paf->type==EFF_PARTICLE) return paf;
164                 paf= paf->next;
165         }
166         return 0;
167 }
168
169 void free_effect(Effect *eff)
170 {
171         PartEff *paf;
172         
173         if(eff->type==EFF_PARTICLE) {
174                 paf= (PartEff *)eff;
175                 if(paf->keys) MEM_freeN(paf->keys);
176         }
177         MEM_freeN(eff); 
178 }
179
180
181 void free_effects(ListBase *lb)
182 {
183         Effect *eff;
184         
185         eff= lb->first;
186         while(eff) {
187                 BLI_remlink(lb, eff);
188                 free_effect(eff);
189                 eff= lb->first;
190         }
191 }
192
193 /* -------------------------- Effectors ------------------ */
194 void free_partdeflect(PartDeflect *pd)
195 {
196         if(!pd)
197                 return;
198
199         if(pd->tex)
200                 pd->tex->id.us--;
201
202         if(pd->rng)
203                 rng_free(pd->rng);
204
205         MEM_freeN(pd);
206 }
207
208 static void precalculate_effector(EffectorCache *eff)
209 {
210         unsigned int cfra = (unsigned int)(eff->scene->r.cfra >= 0 ? eff->scene->r.cfra : -eff->scene->r.cfra);
211         if(!eff->pd->rng)
212                 eff->pd->rng = rng_new(eff->pd->seed + cfra);
213         else
214                 rng_srandom(eff->pd->rng, eff->pd->seed + cfra);
215
216         if(eff->pd->forcefield == PFIELD_GUIDE && eff->ob->type==OB_CURVE) {
217                 Curve *cu= eff->ob->data;
218                 if(cu->flag & CU_PATH) {
219                         if(cu->path==NULL || cu->path->data==NULL)
220                                 makeDispListCurveTypes(eff->scene, eff->ob, 0);
221
222                         if(cu->path && cu->path->data) {
223                                 where_on_path(eff->ob, 0.0, eff->guide_loc, eff->guide_dir, NULL, &eff->guide_radius);
224                                 Mat4MulVecfl(eff->ob->obmat, eff->guide_loc);
225                                 Mat4Mul3Vecfl(eff->ob->obmat, eff->guide_dir);
226                         }
227                 }
228         }
229         else if(eff->pd->shape == PFIELD_SHAPE_SURFACE) {
230                 eff->surmd = (SurfaceModifierData *)modifiers_findByType ( eff->ob, eModifierType_Surface );
231                 if(eff->ob->type == OB_CURVE)
232                         eff->flag |= PE_USE_NORMAL_DATA;
233         }
234         else if(eff->psys)
235                 psys_update_particle_tree(eff->psys, eff->scene->r.cfra);
236 }
237 static EffectorCache *new_effector_cache(Scene *scene, Object *ob, ParticleSystem *psys, PartDeflect *pd)
238 {
239         EffectorCache *eff = MEM_callocN(sizeof(EffectorCache), "EffectorCache");
240         eff->scene = scene;
241         eff->ob = ob;
242         eff->psys = psys;
243         eff->pd = pd;
244         eff->frame = -1;
245
246         precalculate_effector(eff);
247
248         return eff;
249 }
250 static void add_object_to_effectors(ListBase **effectors, Scene *scene, EffectorWeights *weights, Object *ob, Object *ob_src)
251 {
252         EffectorCache *eff = NULL;
253
254         if( ob == ob_src || weights->weight[ob->pd->forcefield] == 0.0f )
255                 return;
256
257         if (ob->pd->shape == PFIELD_SHAPE_POINTS && !ob->derivedFinal )
258                 return;
259
260         if(*effectors == NULL)
261                 *effectors = MEM_callocN(sizeof(ListBase), "effectors list");
262
263         eff = new_effector_cache(scene, ob, NULL, ob->pd);
264
265         BLI_addtail(*effectors, eff);
266 }
267 static void add_particles_to_effectors(ListBase **effectors, Scene *scene, EffectorWeights *weights, Object *ob, ParticleSystem *psys, ParticleSystem *psys_src)
268 {
269         ParticleSettings *part= psys->part;
270
271         if( !psys_check_enabled(ob, psys) )
272                 return;
273
274         if( psys == psys_src && (part->flag & PART_SELF_EFFECT) == 0)
275                 return;
276
277         if( part->pd && part->pd->forcefield && weights->weight[part->pd->forcefield] != 0.0f) {
278                 if(*effectors == NULL)
279                         *effectors = MEM_callocN(sizeof(ListBase), "effectors list");
280
281                 BLI_addtail(*effectors, new_effector_cache(scene, ob, psys, part->pd));
282         }
283
284         if (part->pd2 && part->pd2->forcefield && weights->weight[part->pd2->forcefield] != 0.0f) {
285                 if(*effectors == NULL)
286                         *effectors = MEM_callocN(sizeof(ListBase), "effectors list");
287
288                 BLI_addtail(*effectors, new_effector_cache(scene, ob, psys, part->pd2));
289         }
290 }
291
292 /* returns ListBase handle with objects taking part in the effecting */
293 ListBase *pdInitEffectors(Scene *scene, Object *ob_src, ParticleSystem *psys_src, EffectorWeights *weights)
294 {
295         Base *base;
296         unsigned int layer= ob_src->lay;
297         ListBase *effectors = NULL;
298         
299         if(weights->group) {
300                 GroupObject *go;
301                 
302                 for(go= weights->group->gobject.first; go; go= go->next) {
303                         if( (go->ob->lay & layer) ) {
304                                 if( go->ob->pd && go->ob->pd->forcefield )
305                                         add_object_to_effectors(&effectors, scene, weights, go->ob, ob_src);
306
307                                 if( go->ob->particlesystem.first ) {
308                                         ParticleSystem *psys= go->ob->particlesystem.first;
309
310                                         for( ; psys; psys=psys->next )
311                                                 add_particles_to_effectors(&effectors, scene, weights, go->ob, psys, psys_src);
312                                 }
313                         }
314                 }
315         }
316         else {
317                 for(base = scene->base.first; base; base= base->next) {
318                         if( (base->lay & layer) ) {
319                                 if( base->object->pd && base->object->pd->forcefield )
320                                 add_object_to_effectors(&effectors, scene, weights, base->object, ob_src);
321
322                                 if( base->object->particlesystem.first ) {
323                                         ParticleSystem *psys= base->object->particlesystem.first;
324
325                                         for( ; psys; psys=psys->next )
326                                                 add_particles_to_effectors(&effectors, scene, weights, base->object, psys, psys_src);
327                                 }
328                         }
329                 }
330         }
331         return effectors;
332 }
333
334 void pdEndEffectors(ListBase **effectors)
335 {
336         if(*effectors) {
337                 EffectorCache *eff = (*effectors)->first;
338
339                 for(; eff; eff=eff->next) {
340                         if(eff->guide_data)
341                                 MEM_freeN(eff->guide_data);
342                 }
343
344                 BLI_freelistN(*effectors);
345                 MEM_freeN(*effectors);
346                 *effectors = NULL;
347         }
348 }
349
350
351 void pd_point_from_particle(ParticleSimulationData *sim, ParticleData *pa, ParticleKey *state, EffectedPoint *point)
352 {
353         point->loc = state->co;
354         point->vel = state->vel;
355         point->index = pa - sim->psys->particles;
356         point->size = pa->size;
357         /* TODO: point->charge */
358         point->charge = 1.0f;
359
360         point->vel_to_sec = 1.0f;
361         point->vel_to_frame = psys_get_timestep(sim);
362
363         point->flag = 0;
364
365         if(sim->psys->part->flag & PART_ROT_DYN) {
366                 point->ave = state->ave;
367                 point->rot = state->rot;
368         }
369         else
370                 point->ave = point->rot = NULL;
371
372         point->psys = sim->psys;
373 }
374
375 void pd_point_from_loc(Scene *scene, float *loc, float *vel, int index, EffectedPoint *point)
376 {
377         point->loc = loc;
378         point->vel = vel;
379         point->index = index;
380         point->size = 0.0f;
381
382         point->vel_to_sec = (float)scene->r.frs_sec;
383         point->vel_to_frame = 1.0f;
384
385         point->flag = 0;
386
387         point->ave = point->rot = NULL;
388         point->psys = NULL;
389 }
390 void pd_point_from_soft(Scene *scene, float *loc, float *vel, int index, EffectedPoint *point)
391 {
392         point->loc = loc;
393         point->vel = vel;
394         point->index = index;
395         point->size = 0.0f;
396
397         point->vel_to_sec = (float)scene->r.frs_sec;
398         point->vel_to_frame = 1.0f;
399
400         point->flag = PE_WIND_AS_SPEED;
401
402         point->ave = point->rot = NULL;
403
404         point->psys = NULL;
405 }
406 /************************************************/
407 /*                      Effectors               */
408 /************************************************/
409
410 // triangle - ray callback function
411 static void eff_tri_ray_hit(void *userdata, int index, const BVHTreeRay *ray, BVHTreeRayHit *hit)
412 {       
413         // whenever we hit a bounding box, we don't check further
414         hit->dist = -1;
415         hit->index = 1;
416 }
417
418 // get visibility of a wind ray
419 static float eff_calc_visibility(ListBase *colliders, EffectorCache *eff, EffectorData *efd, EffectedPoint *point)
420 {
421         ListBase *colls = colliders;
422         ColliderCache *col;
423         float norm[3], len = 0.0;
424         float visibility = 1.0, absorption = 0.0;
425         
426         if(!(eff->pd->flag & PFIELD_VISIBILITY))
427                 return visibility;
428
429         if(!colls)
430                 colls = get_collider_cache(eff->scene, NULL);
431
432         if(!colls)
433                 return visibility;
434         
435         VECCOPY(norm, efd->vec_to_point);
436         VecNegf(norm);
437         len = Normalize(norm);
438         
439         // check all collision objects
440         for(col = colls->first; col; col = col->next)
441         {
442                 CollisionModifierData *collmd = col->collmd;
443
444                 if(col->ob == eff->ob)
445                         continue;
446                 
447                 if(collmd->bvhtree)
448                 {
449                         BVHTreeRayHit hit;
450                         
451                         hit.index = -1;
452                         hit.dist = len + FLT_EPSILON;
453                         
454                         // check if the way is blocked
455                         if(BLI_bvhtree_ray_cast(collmd->bvhtree, point->loc, norm, 0.0f, &hit, eff_tri_ray_hit, NULL)>=0)
456                         {
457                                 absorption= col->ob->pd->absorption;
458
459                                 // visibility is only between 0 and 1, calculated from 1-absorption
460                                 visibility *= CLAMPIS(1.0f-absorption, 0.0f, 1.0f);
461                                 
462                                 if(visibility <= 0.0f)
463                                         break;
464                         }
465                 }
466         }
467
468         if(!colliders)
469                 free_collider_cache(&colls);
470         
471         return visibility;
472 }
473
474 // noise function for wind e.g.
475 static float wind_func(struct RNG *rng, float strength)
476 {
477         int random = (rng_getInt(rng)+1) % 128; // max 2357
478         float force = rng_getFloat(rng) + 1.0f;
479         float ret;
480         float sign = 0;
481         
482         sign = ((float)random > 64.0) ? 1.0: -1.0; // dividing by 2 is not giving equal sign distribution
483         
484         ret = sign*((float)random / force)*strength/128.0f;
485         
486         return ret;
487 }
488
489 /* maxdist: zero effect from this distance outwards (if usemax) */
490 /* mindist: full effect up to this distance (if usemin) */
491 /* power: falloff with formula 1/r^power */
492 static float falloff_func(float fac, int usemin, float mindist, int usemax, float maxdist, float power)
493 {
494         /* first quick checks */
495         if(usemax && fac > maxdist)
496                 return 0.0f;
497
498         if(usemin && fac < mindist)
499                 return 1.0f;
500
501         if(!usemin)
502                 mindist = 0.0;
503
504         return pow((double)1.0+fac-mindist, (double)-power);
505 }
506
507 static float falloff_func_dist(PartDeflect *pd, float fac)
508 {
509         return falloff_func(fac, pd->flag&PFIELD_USEMIN, pd->mindist, pd->flag&PFIELD_USEMAX, pd->maxdist, pd->f_power);
510 }
511
512 static float falloff_func_rad(PartDeflect *pd, float fac)
513 {
514         return falloff_func(fac, pd->flag&PFIELD_USEMINR, pd->minrad, pd->flag&PFIELD_USEMAXR, pd->maxrad, pd->f_power_r);
515 }
516
517 float effector_falloff(EffectorCache *eff, EffectorData *efd, EffectedPoint *point, EffectorWeights *weights)
518 {
519         float temp[3];
520         float falloff = weights ? weights->weight[0] * weights->weight[eff->pd->forcefield] : 1.0f;
521         float fac, r_fac;
522
523         fac = Inpf(efd->nor, efd->vec_to_point2);
524
525         if(eff->pd->zdir == PFIELD_Z_POS && fac < 0.0f)
526                 falloff=0.0f;
527         else if(eff->pd->zdir == PFIELD_Z_NEG && fac > 0.0f)
528                 falloff=0.0f;
529         else switch(eff->pd->falloff){
530                 case PFIELD_FALL_SPHERE:
531                         falloff*= falloff_func_dist(eff->pd, efd->distance);
532                         break;
533
534                 case PFIELD_FALL_TUBE:
535                         falloff*= falloff_func_dist(eff->pd, ABS(fac));
536                         if(falloff == 0.0f)
537                                 break;
538
539                         VECADDFAC(temp, efd->vec_to_point, efd->nor, -fac);
540                         r_fac= VecLength(temp);
541                         falloff*= falloff_func_rad(eff->pd, r_fac);
542                         break;
543                 case PFIELD_FALL_CONE:
544                         falloff*= falloff_func_dist(eff->pd, ABS(fac));
545                         if(falloff == 0.0f)
546                                 break;
547
548                         r_fac=saacos(fac/VecLength(efd->vec_to_point))*180.0f/(float)M_PI;
549                         falloff*= falloff_func_rad(eff->pd, r_fac);
550
551                         break;
552         }
553
554         return falloff;
555 }
556
557 int closest_point_on_surface(SurfaceModifierData *surmd, float *co, float *surface_co, float *surface_nor, float *surface_vel)
558 {
559         BVHTreeNearest nearest;
560
561         nearest.index = -1;
562         nearest.dist = FLT_MAX;
563
564         BLI_bvhtree_find_nearest(surmd->bvhtree->tree, co, &nearest, surmd->bvhtree->nearest_callback, surmd->bvhtree);
565
566         if(nearest.index != -1) {
567                 VECCOPY(surface_co, nearest.co);
568
569                 if(surface_nor) {
570                         VECCOPY(surface_nor, nearest.no);
571                 }
572
573                 if(surface_vel) {
574                         MFace *mface = CDDM_get_face(surmd->dm, nearest.index);
575                         
576                         VECCOPY(surface_vel, surmd->v[mface->v1].co);
577                         VecAddf(surface_vel, surface_vel, surmd->v[mface->v2].co);
578                         VecAddf(surface_vel, surface_vel, surmd->v[mface->v3].co);
579                         if(mface->v4)
580                                 VecAddf(surface_vel, surface_vel, surmd->v[mface->v4].co);
581
582                         VecMulf(surface_vel, mface->v4 ? 0.25f : 0.333f);
583                 }
584                 return 1;
585         }
586
587         return 0;
588 }
589 int get_effector_data(EffectorCache *eff, EffectorData *efd, EffectedPoint *point, int real_velocity)
590 {
591         float cfra = eff->scene->r.cfra;
592         int ret = 0;
593
594         if(eff->pd->shape==PFIELD_SHAPE_SURFACE && eff->surmd) {
595                 /* closest point in the object surface is an effector */
596                 float vec[3];
597
598                 /* using velocity corrected location allows for easier sliding over effector surface */
599                 VecCopyf(vec, point->vel);
600                 VecMulf(vec, point->vel_to_frame);
601                 VecAddf(vec, vec, point->loc);
602
603                 ret = closest_point_on_surface(eff->surmd, vec, efd->loc, efd->nor, real_velocity ? efd->vel : NULL);
604
605                 efd->size = 0.0f;
606         }
607         else if(eff->pd->shape==PFIELD_SHAPE_POINTS) {
608
609                 if(eff->ob->derivedFinal) {
610                         DerivedMesh *dm = eff->ob->derivedFinal;
611
612                         dm->getVertCo(dm, *efd->index, efd->loc);
613                         dm->getVertNo(dm, *efd->index, efd->nor);
614
615                         Mat4MulVecfl(eff->ob->obmat, efd->loc);
616                         Mat4Mul3Vecfl(eff->ob->obmat, efd->nor);
617
618                         Normalize(efd->nor);
619
620                         efd->size = 0.0f;
621
622                         /**/
623                         ret = 1;
624                 }
625         }
626         else if(eff->psys) {
627                 ParticleSimulationData sim = {eff->scene, eff->ob, eff->psys, NULL, NULL};
628                 ParticleData *pa = eff->psys->particles + *efd->index;
629                 ParticleKey state;
630
631                 /* exclude the particle itself for self effecting particles */
632                 if(eff->psys == point->psys && *efd->index == point->index)
633                         ;
634                 else {
635                         /* TODO: time from actual previous calculated frame (step might not be 1) */
636                         state.time = cfra - 1.0;
637                         ret = psys_get_particle_state(&sim, *efd->index, &state, 0);
638
639                         /* TODO */
640                         //if(eff->pd->forcefiled == PFIELD_HARMONIC && ret==0) {
641                         //      if(pa->dietime < eff->psys->cfra)
642                         //              eff->flag |= PE_VELOCITY_TO_IMPULSE;
643                         //}
644
645                         VECCOPY(efd->loc, state.co);
646                         VECCOPY(efd->nor, state.vel);
647                         if(real_velocity) {
648                                 VECCOPY(efd->vel, state.vel);
649                         }
650
651                         efd->size = pa->size;
652                 }
653         }
654         else {
655                 /* use center of object for distance calculus */
656                 Object *ob = eff->ob;
657                 Object obcopy = *ob;
658
659                 where_is_object_time(eff->scene, ob, cfra);
660
661                 /* use z-axis as normal*/
662                 VECCOPY(efd->nor, ob->obmat[2]);
663                 Normalize(efd->nor);
664
665                 /* for vortex the shape chooses between old / new force */
666                 if(eff->pd->shape == PFIELD_SHAPE_PLANE) {
667                         /* efd->loc is closes point on effector xy-plane */
668                         float temp[3];
669                         VecSubf(temp, point->loc, ob->obmat[3]);
670                         Projf(efd->loc, temp, efd->nor);
671                         VecSubf(efd->loc, point->loc, efd->loc);
672                 }
673                 else {
674                         VECCOPY(efd->loc, ob->obmat[3]);
675                 }
676
677                 if(real_velocity) {
678                         VECCOPY(efd->vel, ob->obmat[3]);
679
680                         where_is_object_time(eff->scene, ob, cfra - 1.0);
681
682                         VecSubf(efd->vel, efd->vel, ob->obmat[3]);
683                 }
684
685                 *eff->ob = obcopy;
686
687                 efd->size = 0.0f;
688
689                 ret = 1;
690         }
691
692         if(ret) {
693                 VecSubf(efd->vec_to_point, point->loc, efd->loc);
694                 efd->distance = VecLength(efd->vec_to_point);
695
696                 if(eff->flag & PE_USE_NORMAL_DATA) {
697                         VECCOPY(efd->vec_to_point2, efd->vec_to_point);
698                         VECCOPY(efd->nor2, efd->nor);
699                 }
700                 else {
701                         /* for some effectors we need the object center every time */
702                         VecSubf(efd->vec_to_point2, point->loc, eff->ob->obmat[3]);
703                         VECCOPY(efd->nor2, eff->ob->obmat[2]);
704                         Normalize(efd->nor2);
705                 }
706         }
707
708         return ret;
709 }
710 static void get_effector_tot(EffectorCache *eff, EffectorData *efd, EffectedPoint *point, int *tot, int *p)
711 {
712         if(eff->pd->shape == PFIELD_SHAPE_POINTS) {
713                 efd->index = p;
714
715                 *p = 0;
716                 *tot = eff->ob->derivedFinal ? eff->ob->derivedFinal->numVertData : 1;
717
718                 if(*tot && eff->pd->forcefield == PFIELD_HARMONIC && point->index >= 0) {
719                         *p = point->index % *tot;
720                         *tot = *p+1;
721                 }
722         }
723         else if(eff->psys) {
724                 efd->index = p;
725
726                 *p = 0;
727                 *tot = eff->psys->totpart;
728                 
729                 if(eff->pd->forcefield == PFIELD_CHARGE) {
730                         /* Only the charge of the effected particle is used for 
731                         interaction, not fall-offs. If the fall-offs aren't the 
732                         same this will be unphysical, but for animation this            
733                         could be the wanted behavior. If you want physical
734                         correctness the fall-off should be spherical 2.0 anyways.
735                         */
736                         efd->charge = eff->pd->f_strength;
737                 }
738                 else if(eff->pd->forcefield == PFIELD_HARMONIC) {
739                         /* every particle is mapped to only one harmonic effector particle */
740                         *p= point->index % eff->psys->totpart;
741                         *tot= *p + 1;
742                 }
743         }
744         else {
745                 *p = 0;
746                 *tot = 1;
747         }
748 }
749 static void do_texture_effector(EffectorCache *eff, EffectorData *efd, EffectedPoint *point, float *total_force)
750 {
751         TexResult result[4];
752         float tex_co[3], strength, force[3];
753         float nabla = eff->pd->tex_nabla;
754         int hasrgb;
755         short mode = eff->pd->tex_mode;
756
757         if(!eff->pd->tex)
758                 return;
759
760         result[0].nor = result[1].nor = result[2].nor = result[3].nor = 0;
761
762         strength= eff->pd->f_strength * efd->falloff;
763
764         VECCOPY(tex_co,point->loc);
765
766         if(eff->pd->flag & PFIELD_TEX_2D) {
767                 float fac=-Inpf(tex_co, efd->nor);
768                 VECADDFAC(tex_co, tex_co, efd->nor, fac);
769         }
770
771         if(eff->pd->flag & PFIELD_TEX_OBJECT) {
772                 Mat4Mul3Vecfl(eff->ob->obmat, tex_co);
773         }
774
775         hasrgb = multitex_ext(eff->pd->tex, tex_co, NULL,NULL, 1, result);
776
777         if(hasrgb && mode==PFIELD_TEX_RGB) {
778                 force[0] = (0.5f - result->tr) * strength;
779                 force[1] = (0.5f - result->tg) * strength;
780                 force[2] = (0.5f - result->tb) * strength;
781         }
782         else {
783                 strength/=nabla;
784
785                 tex_co[0] += nabla;
786                 multitex_ext(eff->pd->tex, tex_co, NULL, NULL, 1, result+1);
787
788                 tex_co[0] -= nabla;
789                 tex_co[1] += nabla;
790                 multitex_ext(eff->pd->tex, tex_co, NULL, NULL, 1, result+2);
791
792                 tex_co[1] -= nabla;
793                 tex_co[2] += nabla;
794                 multitex_ext(eff->pd->tex, tex_co, NULL, NULL, 1, result+3);
795
796                 if(mode == PFIELD_TEX_GRAD || !hasrgb) { /* if we dont have rgb fall back to grad */
797                         force[0] = (result[0].tin - result[1].tin) * strength;
798                         force[1] = (result[0].tin - result[2].tin) * strength;
799                         force[2] = (result[0].tin - result[3].tin) * strength;
800                 }
801                 else { /*PFIELD_TEX_CURL*/
802                         float dbdy, dgdz, drdz, dbdx, dgdx, drdy;
803
804                         dbdy = result[2].tb - result[0].tb;
805                         dgdz = result[3].tg - result[0].tg;
806                         drdz = result[3].tr - result[0].tr;
807                         dbdx = result[1].tb - result[0].tb;
808                         dgdx = result[1].tg - result[0].tg;
809                         drdy = result[2].tr - result[0].tr;
810
811                         force[0] = (dbdy - dgdz) * strength;
812                         force[1] = (drdz - dbdx) * strength;
813                         force[2] = (dgdx - drdy) * strength;
814                 }
815         }
816
817         if(eff->pd->flag & PFIELD_TEX_2D){
818                 float fac = -Inpf(force, efd->nor);
819                 VECADDFAC(force, force, efd->nor, fac);
820         }
821
822         VecAddf(total_force, total_force, force);
823 }
824 void do_physical_effector(EffectorCache *eff, EffectorData *efd, EffectedPoint *point, float *total_force)
825 {
826         PartDeflect *pd = eff->pd;
827         RNG *rng = pd->rng;
828         float force[3]={0,0,0};
829         float temp[3];
830         float fac;
831         float strength = pd->f_strength;
832         float damp = pd->f_damp;
833         float noise_factor = pd->f_noise;
834
835         if(noise_factor > 0.0f) {
836                 strength += wind_func(rng, noise_factor);
837
838                 if(ELEM(pd->forcefield, PFIELD_HARMONIC, PFIELD_DRAG))
839                         damp += wind_func(rng, noise_factor);
840         }
841
842         VECCOPY(force, efd->vec_to_point);
843
844         switch(pd->forcefield){
845                 case PFIELD_WIND:
846                         VECCOPY(force, efd->nor);
847                         VecMulf(force, strength * efd->falloff);
848                         break;
849                 case PFIELD_FORCE:
850                         Normalize(force);
851                         VecMulf(force, strength * efd->falloff);
852                         break;
853                 case PFIELD_VORTEX:
854                         /* old vortex force */
855                         if(pd->shape == PFIELD_SHAPE_POINT) {
856                                 Crossf(force, efd->nor, efd->vec_to_point);
857                                 Normalize(force);
858                                 VecMulf(force, strength * efd->distance * efd->falloff);
859                         }
860                         else {
861                                 /* new vortex force */
862                                 Crossf(temp, efd->nor2, efd->vec_to_point2);
863                                 VecMulf(temp, strength * efd->falloff);
864                                 
865                                 Crossf(force, efd->nor2, temp);
866                                 VecMulf(force, strength * efd->falloff);
867                                 
868                                 VECADDFAC(temp, temp, point->vel, -point->vel_to_sec);
869                                 VecAddf(force, force, temp);
870                         }
871                         break;
872                 case PFIELD_MAGNET:
873                         if(eff->pd->shape == PFIELD_SHAPE_POINT)
874                                 /* magnetic field of a moving charge */
875                                 Crossf(temp, efd->nor, efd->vec_to_point);
876                         else
877                                 VecCopyf(temp, efd->nor);
878
879                         Normalize(temp);
880                         VecMulf(temp, strength * efd->falloff);
881                         Crossf(force, point->vel, temp);
882                         VecMulf(force, point->vel_to_sec);
883                         break;
884                 case PFIELD_HARMONIC:
885                         VecMulf(force, -strength * efd->falloff);
886                         VecCopyf(temp, point->vel);
887                         VecMulf(temp, -damp * 2.0f * (float)sqrt(fabs(strength)) * point->vel_to_sec);
888                         VecAddf(force, force, temp);
889                         break;
890                 case PFIELD_CHARGE:
891                         VecMulf(force, point->charge * strength * efd->falloff);
892                         break;
893                 case PFIELD_LENNARDJ:
894                         fac = pow((efd->size + point->size) / efd->distance, 6.0);
895                         
896                         fac = - fac * (1.0 - fac) / efd->distance;
897
898                         /* limit the repulsive term drastically to avoid huge forces */
899                         fac = ((fac>2.0) ? 2.0 : fac);
900
901                         VecMulf(force, strength * fac);
902                         break;
903                 case PFIELD_BOID:
904                         /* Boid field is handled completely in boids code. */
905                         return;
906                 case PFIELD_TURBULENCE:
907                         if(pd->flag & PFIELD_GLOBAL_CO) {
908                                 VECCOPY(temp, point->loc);
909                         }
910                         else {
911                                 VECADD(temp, efd->vec_to_point2, efd->nor2);
912                         }
913                         force[0] = -1.0f + 2.0f * BLI_gTurbulence(pd->f_size, temp[0], temp[1], temp[2], 2,0,2);
914                         force[1] = -1.0f + 2.0f * BLI_gTurbulence(pd->f_size, temp[1], temp[2], temp[0], 2,0,2);
915                         force[2] = -1.0f + 2.0f * BLI_gTurbulence(pd->f_size, temp[2], temp[0], temp[1], 2,0,2);
916                         VecMulf(force, strength * efd->falloff);
917                         break;
918                 case PFIELD_DRAG:
919                         VECCOPY(force, point->vel);
920                         fac = Normalize(force) * point->vel_to_sec;
921
922                         strength = MIN2(strength, 2.0f);
923                         damp = MIN2(damp, 2.0f);
924
925                         VecMulf(force, -efd->falloff * fac * (strength * fac + damp));
926                         break;
927         }
928
929         if(pd->flag & PFIELD_DO_LOCATION) {
930                 VECADDFAC(total_force, total_force, force, 1.0f/point->vel_to_sec);
931
932                 if(ELEM(pd->forcefield, PFIELD_HARMONIC, PFIELD_DRAG)==0 && pd->f_flow != 0.0f) {
933                         VECADDFAC(total_force, total_force, point->vel, -pd->f_flow * efd->falloff);
934                 }
935         }
936
937         if(pd->flag & PFIELD_DO_ROTATION && point->ave && point->rot) {
938                 float xvec[3] = {1.0f, 0.0f, 0.0f};
939                 float dave[3];
940                 QuatMulVecf(point->rot, xvec);
941                 Crossf(dave, xvec, force);
942                 if(pd->f_flow != 0.0f) {
943                         VECADDFAC(dave, dave, point->ave, -pd->f_flow * efd->falloff);
944                 }
945                 VecAddf(point->ave, point->ave, dave);
946         }
947 }
948
949 /*  -------- pdDoEffectors() --------
950     generic force/speed system, now used for particles and softbodies
951     scene       = scene where it runs in, for time and stuff
952         lb                      = listbase with objects that take part in effecting
953         opco            = global coord, as input
954     force               = force accumulator
955     speed               = actual current speed which can be altered
956         cur_time        = "external" time in frames, is constant for static particles
957         loc_time        = "local" time in frames, range <0-1> for the lifetime of particle
958     par_layer   = layer the caller is in
959         flags           = only used for softbody wind now
960         guide           = old speed of particle
961
962 */
963 void pdDoEffectors(ListBase *effectors, ListBase *colliders, EffectorWeights *weights, EffectedPoint *point, float *force, float *impulse)
964 {
965 /*
966         Modifies the force on a particle according to its
967         relation with the effector object
968         Different kind of effectors include:
969                 Forcefields: Gravity-like attractor
970                 (force power is related to the inverse of distance to the power of a falloff value)
971                 Vortex fields: swirling effectors
972                 (particles rotate around Z-axis of the object. otherwise, same relation as)
973                 (Forcefields, but this is not done through a force/acceleration)
974                 Guide: particles on a path
975                 (particles are guided along a curve bezier or old nurbs)
976                 (is independent of other effectors)
977 */
978         EffectorCache *eff;
979         EffectorData efd;
980         int p=0, tot = 1;
981
982         /* Cycle through collected objects, get total of (1/(gravity_strength * dist^gravity_power)) */
983         /* Check for min distance here? (yes would be cool to add that, ton) */
984         
985         if(effectors) for(eff = effectors->first; eff; eff=eff->next) {
986                 /* object effectors were fully checked to be OK to evaluate! */
987
988                 get_effector_tot(eff, &efd, point, &tot, &p);
989
990                 for(; p<tot; p++) {
991                         if(get_effector_data(eff, &efd, point, 0)) {
992                                 efd.falloff= effector_falloff(eff, &efd, point, weights);
993                                 
994                                 if(efd.falloff > 0.0f)
995                                         efd.falloff *= eff_calc_visibility(colliders, eff, &efd, point);
996
997                                 if(efd.falloff <= 0.0f)
998                                         ;       /* don't do anything */
999                                 else if(eff->pd->forcefield == PFIELD_TEXTURE)
1000                                         do_texture_effector(eff, &efd, point, force);
1001                                 else {
1002                                         float temp1[3]={0,0,0}, temp2[3];
1003                                         VECCOPY(temp1, force);
1004
1005                                         do_physical_effector(eff, &efd, point, force);
1006                                         
1007                                         // for softbody backward compatibility
1008                                         if(point->flag & PE_WIND_AS_SPEED && impulse){
1009                                                 VECSUB(temp2, force, temp1);
1010                                                 VECSUB(impulse, impulse, temp2);
1011                                         }
1012                                 }
1013                         }
1014                         else if(eff->flag & PE_VELOCITY_TO_IMPULSE && impulse) {
1015                                 /* special case for harmonic effector */
1016                                 VECADD(impulse, impulse, efd.vel);
1017                         }
1018                 }
1019         }
1020 }