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