Removed remaining use of pointers to particle types as well as boids headers.
[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 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         if (eff->pd && eff->pd->shape==PFIELD_SHAPE_SURFACE && eff->surmd) {
493                 /* closest point in the object surface is an effector */
494                 float vec[3];
495
496                 /* using velocity corrected location allows for easier sliding over effector surface */
497                 copy_v3_v3(vec, point->vel);
498                 mul_v3_fl(vec, point->vel_to_frame);
499                 add_v3_v3(vec, point->loc);
500
501                 ret = closest_point_on_surface(eff->surmd, vec, efd->loc, efd->nor, real_velocity ? efd->vel : NULL);
502
503                 efd->size = 0.0f;
504         }
505         else if (eff->pd && eff->pd->shape==PFIELD_SHAPE_POINTS) {
506
507                 if (eff->ob->derivedFinal) {
508                         DerivedMesh *dm = eff->ob->derivedFinal;
509
510                         dm->getVertCo(dm, *efd->index, efd->loc);
511                         dm->getVertNo(dm, *efd->index, efd->nor);
512
513                         mul_m4_v3(eff->ob->obmat, efd->loc);
514                         mul_mat3_m4_v3(eff->ob->obmat, efd->nor);
515
516                         normalize_v3(efd->nor);
517
518                         efd->size = 0.0f;
519
520                         /**/
521                         ret = 1;
522                 }
523         }
524         else {
525                 /* use center of object for distance calculus */
526                 const Object *ob = eff->ob;
527
528                 /* use z-axis as normal*/
529                 normalize_v3_v3(efd->nor, ob->obmat[2]);
530
531                 if (eff->pd && eff->pd->shape == PFIELD_SHAPE_PLANE) {
532                         float temp[3], translate[3];
533                         sub_v3_v3v3(temp, point->loc, ob->obmat[3]);
534                         project_v3_v3v3(translate, temp, efd->nor);
535
536                         /* for vortex the shape chooses between old / new force */
537                         if (eff->pd->forcefield == PFIELD_VORTEX)
538                                 add_v3_v3v3(efd->loc, ob->obmat[3], translate);
539                         else /* normally efd->loc is closest point on effector xy-plane */
540                                 sub_v3_v3v3(efd->loc, point->loc, translate);
541                 }
542                 else {
543                         copy_v3_v3(efd->loc, ob->obmat[3]);
544                 }
545
546                 if (real_velocity)
547                         copy_v3_v3(efd->vel, eff->velocity);
548
549                 efd->size = 0.0f;
550
551                 ret = 1;
552         }
553
554         if (ret) {
555                 sub_v3_v3v3(efd->vec_to_point, point->loc, efd->loc);
556                 efd->distance = len_v3(efd->vec_to_point);
557
558                 /* rest length for harmonic effector, will have to see later if this could be extended to other effectors */
559                 if (eff->pd && eff->pd->forcefield == PFIELD_HARMONIC && eff->pd->f_size)
560                         mul_v3_fl(efd->vec_to_point, (efd->distance-eff->pd->f_size)/efd->distance);
561
562                 if (eff->flag & PE_USE_NORMAL_DATA) {
563                         copy_v3_v3(efd->vec_to_point2, efd->vec_to_point);
564                         copy_v3_v3(efd->nor2, efd->nor);
565                 }
566                 else {
567                         /* for some effectors we need the object center every time */
568                         sub_v3_v3v3(efd->vec_to_point2, point->loc, eff->ob->obmat[3]);
569                         normalize_v3_v3(efd->nor2, eff->ob->obmat[2]);
570                 }
571         }
572
573         return ret;
574 }
575 static void get_effector_tot(EffectorCache *eff, EffectorData *efd, EffectedPoint *point, int *tot, int *p)
576 {
577         *p = 0;
578         efd->index = p;
579
580         if (eff->pd->shape == PFIELD_SHAPE_POINTS) {
581                 *tot = eff->ob->derivedFinal ? eff->ob->derivedFinal->numVertData : 1;
582
583                 if (*tot && eff->pd->forcefield == PFIELD_HARMONIC && point->index >= 0) {
584                         *p = point->index % *tot;
585                         *tot = *p+1;
586                 }
587         }
588         else {
589                 *tot = 1;
590         }
591 }
592 static void do_texture_effector(EffectorCache *eff, EffectorData *efd, EffectedPoint *point, float *total_force)
593 {
594         TexResult result[4];
595         float tex_co[3], strength, force[3];
596         float nabla = eff->pd->tex_nabla;
597         int hasrgb;
598         short mode = eff->pd->tex_mode;
599         bool scene_color_manage;
600
601         if (!eff->pd->tex)
602                 return;
603
604         result[0].nor = result[1].nor = result[2].nor = result[3].nor = NULL;
605
606         strength= eff->pd->f_strength * efd->falloff;
607
608         copy_v3_v3(tex_co, point->loc);
609
610         if (eff->pd->flag & PFIELD_TEX_2D) {
611                 float fac=-dot_v3v3(tex_co, efd->nor);
612                 madd_v3_v3fl(tex_co, efd->nor, fac);
613         }
614
615         if (eff->pd->flag & PFIELD_TEX_OBJECT) {
616                 mul_m4_v3(eff->ob->imat, tex_co);
617         }
618
619         scene_color_manage = BKE_scene_check_color_management_enabled(eff->scene);
620
621         hasrgb = multitex_ext(eff->pd->tex, tex_co, NULL, NULL, 0, result, 0, NULL, scene_color_manage, false);
622
623         if (hasrgb && mode==PFIELD_TEX_RGB) {
624                 force[0] = (0.5f - result->tr) * strength;
625                 force[1] = (0.5f - result->tg) * strength;
626                 force[2] = (0.5f - result->tb) * strength;
627         }
628         else {
629                 strength/=nabla;
630
631                 tex_co[0] += nabla;
632                 multitex_ext(eff->pd->tex, tex_co, NULL, NULL, 0, result+1, 0, NULL, scene_color_manage, false);
633
634                 tex_co[0] -= nabla;
635                 tex_co[1] += nabla;
636                 multitex_ext(eff->pd->tex, tex_co, NULL, NULL, 0, result+2, 0, NULL, scene_color_manage, false);
637
638                 tex_co[1] -= nabla;
639                 tex_co[2] += nabla;
640                 multitex_ext(eff->pd->tex, tex_co, NULL, NULL, 0, result+3, 0, NULL, scene_color_manage, false);
641
642                 if (mode == PFIELD_TEX_GRAD || !hasrgb) { /* if we don't have rgb fall back to grad */
643                         /* generate intensity if texture only has rgb value */
644                         if (hasrgb & TEX_RGB) {
645                                 int i;
646                                 for (i=0; i<4; i++)
647                                         result[i].tin = (1.0f / 3.0f) * (result[i].tr + result[i].tg + result[i].tb);
648                         }
649                         force[0] = (result[0].tin - result[1].tin) * strength;
650                         force[1] = (result[0].tin - result[2].tin) * strength;
651                         force[2] = (result[0].tin - result[3].tin) * strength;
652                 }
653                 else { /*PFIELD_TEX_CURL*/
654                         float dbdy, dgdz, drdz, dbdx, dgdx, drdy;
655
656                         dbdy = result[2].tb - result[0].tb;
657                         dgdz = result[3].tg - result[0].tg;
658                         drdz = result[3].tr - result[0].tr;
659                         dbdx = result[1].tb - result[0].tb;
660                         dgdx = result[1].tg - result[0].tg;
661                         drdy = result[2].tr - result[0].tr;
662
663                         force[0] = (dbdy - dgdz) * strength;
664                         force[1] = (drdz - dbdx) * strength;
665                         force[2] = (dgdx - drdy) * strength;
666                 }
667         }
668
669         if (eff->pd->flag & PFIELD_TEX_2D) {
670                 float fac = -dot_v3v3(force, efd->nor);
671                 madd_v3_v3fl(force, efd->nor, fac);
672         }
673
674         add_v3_v3(total_force, force);
675 }
676 static void do_physical_effector(EffectorCache *eff, EffectorData *efd, EffectedPoint *point, float *total_force)
677 {
678         PartDeflect *pd = eff->pd;
679         RNG *rng = pd->rng;
680         float force[3] = {0, 0, 0};
681         float temp[3];
682         float fac;
683         float strength = pd->f_strength;
684         float damp = pd->f_damp;
685         float noise_factor = pd->f_noise;
686
687         if (noise_factor > 0.0f) {
688                 strength += wind_func(rng, noise_factor);
689
690                 if (ELEM(pd->forcefield, PFIELD_HARMONIC, PFIELD_DRAG))
691                         damp += wind_func(rng, noise_factor);
692         }
693
694         copy_v3_v3(force, efd->vec_to_point);
695
696         switch (pd->forcefield) {
697                 case PFIELD_WIND:
698                         copy_v3_v3(force, efd->nor);
699                         mul_v3_fl(force, strength * efd->falloff);
700                         break;
701                 case PFIELD_FORCE:
702                         normalize_v3(force);
703                         mul_v3_fl(force, strength * efd->falloff);
704                         break;
705                 case PFIELD_VORTEX:
706                         /* old vortex force */
707                         if (pd->shape == PFIELD_SHAPE_POINT) {
708                                 cross_v3_v3v3(force, efd->nor, efd->vec_to_point);
709                                 normalize_v3(force);
710                                 mul_v3_fl(force, strength * efd->distance * efd->falloff);
711                         }
712                         else {
713                                 /* new vortex force */
714                                 cross_v3_v3v3(temp, efd->nor2, efd->vec_to_point2);
715                                 mul_v3_fl(temp, strength * efd->falloff);
716                                 
717                                 cross_v3_v3v3(force, efd->nor2, temp);
718                                 mul_v3_fl(force, strength * efd->falloff);
719                                 
720                                 madd_v3_v3fl(temp, point->vel, -point->vel_to_sec);
721                                 add_v3_v3(force, temp);
722                         }
723                         break;
724                 case PFIELD_MAGNET:
725                         if (eff->pd->shape == PFIELD_SHAPE_POINT)
726                                 /* magnetic field of a moving charge */
727                                 cross_v3_v3v3(temp, efd->nor, efd->vec_to_point);
728                         else
729                                 copy_v3_v3(temp, efd->nor);
730
731                         normalize_v3(temp);
732                         mul_v3_fl(temp, strength * efd->falloff);
733                         cross_v3_v3v3(force, point->vel, temp);
734                         mul_v3_fl(force, point->vel_to_sec);
735                         break;
736                 case PFIELD_HARMONIC:
737                         mul_v3_fl(force, -strength * efd->falloff);
738                         copy_v3_v3(temp, point->vel);
739                         mul_v3_fl(temp, -damp * 2.0f * sqrtf(fabsf(strength)) * point->vel_to_sec);
740                         add_v3_v3(force, temp);
741                         break;
742                 case PFIELD_CHARGE:
743                         mul_v3_fl(force, point->charge * strength * efd->falloff);
744                         break;
745                 case PFIELD_LENNARDJ:
746                         fac = pow((efd->size + point->size) / efd->distance, 6.0);
747                         
748                         fac = - fac * (1.0f - fac) / efd->distance;
749
750                         /* limit the repulsive term drastically to avoid huge forces */
751                         fac = ((fac>2.0f) ? 2.0f : fac);
752
753                         mul_v3_fl(force, strength * fac);
754                         break;
755                 case PFIELD_BOID:
756                         /* Boid field is handled completely in boids code. */
757                         return;
758                 case PFIELD_TURBULENCE:
759                         if (pd->flag & PFIELD_GLOBAL_CO) {
760                                 copy_v3_v3(temp, point->loc);
761                         }
762                         else {
763                                 add_v3_v3v3(temp, efd->vec_to_point2, efd->nor2);
764                         }
765                         force[0] = -1.0f + 2.0f * BLI_gTurbulence(pd->f_size, temp[0], temp[1], temp[2], 2, 0, 2);
766                         force[1] = -1.0f + 2.0f * BLI_gTurbulence(pd->f_size, temp[1], temp[2], temp[0], 2, 0, 2);
767                         force[2] = -1.0f + 2.0f * BLI_gTurbulence(pd->f_size, temp[2], temp[0], temp[1], 2, 0, 2);
768                         mul_v3_fl(force, strength * efd->falloff);
769                         break;
770                 case PFIELD_DRAG:
771                         copy_v3_v3(force, point->vel);
772                         fac = normalize_v3(force) * point->vel_to_sec;
773
774                         strength = MIN2(strength, 2.0f);
775                         damp = MIN2(damp, 2.0f);
776
777                         mul_v3_fl(force, -efd->falloff * fac * (strength * fac + damp));
778                         break;
779                 case PFIELD_SMOKEFLOW:
780                         zero_v3(force);
781                         if (pd->f_source) {
782                                 float density;
783                                 if ((density = smoke_get_velocity_at(pd->f_source, point->loc, force)) >= 0.0f) {
784                                         float influence = strength * efd->falloff;
785                                         if (pd->flag & PFIELD_SMOKE_DENSITY)
786                                                 influence *= density;
787                                         mul_v3_fl(force, influence);
788                                         /* apply flow */
789                                         madd_v3_v3fl(total_force, point->vel, -pd->f_flow * influence);
790                                 }
791                         }
792                         break;
793
794         }
795
796         if (pd->flag & PFIELD_DO_LOCATION) {
797                 madd_v3_v3fl(total_force, force, 1.0f/point->vel_to_sec);
798
799                 if (ELEM(pd->forcefield, PFIELD_HARMONIC, PFIELD_DRAG, PFIELD_SMOKEFLOW)==0 && pd->f_flow != 0.0f) {
800                         madd_v3_v3fl(total_force, point->vel, -pd->f_flow * efd->falloff);
801                 }
802         }
803
804         if (point->ave)
805                 zero_v3(point->ave);
806         if (pd->flag & PFIELD_DO_ROTATION && point->ave && point->rot) {
807                 float xvec[3] = {1.0f, 0.0f, 0.0f};
808                 float dave[3];
809                 mul_qt_v3(point->rot, xvec);
810                 cross_v3_v3v3(dave, xvec, force);
811                 if (pd->f_flow != 0.0f) {
812                         madd_v3_v3fl(dave, point->ave, -pd->f_flow * efd->falloff);
813                 }
814                 add_v3_v3(point->ave, dave);
815         }
816 }
817
818 /*  -------- pdDoEffectors() --------
819  * generic force/speed system, now used for particles and softbodies
820  * scene       = scene where it runs in, for time and stuff
821  * lb                   = listbase with objects that take part in effecting
822  * opco         = global coord, as input
823  * force                = force accumulator
824  * speed                = actual current speed which can be altered
825  * cur_time     = "external" time in frames, is constant for static particles
826  * loc_time     = "local" time in frames, range <0-1> for the lifetime of particle
827  * par_layer    = layer the caller is in
828  * flags                = only used for softbody wind now
829  * guide                = old speed of particle
830  */
831 void pdDoEffectors(ListBase *effectors, ListBase *colliders, EffectorWeights *weights, EffectedPoint *point, float *force, float *impulse)
832 {
833 /*
834  * Modifies the force on a particle according to its
835  * relation with the effector object
836  * Different kind of effectors include:
837  *     Forcefields: Gravity-like attractor
838  *     (force power is related to the inverse of distance to the power of a falloff value)
839  *     Vortex fields: swirling effectors
840  *     (particles rotate around Z-axis of the object. otherwise, same relation as)
841  *     (Forcefields, but this is not done through a force/acceleration)
842  *     Guide: particles on a path
843  *     (particles are guided along a curve bezier or old nurbs)
844  *     (is independent of other effectors)
845  */
846         EffectorCache *eff;
847         EffectorData efd;
848         int p=0, tot = 1;
849
850         /* Cycle through collected objects, get total of (1/(gravity_strength * dist^gravity_power)) */
851         /* Check for min distance here? (yes would be cool to add that, ton) */
852         
853         if (effectors) for (eff = effectors->first; eff; eff=eff->next) {
854                 /* object effectors were fully checked to be OK to evaluate! */
855
856                 get_effector_tot(eff, &efd, point, &tot, &p);
857
858                 for (; p<tot; p++) {
859                         if (get_effector_data(eff, &efd, point, 0)) {
860                                 efd.falloff= effector_falloff(eff, &efd, point, weights);
861                                 
862                                 if (efd.falloff > 0.0f)
863                                         efd.falloff *= eff_calc_visibility(colliders, eff, &efd, point);
864
865                                 if (efd.falloff <= 0.0f) {
866                                         /* don't do anything */
867                                 }
868                                 else if (eff->pd->forcefield == PFIELD_TEXTURE) {
869                                         do_texture_effector(eff, &efd, point, force);
870                                 }
871                                 else {
872                                         float temp1[3] = {0, 0, 0}, temp2[3];
873                                         copy_v3_v3(temp1, force);
874
875                                         do_physical_effector(eff, &efd, point, force);
876                                         
877                                         /* for softbody backward compatibility */
878                                         if (point->flag & PE_WIND_AS_SPEED && impulse) {
879                                                 sub_v3_v3v3(temp2, force, temp1);
880                                                 sub_v3_v3v3(impulse, impulse, temp2);
881                                         }
882                                 }
883                         }
884                         else if (eff->flag & PE_VELOCITY_TO_IMPULSE && impulse) {
885                                 /* special case for harmonic effector */
886                                 add_v3_v3v3(impulse, impulse, efd.vel);
887                         }
888                 }
889         }
890 }
891
892 /* ======== Simulation Debugging ======== */
893
894 SimDebugData *_sim_debug_data = NULL;
895
896 unsigned int BKE_sim_debug_data_hash(int i)
897 {
898         return BLI_ghashutil_uinthash((unsigned int)i);
899 }
900
901 unsigned int BKE_sim_debug_data_hash_combine(unsigned int kx, unsigned int ky)
902 {
903 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
904
905         unsigned int a, b, c;
906
907         a = b = c = 0xdeadbeef + (2 << 2) + 13;
908         a += kx;
909         b += ky;
910
911         c ^= b; c -= rot(b,14);
912         a ^= c; a -= rot(c,11);
913         b ^= a; b -= rot(a,25);
914         c ^= b; c -= rot(b,16);
915         a ^= c; a -= rot(c,4);
916         b ^= a; b -= rot(a,14);
917         c ^= b; c -= rot(b,24);
918
919         return c;
920
921 #undef rot
922 }
923
924 static unsigned int debug_element_hash(const void *key)
925 {
926         const SimDebugElement *elem = key;
927         return elem->hash;
928 }
929
930 static bool debug_element_compare(const void *a, const void *b)
931 {
932         const SimDebugElement *elem1 = a;
933         const SimDebugElement *elem2 = b;
934
935         if (elem1->hash == elem2->hash) {
936                 return 0;
937         }
938         return 1;
939 }
940
941 static void debug_element_free(void *val)
942 {
943         SimDebugElement *elem = val;
944         MEM_freeN(elem);
945 }
946
947 void BKE_sim_debug_data_set_enabled(bool enable)
948 {
949         if (enable) {
950                 if (!_sim_debug_data) {
951                         _sim_debug_data = MEM_callocN(sizeof(SimDebugData), "sim debug data");
952                         _sim_debug_data->gh = BLI_ghash_new(debug_element_hash, debug_element_compare, "sim debug element hash");
953                 }
954         }
955         else {
956                 BKE_sim_debug_data_free();
957         }
958 }
959
960 bool BKE_sim_debug_data_get_enabled(void)
961 {
962         return _sim_debug_data != NULL;
963 }
964
965 void BKE_sim_debug_data_free(void)
966 {
967         if (_sim_debug_data) {
968                 if (_sim_debug_data->gh)
969                         BLI_ghash_free(_sim_debug_data->gh, NULL, debug_element_free);
970                 MEM_freeN(_sim_debug_data);
971         }
972 }
973
974 static void debug_data_insert(SimDebugData *debug_data, SimDebugElement *elem)
975 {
976         SimDebugElement *old_elem = BLI_ghash_lookup(debug_data->gh, elem);
977         if (old_elem) {
978                 *old_elem = *elem;
979                 MEM_freeN(elem);
980         }
981         else
982                 BLI_ghash_insert(debug_data->gh, elem, elem);
983 }
984
985 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)
986 {
987         unsigned int category_hash = BLI_ghashutil_strhash_p(category);
988         SimDebugElement *elem;
989         
990         if (!_sim_debug_data) {
991                 if (G.debug & G_DEBUG_SIMDATA)
992                         BKE_sim_debug_data_set_enabled(true);
993                 else
994                         return;
995         }
996         
997         elem = MEM_callocN(sizeof(SimDebugElement), "sim debug data element");
998         elem->type = type;
999         elem->category_hash = category_hash;
1000         elem->hash = hash;
1001         elem->color[0] = r;
1002         elem->color[1] = g;
1003         elem->color[2] = b;
1004         copy_v3_v3(elem->v1, v1);
1005         copy_v3_v3(elem->v2, v2);
1006         
1007         debug_data_insert(_sim_debug_data, elem);
1008 }
1009
1010 void BKE_sim_debug_data_remove_element(unsigned int hash)
1011 {
1012         SimDebugElement dummy;
1013         if (!_sim_debug_data)
1014                 return;
1015         
1016         dummy.hash = hash;
1017         BLI_ghash_remove(_sim_debug_data->gh, &dummy, NULL, debug_element_free);
1018 }
1019
1020 void BKE_sim_debug_data_clear(void)
1021 {
1022         if (!_sim_debug_data)
1023                 return;
1024         
1025         if (_sim_debug_data->gh)
1026                 BLI_ghash_clear(_sim_debug_data->gh, NULL, debug_element_free);
1027 }
1028
1029 void BKE_sim_debug_data_clear_category(const char *category)
1030 {
1031         int category_hash = (int)BLI_ghashutil_strhash_p(category);
1032         
1033         if (!_sim_debug_data)
1034                 return;
1035         
1036         if (_sim_debug_data->gh) {
1037                 GHashIterator iter;
1038                 BLI_ghashIterator_init(&iter, _sim_debug_data->gh);
1039                 while (!BLI_ghashIterator_done(&iter)) {
1040                         const SimDebugElement *elem = BLI_ghashIterator_getValue(&iter);
1041                         BLI_ghashIterator_step(&iter); /* removing invalidates the current iterator, so step before removing */
1042                         
1043                         if (elem->category_hash == category_hash)
1044                                 BLI_ghash_remove(_sim_debug_data->gh, elem, NULL, debug_element_free);
1045                 }
1046         }
1047 }