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