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