cca5d68167e74084b2fe0aed94a02a938cb2a822
[blender.git] / source / blender / blenkernel / intern / effect.c
1 /*  effect.c
2  * 
3  * 
4  * $Id$
5  *
6  * ***** BEGIN GPL LICENSE BLOCK *****
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License
10  * as published by the Free Software Foundation; either version 2
11  * of the License, or (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software Foundation,
20  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
21  *
22  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
23  * All rights reserved.
24  *
25  * The Original Code is: all of this file.
26  *
27  * Contributor(s): none yet.
28  *
29  * ***** END GPL LICENSE BLOCK *****
30  */
31
32 #include <math.h>
33 #include <stdlib.h>
34
35 #include "MEM_guardedalloc.h"
36
37 #include "DNA_curve_types.h"
38 #include "DNA_effect_types.h"
39 #include "DNA_group_types.h"
40 #include "DNA_ipo_types.h"
41 #include "DNA_key_types.h"
42 #include "DNA_lattice_types.h"
43 #include "DNA_listBase.h"
44 #include "DNA_mesh_types.h"
45 #include "DNA_meshdata_types.h"
46 #include "DNA_material_types.h"
47 #include "DNA_object_types.h"
48 #include "DNA_object_force.h"
49 #include "DNA_texture_types.h"
50 #include "DNA_scene_types.h"
51
52 #include "BLI_arithb.h"
53 #include "BLI_blenlib.h"
54 #include "BLI_jitter.h"
55 #include "BLI_rand.h"
56
57 #include "BKE_action.h"
58 #include "BKE_anim.h"           /* needed for where_on_path */
59 #include "BKE_armature.h"
60 #include "BKE_bad_level_calls.h"
61 #include "BKE_blender.h"
62 #include "BKE_collision.h"
63 #include "BKE_constraint.h"
64 #include "BKE_deform.h"
65 #include "BKE_depsgraph.h"
66 #include "BKE_displist.h"
67 #include "BKE_DerivedMesh.h"
68 #include "BKE_effect.h"
69 #include "BKE_global.h"
70 #include "BKE_group.h"
71 #include "BKE_ipo.h"
72 #include "BKE_key.h"
73 #include "BKE_lattice.h"
74 #include "BKE_mesh.h"
75 #include "BKE_material.h"
76 #include "BKE_main.h"
77 #include "BKE_modifier.h"
78 #include "BKE_object.h"
79 #include "BKE_scene.h"
80 #include "BKE_screen.h"
81 #include "BKE_utildefines.h"
82
83 #include "PIL_time.h"
84 #include "RE_render_ext.h"
85
86 /* fluid sim particle import */
87 #ifndef DISABLE_ELBEEM
88 #include "DNA_object_fluidsim.h"
89 #include "LBM_fluidsim.h"
90 #include "elbeem.h"
91 #include <zlib.h>
92 #include <string.h>
93 #endif // DISABLE_ELBEEM
94
95 /* temporal struct, used for reading return of mesh_get_mapped_verts_nors() */
96 typedef struct VeNoCo {
97         float co[3], no[3];
98 } VeNoCo;
99
100 /* ***************** PARTICLES ***************** */
101
102 /* deprecated, only keep this for readfile.c */
103 PartEff *give_parteff(Object *ob)
104 {
105         PartEff *paf;
106         
107         paf= ob->effect.first;
108         while(paf) {
109                 if(paf->type==EFF_PARTICLE) return paf;
110                 paf= paf->next;
111         }
112         return 0;
113 }
114
115 void free_effect(Effect *eff)
116 {
117         PartEff *paf;
118         
119         if(eff->type==EFF_PARTICLE) {
120                 paf= (PartEff *)eff;
121                 if(paf->keys) MEM_freeN(paf->keys);
122         }
123         MEM_freeN(eff); 
124 }
125
126
127 void free_effects(ListBase *lb)
128 {
129         Effect *eff;
130         
131         eff= lb->first;
132         while(eff) {
133                 BLI_remlink(lb, eff);
134                 free_effect(eff);
135                 eff= lb->first;
136         }
137 }
138
139 /* -------------------------- Effectors ------------------ */
140
141 static void add_to_effectorcache(ListBase *lb, Object *ob, Object *obsrc)
142 {
143         pEffectorCache *ec;
144         PartDeflect *pd= ob->pd;
145                         
146         if(pd->forcefield == PFIELD_GUIDE) {
147                 if(ob->type==OB_CURVE && obsrc->type==OB_MESH) {        /* guides only do mesh particles */
148                         Curve *cu= ob->data;
149                         if(cu->flag & CU_PATH) {
150                                 if(cu->path==NULL || cu->path->data==NULL)
151                                         makeDispListCurveTypes(ob, 0);
152                                 if(cu->path && cu->path->data) {
153                                         ec= MEM_callocN(sizeof(pEffectorCache), "effector cache");
154                                         ec->ob= ob;
155                                         BLI_addtail(lb, ec);
156                                 }
157                         }
158                 }
159         }
160         else if(pd->forcefield) {
161                 
162                 if(pd->forcefield == PFIELD_WIND)
163                 {
164                         pd->rng = rng_new(1);
165                         rng_srandom(pd->rng, (unsigned int)(ceil(PIL_check_seconds_timer()))); // use better seed
166                 }
167         
168                 ec= MEM_callocN(sizeof(pEffectorCache), "effector cache");
169                 ec->ob= ob;
170                 BLI_addtail(lb, ec);
171         }
172 }
173
174 /* returns ListBase handle with objects taking part in the effecting */
175 ListBase *pdInitEffectors(Object *obsrc, Group *group)
176 {
177         static ListBase listb={NULL, NULL};
178         pEffectorCache *ec;
179         Base *base;
180         unsigned int layer= obsrc->lay;
181         
182         if(group) {
183                 GroupObject *go;
184                 
185                 for(go= group->gobject.first; go; go= go->next) {
186                         if( (go->ob->lay & layer) && go->ob->pd && go->ob!=obsrc) {
187                                 add_to_effectorcache(&listb, go->ob, obsrc);
188                         }
189                 }
190         }
191         else {
192                 for(base = G.scene->base.first; base; base= base->next) {
193                         if( (base->lay & layer) && base->object->pd && base->object!=obsrc) {
194                                 add_to_effectorcache(&listb, base->object, obsrc);
195                         }
196                 }
197         }
198         
199         /* make a full copy */
200         for(ec= listb.first; ec; ec= ec->next) {
201                 ec->obcopy= *(ec->ob);
202         }
203
204         if(listb.first)
205                 return &listb;
206         
207         return NULL;
208 }
209
210 void pdEndEffectors(ListBase *lb)
211 {
212         if(lb) {
213                 pEffectorCache *ec;
214                 /* restore full copy */
215                 for(ec= lb->first; ec; ec= ec->next)
216                 {
217                         if(ec->ob->pd && (ec->ob->pd->forcefield == PFIELD_WIND))
218                                 rng_free(ec->ob->pd->rng);
219                         
220                         *(ec->ob)= ec->obcopy;
221                 }
222
223                 BLI_freelistN(lb);
224         }
225 }
226
227
228 /************************************************/
229 /*                      Effectors               */
230 /************************************************/
231
232 // triangle - ray callback function
233 static void eff_tri_ray_hit(void *userdata, int index, const BVHTreeRay *ray, BVHTreeRayHit *hit)
234 {       
235         // whenever we hit a bounding box, we don't check further
236         hit->dist = -1;
237         hit->index = 1;
238 }
239
240 // get visibility of a wind ray
241 static float eff_calc_visibility(Object *ob, float *co, float *dir)
242 {
243         CollisionModifierData **collobjs = NULL;
244         int numcollobj = 0, i;
245         float norm[3], len = 0.0;
246         float visibility = 1.0;
247         
248         collobjs = get_collisionobjects(ob, &numcollobj);
249         
250         if(!collobjs)
251                 return 0;
252         
253         VECCOPY(norm, dir);
254         VecNegf(norm);
255         len = Normalize(norm);
256         
257         // check all collision objects
258         for(i = 0; i < numcollobj; i++)
259         {
260                 CollisionModifierData *collmd = collobjs[i];
261                 
262                 if(collmd->bvhtree)
263                 {
264                         BVHTreeRayHit hit;
265                         
266                         hit.index = -1;
267                         hit.dist = len + FLT_EPSILON;
268                         
269                         // check if the way is blocked
270                         if(BLI_bvhtree_ray_cast(collmd->bvhtree, co, norm, 0.0f, &hit, eff_tri_ray_hit, NULL)>=0)
271                         {
272                                 // visibility is only between 0 and 1, calculated from 1-absorption
273                                 visibility *= MAX2(0.0, MIN2(1.0, (1.0-((float)collmd->absorption)*0.01)));
274                                 
275                                 if(visibility <= 0.0f)
276                                         break;
277                         }
278                 }
279         }
280         
281         MEM_freeN(collobjs);
282         
283         return visibility;
284 }
285
286 // noise function for wind e.g.
287 static float wind_func(struct RNG *rng, float strength)
288 {
289         int random = (rng_getInt(rng)+1) % 65535; // max 2357
290         float force = rng_getFloat(rng) + 1.0f;
291         float ret;
292         float sign = 0;
293         
294         sign = (random > 32000.0) ? 1.0: -1.0; // dividing by 2 is not giving equal sign distribution
295         
296         ret = sign*((float)random / force)*strength/65535.0f;
297         
298         return ret;
299 }
300
301 /* maxdist: zero effect from this distance outwards (if usemax) */
302 /* mindist: full effect up to this distance (if usemin) */
303 /* power: falloff with formula 1/r^power */
304 static float falloff_func(float fac, int usemin, float mindist, int usemax, float maxdist, float power)
305 {
306         /* first quick checks */
307         if(usemax && fac > maxdist)
308                 return 0.0f;
309
310         if(usemin && fac < mindist)
311                 return 1.0f;
312
313         if(!usemin)
314                 mindist = 0.0;
315
316         return pow((double)1.0+fac-mindist, (double)-power);
317 }
318
319 static float falloff_func_dist(PartDeflect *pd, float fac)
320 {
321         return falloff_func(fac, pd->flag&PFIELD_USEMIN, pd->mindist, pd->flag&PFIELD_USEMAX, pd->maxdist, pd->f_power);
322 }
323
324 static float falloff_func_rad(PartDeflect *pd, float fac)
325 {
326         return falloff_func(fac, pd->flag&PFIELD_USEMINR, pd->minrad, pd->flag&PFIELD_USEMAXR, pd->maxrad, pd->f_power_r);
327 }
328
329 float effector_falloff(PartDeflect *pd, float *eff_velocity, float *vec_to_part)
330 {
331         float eff_dir[3], temp[3];
332         float falloff=1.0, fac, r_fac;
333
334         if(pd->forcefield==PFIELD_LENNARDJ)
335                 return falloff; /* Lennard-Jones field has it's own falloff built in */
336
337         VecCopyf(eff_dir,eff_velocity);
338         Normalize(eff_dir);
339
340         if(pd->flag & PFIELD_POSZ && Inpf(eff_dir,vec_to_part)<0.0f)
341                 falloff=0.0f;
342         else switch(pd->falloff){
343                 case PFIELD_FALL_SPHERE:
344                         fac=VecLength(vec_to_part);
345                         falloff= falloff_func_dist(pd, fac);
346                         break;
347
348                 case PFIELD_FALL_TUBE:
349                         fac=Inpf(vec_to_part,eff_dir);
350                         falloff= falloff_func_dist(pd, ABS(fac));
351                         if(falloff == 0.0f)
352                                 break;
353
354                         VECADDFAC(temp,vec_to_part,eff_dir,-fac);
355                         r_fac=VecLength(temp);
356                         falloff*= falloff_func_rad(pd, r_fac);
357                         break;
358                 case PFIELD_FALL_CONE:
359                         fac=Inpf(vec_to_part,eff_dir);
360                         falloff= falloff_func_dist(pd, ABS(fac));
361                         if(falloff == 0.0f)
362                                 break;
363
364                         r_fac=saacos(fac/VecLength(vec_to_part))*180.0f/(float)M_PI;
365                         falloff*= falloff_func_rad(pd, r_fac);
366
367                         break;
368         }
369
370         return falloff;
371 }
372
373 void do_physical_effector(Object *ob, float *opco, short type, float force_val, float distance, float falloff, float size, float damp, float *eff_velocity, float *vec_to_part, float *velocity, float *field, int planar, struct RNG *rng, float noise_factor, float charge, float pa_size)
374 {
375         float mag_vec[3]={0,0,0};
376         float temp[3], temp2[3];
377         float eff_vel[3];
378         float noise = 0, visibility;
379         
380         // calculate visibility
381         visibility = eff_calc_visibility(ob, opco, vec_to_part);
382         if(visibility <= 0.0)
383                 return;
384         falloff *= visibility;
385
386         VecCopyf(eff_vel,eff_velocity);
387         Normalize(eff_vel);
388
389         switch(type){
390                 case PFIELD_WIND:
391                         VECCOPY(mag_vec,eff_vel);
392                         
393                         // add wind noise here, only if we have wind
394                         if((noise_factor > 0.0f) && (force_val > FLT_EPSILON))
395                                 noise = wind_func(rng, noise_factor);
396                         
397                         VecMulf(mag_vec,(force_val+noise)*falloff);
398                         VecAddf(field,field,mag_vec);
399                         break;
400
401                 case PFIELD_FORCE:
402                         if(planar)
403                                 Projf(mag_vec,vec_to_part,eff_vel);
404                         else
405                                 VecCopyf(mag_vec,vec_to_part);
406
407                         Normalize(mag_vec);
408
409                         VecMulf(mag_vec,force_val*falloff);
410                         VecAddf(field,field,mag_vec);
411                         break;
412
413                 case PFIELD_VORTEX:
414                         Crossf(mag_vec,eff_vel,vec_to_part);
415
416                         Normalize(mag_vec);
417
418                         VecMulf(mag_vec,force_val*distance*falloff);
419                         VecAddf(field,field,mag_vec);
420
421                         break;
422                 case PFIELD_MAGNET:
423                         if(planar)
424                                 VecCopyf(temp,eff_vel);
425                         else
426                                 /* magnetic field of a moving charge */
427                                 Crossf(temp,eff_vel,vec_to_part);
428
429                         Normalize(temp);
430
431                         Crossf(temp2,velocity,temp);
432                         VecAddf(mag_vec,mag_vec,temp2);
433
434                         VecMulf(mag_vec,force_val*falloff);
435                         VecAddf(field,field,mag_vec);
436                         break;
437                 case PFIELD_HARMONIC:
438                         if(planar)
439                                 Projf(mag_vec,vec_to_part,eff_vel);
440                         else
441                                 VecCopyf(mag_vec,vec_to_part);
442
443                         VecMulf(mag_vec,force_val*falloff);
444                         VecSubf(field,field,mag_vec);
445
446                         VecCopyf(mag_vec,velocity);
447                         VecMulf(mag_vec,damp*2.0f*(float)sqrt(force_val));
448                         VecSubf(field,field,mag_vec);
449                         break;
450                 case PFIELD_CHARGE:
451                         if(planar)
452                                 Projf(mag_vec,vec_to_part,eff_vel);
453                         else
454                                 VecCopyf(mag_vec,vec_to_part);
455
456                         Normalize(mag_vec);
457
458                         VecMulf(mag_vec,charge*force_val*falloff);
459                         VecAddf(field,field,mag_vec);
460                         break;
461                 case PFIELD_LENNARDJ:
462                 {
463                         float fac;
464
465                         if(planar) {
466                                 Projf(mag_vec,vec_to_part,eff_vel);
467                                 distance = VecLength(mag_vec);
468                         }
469                         else
470                                 VecCopyf(mag_vec,vec_to_part);
471
472                         /* at this distance the field is 60 times weaker than maximum */
473                         if(distance > 2.22 * (size+pa_size))
474                                 break;
475
476                         fac = pow((size+pa_size)/distance,6.0);
477                         
478                         fac = - fac * (1.0 - fac) / distance;
479
480                         /* limit the repulsive term drastically to avoid huge forces */
481                         fac = ((fac>2.0) ? 2.0 : fac);
482
483                         /* 0.003715 is the fac value at 2.22 times (size+pa_size),
484                            substracted to avoid discontinuity at the border
485                         */
486                         VecMulf(mag_vec, force_val * (fac-0.0037315));
487                         VecAddf(field,field,mag_vec);
488                         break;
489                 }
490         }
491 }
492
493 /*  -------- pdDoEffectors() --------
494     generic force/speed system, now used for particles and softbodies
495         lb                      = listbase with objects that take part in effecting
496         opco            = global coord, as input
497     force               = force accumulator
498     speed               = actual current speed which can be altered
499         cur_time        = "external" time in frames, is constant for static particles
500         loc_time        = "local" time in frames, range <0-1> for the lifetime of particle
501     par_layer   = layer the caller is in
502         flags           = only used for softbody wind now
503         guide           = old speed of particle
504
505 */
506 void pdDoEffectors(ListBase *lb, float *opco, float *force, float *speed, float cur_time, float loc_time, unsigned int flags)
507 {
508 /*
509         Modifies the force on a particle according to its
510         relation with the effector object
511         Different kind of effectors include:
512                 Forcefields: Gravity-like attractor
513                 (force power is related to the inverse of distance to the power of a falloff value)
514                 Vortex fields: swirling effectors
515                 (particles rotate around Z-axis of the object. otherwise, same relation as)
516                 (Forcefields, but this is not done through a force/acceleration)
517                 Guide: particles on a path
518                 (particles are guided along a curve bezier or old nurbs)
519                 (is independent of other effectors)
520 */
521         Object *ob;
522         pEffectorCache *ec;
523         PartDeflect *pd;
524         
525         float distance, vec_to_part[3];
526         float falloff;
527
528         /* Cycle through collected objects, get total of (1/(gravity_strength * dist^gravity_power)) */
529         /* Check for min distance here? (yes would be cool to add that, ton) */
530         
531         for(ec = lb->first; ec; ec= ec->next) {
532                 /* object effectors were fully checked to be OK to evaluate! */
533                 ob= ec->ob;
534                 pd= ob->pd;
535                         
536                 /* Get IPO force strength and fall off values here */
537                 where_is_object_time(ob,cur_time);
538                         
539                 /* use center of object for distance calculus */
540                 VecSubf(vec_to_part, opco, ob->obmat[3]);
541                 distance = VecLength(vec_to_part);
542
543                 falloff=effector_falloff(pd,ob->obmat[2],vec_to_part);          
544                 
545                 if(falloff<=0.0f)
546                         ;       /* don't do anything */
547                 else {
548                         float field[3]={0,0,0}, tmp[3];
549                         VECCOPY(field, force);
550                         do_physical_effector(ob, opco, pd->forcefield,pd->f_strength,distance,
551                                                                 falloff,pd->f_dist,pd->f_damp,ob->obmat[2],vec_to_part,
552                                                                 speed,force,pd->flag&PFIELD_PLANAR, pd->rng, pd->f_noise, 0.0f, 0.0f);
553                         
554                         // for softbody backward compatibility
555                         if(flags & PE_WIND_AS_SPEED){
556                                 VECSUB(tmp, force, field);
557                                 VECSUB(speed, speed, tmp);
558                         }
559                 }
560         }
561 }