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