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