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