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