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