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