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