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