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