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