Merging r40615 through r40652 from trunk into soc-2011-tomato
[blender-staging.git] / source / blender / blenkernel / intern / boids.c
1 /* boids.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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21  *
22  * The Original Code is Copyright (C) 2009 by Janne Karhu.
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 /** \file blender/blenkernel/intern/boids.c
33  *  \ingroup bke
34  */
35
36
37 #include <string.h>
38 #include <math.h>
39
40 #include "MEM_guardedalloc.h"
41
42 #include "DNA_object_force.h"
43 #include "DNA_scene_types.h"
44
45 #include "BLI_rand.h"
46 #include "BLI_math.h"
47 #include "BLI_blenlib.h"
48 #include "BLI_kdtree.h"
49 #include "BLI_utildefines.h"
50
51 #include "BKE_collision.h"
52 #include "BKE_effect.h"
53 #include "BKE_boids.h"
54 #include "BKE_particle.h"
55
56 #include "BKE_modifier.h"
57
58 #include "RNA_enum_types.h"
59
60 typedef struct BoidValues {
61         float max_speed, max_acc;
62         float max_ave, min_speed;
63         float personal_space, jump_speed;
64 } BoidValues;
65
66 static int apply_boid_rule(BoidBrainData *bbd, BoidRule *rule, BoidValues *val, ParticleData *pa, float fuzziness);
67
68 static int rule_none(BoidRule *UNUSED(rule), BoidBrainData *UNUSED(data), BoidValues *UNUSED(val), ParticleData *UNUSED(pa))
69 {
70         return 0;
71 }
72
73 static int rule_goal_avoid(BoidRule *rule, BoidBrainData *bbd, BoidValues *val, ParticleData *pa)
74 {
75         BoidRuleGoalAvoid *gabr = (BoidRuleGoalAvoid*) rule;
76         BoidSettings *boids = bbd->part->boids;
77         BoidParticle *bpa = pa->boid;
78         EffectedPoint epoint;
79         ListBase *effectors = bbd->sim->psys->effectors;
80         EffectorCache *cur, *eff = NULL;
81         EffectorCache temp_eff;
82         EffectorData efd, cur_efd;
83         float mul = (rule->type == eBoidRuleType_Avoid ? 1.0 : -1.0);
84         float priority = 0.0f, len = 0.0f;
85         int ret = 0;
86
87         pd_point_from_particle(bbd->sim, pa, &pa->state, &epoint);
88
89         /* first find out goal/predator with highest priority */
90         if(effectors) for(cur = effectors->first; cur; cur=cur->next) {
91                 Object *eob = cur->ob;
92                 PartDeflect *pd = cur->pd;
93
94                 if(gabr->ob && (rule->type != eBoidRuleType_Goal || gabr->ob != bpa->ground)) {
95                         if(gabr->ob == eob) {
96                                 /* TODO: effectors with multiple points */
97                                 if(get_effector_data(cur, &efd, &epoint, 0)) {
98                                         if(cur->pd && cur->pd->forcefield == PFIELD_BOID)
99                                                 priority = mul * pd->f_strength * effector_falloff(cur, &efd, &epoint, bbd->part->effector_weights);
100                                         else
101                                                 priority = 1.0;
102
103                                         eff = cur;
104                                 }
105                                 break;
106                         }
107                 }
108                 else if(rule->type == eBoidRuleType_Goal && eob == bpa->ground)
109                         ; /* skip current object */
110                 else if(pd->forcefield == PFIELD_BOID && mul * pd->f_strength > 0.0f && get_effector_data(cur, &cur_efd, &epoint, 0)) {
111                         float temp = mul * pd->f_strength * effector_falloff(cur, &cur_efd, &epoint, bbd->part->effector_weights);
112
113                         if(temp == 0.0f)
114                                 ; /* do nothing */
115                         else if(temp > priority) {
116                                 priority = temp;
117                                 eff = cur;
118                                 efd = cur_efd;
119                                 len = efd.distance;
120                         }
121                         /* choose closest object with same priority */
122                         else if(temp == priority && efd.distance < len) {
123                                 eff = cur;
124                                 efd = cur_efd;
125                                 len = efd.distance;
126                         }
127                 }
128         }
129
130         /* if the object doesn't have effector data we have to fake it */
131         if(eff == NULL && gabr->ob) {
132                 memset(&temp_eff, 0, sizeof(EffectorCache));
133                 temp_eff.ob = gabr->ob;
134                 temp_eff.scene = bbd->sim->scene;
135                 eff = &temp_eff;
136                 get_effector_data(eff, &efd, &epoint, 0);
137                 priority = 1.0f;
138         }
139
140         /* then use that effector */
141         if(priority > (rule->type==eBoidRuleType_Avoid ? gabr->fear_factor : 0.0f)) { /* with avoid, factor is "fear factor" */
142                 Object *eob = eff->ob;
143                 PartDeflect *pd = eff->pd;
144                 float surface = (pd && pd->shape == PFIELD_SHAPE_SURFACE) ? 1.0f : 0.0f;
145
146                 if(gabr->options & BRULE_GOAL_AVOID_PREDICT) {
147                         /* estimate future location of target */
148                         get_effector_data(eff, &efd, &epoint, 1);
149
150                         mul_v3_fl(efd.vel, efd.distance / (val->max_speed * bbd->timestep));
151                         add_v3_v3(efd.loc, efd.vel);
152                         sub_v3_v3v3(efd.vec_to_point, pa->prev_state.co, efd.loc);
153                         efd.distance = len_v3(efd.vec_to_point);
154                 }
155
156                 if(rule->type == eBoidRuleType_Goal && boids->options & BOID_ALLOW_CLIMB && surface!=0.0f) {
157                         if(!bbd->goal_ob || bbd->goal_priority < priority) {
158                                 bbd->goal_ob = eob;
159                                 copy_v3_v3(bbd->goal_co, efd.loc);
160                                 copy_v3_v3(bbd->goal_nor, efd.nor);
161                         }
162                 }
163                 else if(rule->type == eBoidRuleType_Avoid && bpa->data.mode == eBoidMode_Climbing &&
164                         priority > 2.0f * gabr->fear_factor) {
165                         /* detach from surface and try to fly away from danger */
166                         negate_v3_v3(efd.vec_to_point, bpa->gravity);
167                 }
168
169                 VECCOPY(bbd->wanted_co, efd.vec_to_point);
170                 mul_v3_fl(bbd->wanted_co, mul);
171
172                 bbd->wanted_speed = val->max_speed * priority;
173
174                 /* with goals factor is approach velocity factor */
175                 if(rule->type == eBoidRuleType_Goal && boids->landing_smoothness > 0.0f) {
176                         float len2 = 2.0f*len_v3(pa->prev_state.vel);
177
178                         surface *= pa->size * boids->height;
179
180                         if(len2 > 0.0f && efd.distance - surface < len2) {
181                                 len2 = (efd.distance - surface)/len2;
182                                 bbd->wanted_speed *= pow(len2, boids->landing_smoothness);
183                         }
184                 }
185
186                 ret = 1;
187         }
188
189         return ret;
190 }
191
192 static int rule_avoid_collision(BoidRule *rule, BoidBrainData *bbd, BoidValues *val, ParticleData *pa)
193 {
194         BoidRuleAvoidCollision *acbr = (BoidRuleAvoidCollision*) rule;
195         KDTreeNearest *ptn = NULL;
196         ParticleTarget *pt;
197         BoidParticle *bpa = pa->boid;
198         ColliderCache *coll;
199         float vec[3] = {0.0f, 0.0f, 0.0f}, loc[3] = {0.0f, 0.0f, 0.0f};
200         float co1[3], vel1[3], co2[3], vel2[3];
201         float  len, t, inp, t_min = 2.0f;
202         int n, neighbors = 0, nearest = 0;
203         int ret = 0;
204
205         //check deflector objects first
206         if(acbr->options & BRULE_ACOLL_WITH_DEFLECTORS && bbd->sim->colliders) {
207                 ParticleCollision col;
208                 BVHTreeRayHit hit;
209                 float radius = val->personal_space * pa->size, ray_dir[3];
210
211                 VECCOPY(col.co1, pa->prev_state.co);
212                 add_v3_v3v3(col.co2, pa->prev_state.co, pa->prev_state.vel);
213                 sub_v3_v3v3(ray_dir, col.co2, col.co1);
214                 mul_v3_fl(ray_dir, acbr->look_ahead);
215                 col.f = 0.0f;
216                 hit.index = -1;
217                 hit.dist = col.original_ray_length = len_v3(ray_dir);
218
219                 /* find out closest deflector object */
220                 for(coll = bbd->sim->colliders->first; coll; coll=coll->next) {
221                         /* don't check with current ground object */
222                         if(coll->ob == bpa->ground)
223                                 continue;
224
225                         col.current = coll->ob;
226                         col.md = coll->collmd;
227
228                         if(col.md && col.md->bvhtree)
229                                 BLI_bvhtree_ray_cast(col.md->bvhtree, col.co1, ray_dir, radius, &hit, BKE_psys_collision_neartest_cb, &col);
230                 }
231                 /* then avoid that object */
232                 if(hit.index>=0) {
233                         t = hit.dist/col.original_ray_length;
234
235                         /* avoid head-on collision */
236                         if(dot_v3v3(col.pce.nor, pa->prev_state.ave) < -0.99f) {
237                                 /* don't know why, but uneven range [0.0,1.0] */
238                                 /* works much better than even [-1.0,1.0] */
239                                 bbd->wanted_co[0] = BLI_frand();
240                                 bbd->wanted_co[1] = BLI_frand();
241                                 bbd->wanted_co[2] = BLI_frand();
242                         }
243                         else {
244                                 copy_v3_v3(bbd->wanted_co, col.pce.nor);
245                         }
246
247                         mul_v3_fl(bbd->wanted_co, (1.0f - t) * val->personal_space * pa->size);
248
249                         bbd->wanted_speed = sqrt(t) * len_v3(pa->prev_state.vel);
250                         bbd->wanted_speed = MAX2(bbd->wanted_speed, val->min_speed);
251
252                         return 1;
253                 }
254         }
255
256         //check boids in own system
257         if(acbr->options & BRULE_ACOLL_WITH_BOIDS)
258         {
259                 neighbors = BLI_kdtree_range_search(bbd->sim->psys->tree, acbr->look_ahead * len_v3(pa->prev_state.vel), pa->prev_state.co, pa->prev_state.ave, &ptn);
260                 if(neighbors > 1) for(n=1; n<neighbors; n++) {
261                         VECCOPY(co1, pa->prev_state.co);
262                         VECCOPY(vel1, pa->prev_state.vel);
263                         VECCOPY(co2, (bbd->sim->psys->particles + ptn[n].index)->prev_state.co);
264                         VECCOPY(vel2, (bbd->sim->psys->particles + ptn[n].index)->prev_state.vel);
265
266                         sub_v3_v3v3(loc, co1, co2);
267
268                         sub_v3_v3v3(vec, vel1, vel2);
269                         
270                         inp = dot_v3v3(vec,vec);
271
272                         /* velocities not parallel */
273                         if(inp != 0.0f) {
274                                 t = -dot_v3v3(loc, vec)/inp;
275                                 /* cpa is not too far in the future so investigate further */
276                                 if(t > 0.0f && t < t_min) {
277                                         VECADDFAC(co1, co1, vel1, t);
278                                         VECADDFAC(co2, co2, vel2, t);
279                                         
280                                         sub_v3_v3v3(vec, co2, co1);
281
282                                         len = normalize_v3(vec);
283
284                                         /* distance of cpa is close enough */
285                                         if(len < 2.0f * val->personal_space * pa->size) {
286                                                 t_min = t;
287
288                                                 mul_v3_fl(vec, len_v3(vel1));
289                                                 mul_v3_fl(vec, (2.0f - t)/2.0f);
290                                                 sub_v3_v3v3(bbd->wanted_co, vel1, vec);
291                                                 bbd->wanted_speed = len_v3(bbd->wanted_co);
292                                                 ret = 1;
293                                         }
294                                 }
295                         }
296                 }
297         }
298         if(ptn){ MEM_freeN(ptn); ptn=NULL; }
299
300         /* check boids in other systems */
301         for(pt=bbd->sim->psys->targets.first; pt; pt=pt->next) {
302                 ParticleSystem *epsys = psys_get_target_system(bbd->sim->ob, pt);
303
304                 if(epsys) {
305                         neighbors = BLI_kdtree_range_search(epsys->tree, acbr->look_ahead * len_v3(pa->prev_state.vel), pa->prev_state.co, pa->prev_state.ave, &ptn);
306                         if(neighbors > 0) for(n=0; n<neighbors; n++) {
307                                 VECCOPY(co1, pa->prev_state.co);
308                                 VECCOPY(vel1, pa->prev_state.vel);
309                                 VECCOPY(co2, (epsys->particles + ptn[n].index)->prev_state.co);
310                                 VECCOPY(vel2, (epsys->particles + ptn[n].index)->prev_state.vel);
311
312                                 sub_v3_v3v3(loc, co1, co2);
313
314                                 sub_v3_v3v3(vec, vel1, vel2);
315                                 
316                                 inp = dot_v3v3(vec,vec);
317
318                                 /* velocities not parallel */
319                                 if(inp != 0.0f) {
320                                         t = -dot_v3v3(loc, vec)/inp;
321                                         /* cpa is not too far in the future so investigate further */
322                                         if(t > 0.0f && t < t_min) {
323                                                 VECADDFAC(co1, co1, vel1, t);
324                                                 VECADDFAC(co2, co2, vel2, t);
325                                                 
326                                                 sub_v3_v3v3(vec, co2, co1);
327
328                                                 len = normalize_v3(vec);
329
330                                                 /* distance of cpa is close enough */
331                                                 if(len < 2.0f * val->personal_space * pa->size) {
332                                                         t_min = t;
333
334                                                         mul_v3_fl(vec, len_v3(vel1));
335                                                         mul_v3_fl(vec, (2.0f - t)/2.0f);
336                                                         sub_v3_v3v3(bbd->wanted_co, vel1, vec);
337                                                         bbd->wanted_speed = len_v3(bbd->wanted_co);
338                                                         ret = 1;
339                                                 }
340                                         }
341                                 }
342                         }
343
344                         if(ptn){ MEM_freeN(ptn); ptn=NULL; }
345                 }
346         }
347
348
349         if(ptn && nearest==0)
350                 MEM_freeN(ptn);
351
352         return ret;
353 }
354 static int rule_separate(BoidRule *UNUSED(rule), BoidBrainData *bbd, BoidValues *val, ParticleData *pa)
355 {
356         KDTreeNearest *ptn = NULL;
357         ParticleTarget *pt;
358         float len = 2.0f * val->personal_space * pa->size + 1.0f;
359         float vec[3] = {0.0f, 0.0f, 0.0f};
360         int neighbors = BLI_kdtree_range_search(bbd->sim->psys->tree, 2.0f * val->personal_space * pa->size, pa->prev_state.co, NULL, &ptn);
361         int ret = 0;
362
363         if(neighbors > 1 && ptn[1].dist!=0.0f) {
364                 sub_v3_v3v3(vec, pa->prev_state.co, bbd->sim->psys->particles[ptn[1].index].state.co);
365                 mul_v3_fl(vec, (2.0f * val->personal_space * pa->size - ptn[1].dist) / ptn[1].dist);
366                 add_v3_v3(bbd->wanted_co, vec);
367                 bbd->wanted_speed = val->max_speed;
368                 len = ptn[1].dist;
369                 ret = 1;
370         }
371         if(ptn){ MEM_freeN(ptn); ptn=NULL; }
372
373         /* check other boid systems */
374         for(pt=bbd->sim->psys->targets.first; pt; pt=pt->next) {
375                 ParticleSystem *epsys = psys_get_target_system(bbd->sim->ob, pt);
376
377                 if(epsys) {
378                         neighbors = BLI_kdtree_range_search(epsys->tree, 2.0f * val->personal_space * pa->size, pa->prev_state.co, NULL, &ptn);
379                         
380                         if(neighbors > 0 && ptn[0].dist < len) {
381                                 sub_v3_v3v3(vec, pa->prev_state.co, ptn[0].co);
382                                 mul_v3_fl(vec, (2.0f * val->personal_space * pa->size - ptn[0].dist) / ptn[1].dist);
383                                 add_v3_v3(bbd->wanted_co, vec);
384                                 bbd->wanted_speed = val->max_speed;
385                                 len = ptn[0].dist;
386                                 ret = 1;
387                         }
388
389                         if(ptn){ MEM_freeN(ptn); ptn=NULL; }
390                 }
391         }
392         return ret;
393 }
394 static int rule_flock(BoidRule *UNUSED(rule), BoidBrainData *bbd, BoidValues *UNUSED(val), ParticleData *pa)
395 {
396         KDTreeNearest ptn[11];
397         float vec[3] = {0.0f, 0.0f, 0.0f}, loc[3] = {0.0f, 0.0f, 0.0f};
398         int neighbors = BLI_kdtree_find_n_nearest(bbd->sim->psys->tree, 11, pa->state.co, pa->prev_state.ave, ptn);
399         int n;
400         int ret = 0;
401
402         if(neighbors > 1) {
403                 for(n=1; n<neighbors; n++) {
404                         add_v3_v3(loc, bbd->sim->psys->particles[ptn[n].index].prev_state.co);
405                         add_v3_v3(vec, bbd->sim->psys->particles[ptn[n].index].prev_state.vel);
406                 }
407
408                 mul_v3_fl(loc, 1.0f/((float)neighbors - 1.0f));
409                 mul_v3_fl(vec, 1.0f/((float)neighbors - 1.0f));
410
411                 sub_v3_v3(loc, pa->prev_state.co);
412                 sub_v3_v3(vec, pa->prev_state.vel);
413
414                 add_v3_v3(bbd->wanted_co, vec);
415                 add_v3_v3(bbd->wanted_co, loc);
416                 bbd->wanted_speed = len_v3(bbd->wanted_co);
417
418                 ret = 1;
419         }
420         return ret;
421 }
422 static int rule_follow_leader(BoidRule *rule, BoidBrainData *bbd, BoidValues *val, ParticleData *pa)
423 {
424         BoidRuleFollowLeader *flbr = (BoidRuleFollowLeader*) rule;
425         float vec[3] = {0.0f, 0.0f, 0.0f}, loc[3] = {0.0f, 0.0f, 0.0f};
426         float mul, len;
427         int n = (flbr->queue_size <= 1) ? bbd->sim->psys->totpart : flbr->queue_size;
428         int i, ret = 0, p = pa - bbd->sim->psys->particles;
429
430         if(flbr->ob) {
431                 float vec2[3], t;
432
433                 /* first check we're not blocking the leader*/
434                 sub_v3_v3v3(vec, flbr->loc, flbr->oloc);
435                 mul_v3_fl(vec, 1.0f/bbd->timestep);
436
437                 sub_v3_v3v3(loc, pa->prev_state.co, flbr->oloc);
438
439                 mul = dot_v3v3(vec, vec);
440
441                 /* leader is not moving */
442                 if(mul < 0.01f) {
443                         len = len_v3(loc);
444                         /* too close to leader */
445                         if(len < 2.0f * val->personal_space * pa->size) {
446                                 VECCOPY(bbd->wanted_co, loc);
447                                 bbd->wanted_speed = val->max_speed;
448                                 return 1;
449                         }
450                 }
451                 else {
452                         t = dot_v3v3(loc, vec)/mul;
453
454                         /* possible blocking of leader in near future */
455                         if(t > 0.0f && t < 3.0f) {
456                                 VECCOPY(vec2, vec);
457                                 mul_v3_fl(vec2, t);
458
459                                 sub_v3_v3v3(vec2, loc, vec2);
460
461                                 len = len_v3(vec2);
462
463                                 if(len < 2.0f * val->personal_space * pa->size) {
464                                         VECCOPY(bbd->wanted_co, vec2);
465                                         bbd->wanted_speed = val->max_speed * (3.0f - t)/3.0f;
466                                         return 1;
467                                 }
468                         }
469                 }
470
471                 /* not blocking so try to follow leader */
472                 if(p && flbr->options & BRULE_LEADER_IN_LINE) {
473                         VECCOPY(vec, bbd->sim->psys->particles[p-1].prev_state.vel);
474                         VECCOPY(loc, bbd->sim->psys->particles[p-1].prev_state.co);
475                 }
476                 else {
477                         VECCOPY(loc, flbr->oloc);
478                         sub_v3_v3v3(vec, flbr->loc, flbr->oloc);
479                         mul_v3_fl(vec, 1.0f/bbd->timestep);
480                 }
481                 
482                 /* fac is seconds behind leader */
483                 VECADDFAC(loc, loc, vec, -flbr->distance);
484
485                 sub_v3_v3v3(bbd->wanted_co, loc, pa->prev_state.co);
486                 bbd->wanted_speed = len_v3(bbd->wanted_co);
487                         
488                 ret = 1;
489         }
490         else if(p % n) {
491                 float vec2[3], t, t_min = 3.0f;
492
493                 /* first check we're not blocking any leaders */
494                 for(i = 0; i< bbd->sim->psys->totpart; i+=n){
495                         VECCOPY(vec, bbd->sim->psys->particles[i].prev_state.vel);
496
497                         sub_v3_v3v3(loc, pa->prev_state.co, bbd->sim->psys->particles[i].prev_state.co);
498
499                         mul = dot_v3v3(vec, vec);
500
501                         /* leader is not moving */
502                         if(mul < 0.01f) {
503                                 len = len_v3(loc);
504                                 /* too close to leader */
505                                 if(len < 2.0f * val->personal_space * pa->size) {
506                                         VECCOPY(bbd->wanted_co, loc);
507                                         bbd->wanted_speed = val->max_speed;
508                                         return 1;
509                                 }
510                         }
511                         else {
512                                 t = dot_v3v3(loc, vec)/mul;
513
514                                 /* possible blocking of leader in near future */
515                                 if(t > 0.0f && t < t_min) {
516                                         VECCOPY(vec2, vec);
517                                         mul_v3_fl(vec2, t);
518
519                                         sub_v3_v3v3(vec2, loc, vec2);
520
521                                         len = len_v3(vec2);
522
523                                         if(len < 2.0f * val->personal_space * pa->size) {
524                                                 t_min = t;
525                                                 VECCOPY(bbd->wanted_co, loc);
526                                                 bbd->wanted_speed = val->max_speed * (3.0f - t)/3.0f;
527                                                 ret = 1;
528                                         }
529                                 }
530                         }
531                 }
532
533                 if(ret) return 1;
534
535                 /* not blocking so try to follow leader */
536                 if(flbr->options & BRULE_LEADER_IN_LINE) {
537                         VECCOPY(vec, bbd->sim->psys->particles[p-1].prev_state.vel);
538                         VECCOPY(loc, bbd->sim->psys->particles[p-1].prev_state.co);
539                 }
540                 else {
541                         VECCOPY(vec, bbd->sim->psys->particles[p - p%n].prev_state.vel);
542                         VECCOPY(loc, bbd->sim->psys->particles[p - p%n].prev_state.co);
543                 }
544                 
545                 /* fac is seconds behind leader */
546                 VECADDFAC(loc, loc, vec, -flbr->distance);
547
548                 sub_v3_v3v3(bbd->wanted_co, loc, pa->prev_state.co);
549                 bbd->wanted_speed = len_v3(bbd->wanted_co);
550                 
551                 ret = 1;
552         }
553
554         return ret;
555 }
556 static int rule_average_speed(BoidRule *rule, BoidBrainData *bbd, BoidValues *val, ParticleData *pa)
557 {
558         BoidParticle *bpa = pa->boid;
559         BoidRuleAverageSpeed *asbr = (BoidRuleAverageSpeed*)rule;
560         float vec[3] = {0.0f, 0.0f, 0.0f};
561
562         if(asbr->wander > 0.0f) {
563                 /* abuse pa->r_ave for wandering */
564                 bpa->wander[0] += asbr->wander * (-1.0f + 2.0f * BLI_frand());
565                 bpa->wander[1] += asbr->wander * (-1.0f + 2.0f * BLI_frand());
566                 bpa->wander[2] += asbr->wander * (-1.0f + 2.0f * BLI_frand());
567
568                 normalize_v3(bpa->wander);
569
570                 VECCOPY(vec, bpa->wander);
571
572                 mul_qt_v3(pa->prev_state.rot, vec);
573
574                 VECCOPY(bbd->wanted_co, pa->prev_state.ave);
575
576                 mul_v3_fl(bbd->wanted_co, 1.1f);
577
578                 add_v3_v3(bbd->wanted_co, vec);
579
580                 /* leveling */
581                 if(asbr->level > 0.0f && psys_uses_gravity(bbd->sim)) {
582                         project_v3_v3v3(vec, bbd->wanted_co, bbd->sim->scene->physics_settings.gravity);
583                         mul_v3_fl(vec, asbr->level);
584                         sub_v3_v3(bbd->wanted_co, vec);
585                 }
586         }
587         else {
588                 VECCOPY(bbd->wanted_co, pa->prev_state.ave);
589
590                 /* may happen at birth */
591                 if(dot_v2v2(bbd->wanted_co,bbd->wanted_co)==0.0f) {
592                         bbd->wanted_co[0] = 2.0f*(0.5f - BLI_frand());
593                         bbd->wanted_co[1] = 2.0f*(0.5f - BLI_frand());
594                         bbd->wanted_co[2] = 2.0f*(0.5f - BLI_frand());
595                 }
596                 
597                 /* leveling */
598                 if(asbr->level > 0.0f && psys_uses_gravity(bbd->sim)) {
599                         project_v3_v3v3(vec, bbd->wanted_co, bbd->sim->scene->physics_settings.gravity);
600                         mul_v3_fl(vec, asbr->level);
601                         sub_v3_v3(bbd->wanted_co, vec);
602                 }
603
604         }
605         bbd->wanted_speed = asbr->speed * val->max_speed;
606         
607         return 1;
608 }
609 static int rule_fight(BoidRule *rule, BoidBrainData *bbd, BoidValues *val, ParticleData *pa)
610 {
611         BoidRuleFight *fbr = (BoidRuleFight*)rule;
612         KDTreeNearest *ptn = NULL;
613         ParticleTarget *pt;
614         ParticleData *epars;
615         ParticleData *enemy_pa = NULL;
616         BoidParticle *bpa;
617         /* friends & enemies */
618         float closest_enemy[3] = {0.0f,0.0f,0.0f};
619         float closest_dist = fbr->distance + 1.0f;
620         float f_strength = 0.0f, e_strength = 0.0f;
621         float health = 0.0f;
622         int n, ret = 0;
623
624         /* calculate own group strength */
625         int neighbors = BLI_kdtree_range_search(bbd->sim->psys->tree, fbr->distance, pa->prev_state.co, NULL, &ptn);
626         for(n=0; n<neighbors; n++) {
627                 bpa = bbd->sim->psys->particles[ptn[n].index].boid;
628                 health += bpa->data.health;
629         }
630
631         f_strength += bbd->part->boids->strength * health;
632
633         if(ptn){ MEM_freeN(ptn); ptn=NULL; }
634
635         /* add other friendlies and calculate enemy strength and find closest enemy */
636         for(pt=bbd->sim->psys->targets.first; pt; pt=pt->next) {
637                 ParticleSystem *epsys = psys_get_target_system(bbd->sim->ob, pt);
638                 if(epsys) {
639                         epars = epsys->particles;
640
641                         neighbors = BLI_kdtree_range_search(epsys->tree, fbr->distance, pa->prev_state.co, NULL, &ptn);
642                         
643                         health = 0.0f;
644
645                         for(n=0; n<neighbors; n++) {
646                                 bpa = epars[ptn[n].index].boid;
647                                 health += bpa->data.health;
648
649                                 if(n==0 && pt->mode==PTARGET_MODE_ENEMY && ptn[n].dist < closest_dist) {
650                                         VECCOPY(closest_enemy, ptn[n].co);
651                                         closest_dist = ptn[n].dist;
652                                         enemy_pa = epars + ptn[n].index;
653                                 }
654                         }
655                         if(pt->mode==PTARGET_MODE_ENEMY)
656                                 e_strength += epsys->part->boids->strength * health;
657                         else if(pt->mode==PTARGET_MODE_FRIEND)
658                                 f_strength += epsys->part->boids->strength * health;
659
660                         if(ptn){ MEM_freeN(ptn); ptn=NULL; }
661                 }
662         }
663         /* decide action if enemy presence found */
664         if(e_strength > 0.0f) {
665                 sub_v3_v3v3(bbd->wanted_co, closest_enemy, pa->prev_state.co);
666
667                 /* attack if in range */
668                 if(closest_dist <= bbd->part->boids->range + pa->size + enemy_pa->size) {
669                         float damage = BLI_frand();
670                         float enemy_dir[3];
671
672                         normalize_v3_v3(enemy_dir, bbd->wanted_co);
673
674                         /* fight mode */
675                         bbd->wanted_speed = 0.0f;
676
677                         /* must face enemy to fight */
678                         if(dot_v3v3(pa->prev_state.ave, enemy_dir)>0.5f) {
679                                 bpa = enemy_pa->boid;
680                                 bpa->data.health -= bbd->part->boids->strength * bbd->timestep * ((1.0f-bbd->part->boids->accuracy)*damage + bbd->part->boids->accuracy);
681                         }
682                 }
683                 else {
684                         /* approach mode */
685                         bbd->wanted_speed = val->max_speed;
686                 }
687
688                 /* check if boid doesn't want to fight */
689                 bpa = pa->boid;
690                 if(bpa->data.health/bbd->part->boids->health * bbd->part->boids->aggression < e_strength / f_strength) {
691                         /* decide to flee */
692                         if(closest_dist < fbr->flee_distance * fbr->distance) {
693                                 negate_v3(bbd->wanted_co);
694                                 bbd->wanted_speed = val->max_speed;
695                         }
696                         else { /* wait for better odds */
697                                 bbd->wanted_speed = 0.0f;
698                         }
699                 }
700
701                 ret = 1;
702         }
703
704         return ret;
705 }
706
707 typedef int (*boid_rule_cb)(BoidRule *rule, BoidBrainData *data, BoidValues *val, ParticleData *pa);
708
709 static boid_rule_cb boid_rules[] = {
710         rule_none,
711         rule_goal_avoid,
712         rule_goal_avoid,
713         rule_avoid_collision,
714         rule_separate,
715         rule_flock,
716         rule_follow_leader,
717         rule_average_speed,
718         rule_fight,
719         //rule_help,
720         //rule_protect,
721         //rule_hide,
722         //rule_follow_path,
723         //rule_follow_wall
724 };
725
726 static void set_boid_values(BoidValues *val, BoidSettings *boids, ParticleData *pa)
727 {
728         BoidParticle *bpa = pa->boid;
729
730         if(ELEM(bpa->data.mode, eBoidMode_OnLand, eBoidMode_Climbing)) {
731                 val->max_speed = boids->land_max_speed * bpa->data.health/boids->health;
732                 val->max_acc = boids->land_max_acc * val->max_speed;
733                 val->max_ave = boids->land_max_ave * (float)M_PI * bpa->data.health/boids->health;
734                 val->min_speed = 0.0f; /* no minimum speed on land */
735                 val->personal_space = boids->land_personal_space;
736                 val->jump_speed = boids->land_jump_speed * bpa->data.health/boids->health;
737         }
738         else {
739                 val->max_speed = boids->air_max_speed * bpa->data.health/boids->health;
740                 val->max_acc = boids->air_max_acc * val->max_speed;
741                 val->max_ave = boids->air_max_ave * (float)M_PI * bpa->data.health/boids->health;
742                 val->min_speed = boids->air_min_speed * boids->air_max_speed;
743                 val->personal_space = boids->air_personal_space;
744                 val->jump_speed = 0.0f; /* no jumping in air */
745         }
746 }
747
748 static Object *boid_find_ground(BoidBrainData *bbd, ParticleData *pa, float *ground_co, float *ground_nor)
749 {
750         BoidParticle *bpa = pa->boid;
751
752         if(bpa->data.mode == eBoidMode_Climbing) {
753                 SurfaceModifierData *surmd = NULL;
754                 float x[3], v[3];
755                 
756                 surmd = (SurfaceModifierData *)modifiers_findByType ( bpa->ground, eModifierType_Surface );
757
758                 /* take surface velocity into account */
759                 closest_point_on_surface(surmd, pa->state.co, x, NULL, v);
760                 add_v3_v3(x, v);
761
762                 /* get actual position on surface */
763                 closest_point_on_surface(surmd, x, ground_co, ground_nor, NULL);
764
765                 return bpa->ground;
766         }
767         else {
768                 float zvec[3] = {0.0f, 0.0f, 2000.0f};
769                 ParticleCollision col;
770                 ColliderCache *coll;
771                 BVHTreeRayHit hit;
772                 float radius = 0.0f, t, ray_dir[3];
773
774                 if(!bbd->sim->colliders)
775                         return NULL;
776
777                 /* first try to find below boid */
778                 copy_v3_v3(col.co1, pa->state.co);
779                 sub_v3_v3v3(col.co2, pa->state.co, zvec);
780                 sub_v3_v3v3(ray_dir, col.co2, col.co1);
781                 col.f = 0.0f;
782                 hit.index = -1;
783                 hit.dist = col.original_ray_length = len_v3(ray_dir);
784                 col.pce.inside = 0;
785
786                 for(coll = bbd->sim->colliders->first; coll; coll = coll->next){
787                         col.current = coll->ob;
788                         col.md = coll->collmd;
789                         col.fac1 = col.fac2 = 0.f;
790
791                         if(col.md && col.md->bvhtree)
792                                 BLI_bvhtree_ray_cast(col.md->bvhtree, col.co1, ray_dir, radius, &hit, BKE_psys_collision_neartest_cb, &col);
793                 }
794                 /* then use that object */
795                 if(hit.index>=0) {
796                         t = hit.dist/col.original_ray_length;
797                         interp_v3_v3v3(ground_co, col.co1, col.co2, t);
798                         normalize_v3_v3(ground_nor, col.pce.nor);
799                         return col.hit;
800                 }
801
802                 /* couldn't find below, so find upmost deflector object */
803                 add_v3_v3v3(col.co1, pa->state.co, zvec);
804                 sub_v3_v3v3(col.co2, pa->state.co, zvec);
805                 sub_v3_v3(col.co2, zvec);
806                 sub_v3_v3v3(ray_dir, col.co2, col.co1);
807                 col.f = 0.0f;
808                 hit.index = -1;
809                 hit.dist = col.original_ray_length = len_v3(ray_dir);
810
811                 for(coll = bbd->sim->colliders->first; coll; coll = coll->next){
812                         col.current = coll->ob;
813                         col.md = coll->collmd;
814
815                         if(col.md && col.md->bvhtree)
816                                 BLI_bvhtree_ray_cast(col.md->bvhtree, col.co1, ray_dir, radius, &hit, BKE_psys_collision_neartest_cb, &col);
817                 }
818                 /* then use that object */
819                 if(hit.index>=0) {
820                         t = hit.dist/col.original_ray_length;
821                         interp_v3_v3v3(ground_co, col.co1, col.co2, t);
822                         normalize_v3_v3(ground_nor, col.pce.nor);
823                         return col.hit;
824                 }
825
826                 /* default to z=0 */
827                 VECCOPY(ground_co, pa->state.co);
828                 ground_co[2] = 0;
829                 ground_nor[0] = ground_nor[1] = 0.0f;
830                 ground_nor[2] = 1.0f;
831                 return NULL;
832         }
833 }
834 static int boid_rule_applies(ParticleData *pa, BoidSettings *UNUSED(boids), BoidRule *rule)
835 {
836         BoidParticle *bpa = pa->boid;
837
838         if(rule==NULL)
839                 return 0;
840         
841         if(ELEM(bpa->data.mode, eBoidMode_OnLand, eBoidMode_Climbing) && rule->flag & BOIDRULE_ON_LAND)
842                 return 1;
843         
844         if(bpa->data.mode==eBoidMode_InAir && rule->flag & BOIDRULE_IN_AIR)
845                 return 1;
846
847         return 0;
848 }
849 void boids_precalc_rules(ParticleSettings *part, float cfra)
850 {
851         BoidState *state = part->boids->states.first;
852         BoidRule *rule;
853         for(; state; state=state->next) {
854                 for(rule = state->rules.first; rule; rule=rule->next) {
855                         if(rule->type==eBoidRuleType_FollowLeader) {
856                                 BoidRuleFollowLeader *flbr = (BoidRuleFollowLeader*) rule;
857
858                                 if(flbr->ob && flbr->cfra != cfra) {
859                                         /* save object locations for velocity calculations */
860                                         VECCOPY(flbr->oloc, flbr->loc);
861                                         VECCOPY(flbr->loc, flbr->ob->obmat[3]);
862                                         flbr->cfra = cfra;
863                                 }
864                         }
865                 }
866         }
867 }
868 static void boid_climb(BoidSettings *boids, ParticleData *pa, float *surface_co, float *surface_nor)
869 {
870         BoidParticle *bpa = pa->boid;
871         float nor[3], vel[3];
872         copy_v3_v3(nor, surface_nor);
873
874         /* gather apparent gravity */
875         VECADDFAC(bpa->gravity, bpa->gravity, surface_nor, -1.0f);
876         normalize_v3(bpa->gravity);
877
878         /* raise boid it's size from surface */
879         mul_v3_fl(nor, pa->size * boids->height);
880         add_v3_v3v3(pa->state.co, surface_co, nor);
881
882         /* remove normal component from velocity */
883         project_v3_v3v3(vel, pa->state.vel, surface_nor);
884         sub_v3_v3v3(pa->state.vel, pa->state.vel, vel);
885 }
886 static float boid_goal_signed_dist(float *boid_co, float *goal_co, float *goal_nor)
887 {
888         float vec[3];
889
890         sub_v3_v3v3(vec, boid_co, goal_co);
891
892         return dot_v3v3(vec, goal_nor);
893 }
894 /* wanted_co is relative to boid location */
895 static int apply_boid_rule(BoidBrainData *bbd, BoidRule *rule, BoidValues *val, ParticleData *pa, float fuzziness)
896 {
897         if(rule==NULL)
898                 return 0;
899
900         if(boid_rule_applies(pa, bbd->part->boids, rule)==0)
901                 return 0;
902
903         if(boid_rules[rule->type](rule, bbd, val, pa)==0)
904                 return 0;
905
906         if(fuzziness < 0.0f || compare_len_v3v3(bbd->wanted_co, pa->prev_state.vel, fuzziness * len_v3(pa->prev_state.vel))==0)
907                 return 1;
908         else
909                 return 0;
910 }
911 static BoidState *get_boid_state(BoidSettings *boids, ParticleData *pa)
912 {
913         BoidState *state = boids->states.first;
914         BoidParticle *bpa = pa->boid;
915
916         for(; state; state=state->next) {
917                 if(state->id==bpa->data.state_id)
918                         return state;
919         }
920
921         /* for some reason particle isn't at a valid state */
922         state = boids->states.first;
923         if(state)
924                 bpa->data.state_id = state->id;
925
926         return state;
927 }
928 //static int boid_condition_is_true(BoidCondition *cond) {
929 //      /* TODO */
930 //      return 0;
931 //}
932
933 /* determines the velocity the boid wants to have */
934 void boid_brain(BoidBrainData *bbd, int p, ParticleData *pa)
935 {
936         BoidRule *rule;
937         BoidSettings *boids = bbd->part->boids;
938         BoidValues val;
939         BoidState *state = get_boid_state(boids, pa);
940         BoidParticle *bpa = pa->boid;
941         ParticleSystem *psys = bbd->sim->psys;
942         int rand;
943         //BoidCondition *cond;
944
945         if(bpa->data.health <= 0.0f) {
946                 pa->alive = PARS_DYING;
947                 pa->dietime = bbd->cfra;
948                 return;
949         }
950
951         //planned for near future
952         //cond = state->conditions.first;
953         //for(; cond; cond=cond->next) {
954         //      if(boid_condition_is_true(cond)) {
955         //              pa->boid->state_id = cond->state_id;
956         //              state = get_boid_state(boids, pa);
957         //              break; /* only first true condition is used */
958         //      }
959         //}
960
961         bbd->wanted_co[0]=bbd->wanted_co[1]=bbd->wanted_co[2]=bbd->wanted_speed=0.0f;
962
963         /* create random seed for every particle & frame */
964         rand = (int)(PSYS_FRAND(psys->seed + p) * 1000);
965         rand = (int)(PSYS_FRAND((int)bbd->cfra + rand) * 1000);
966
967         set_boid_values(&val, bbd->part->boids, pa);
968
969         /* go through rules */
970         switch(state->ruleset_type) {
971                 case eBoidRulesetType_Fuzzy:
972                 {
973                         for(rule = state->rules.first; rule; rule = rule->next) {
974                                 if(apply_boid_rule(bbd, rule, &val, pa, state->rule_fuzziness))
975                                         break; /* only first nonzero rule that comes through fuzzy rule is applied */
976                         }
977                         break;
978                 }
979                 case eBoidRulesetType_Random:
980                 {
981                         /* use random rule for each particle (allways same for same particle though) */
982                         rule = BLI_findlink(&state->rules, rand % BLI_countlist(&state->rules));
983
984                         apply_boid_rule(bbd, rule, &val, pa, -1.0);
985                 }
986                 case eBoidRulesetType_Average:
987                 {
988                         float wanted_co[3] = {0.0f, 0.0f, 0.0f}, wanted_speed = 0.0f;
989                         int n = 0;
990                         for(rule = state->rules.first; rule; rule=rule->next) {
991                                 if(apply_boid_rule(bbd, rule, &val, pa, -1.0f)) {
992                                         add_v3_v3(wanted_co, bbd->wanted_co);
993                                         wanted_speed += bbd->wanted_speed;
994                                         n++;
995                                         bbd->wanted_co[0]=bbd->wanted_co[1]=bbd->wanted_co[2]=bbd->wanted_speed=0.0f;
996                                 }
997                         }
998
999                         if(n > 1) {
1000                                 mul_v3_fl(wanted_co, 1.0f/(float)n);
1001                                 wanted_speed /= (float)n;
1002                         }
1003
1004                         VECCOPY(bbd->wanted_co, wanted_co);
1005                         bbd->wanted_speed = wanted_speed;
1006                         break;
1007                 }
1008
1009         }
1010
1011         /* decide on jumping & liftoff */
1012         if(bpa->data.mode == eBoidMode_OnLand) {
1013                 /* fuzziness makes boids capable of misjudgement */
1014                 float mul = 1.0f + state->rule_fuzziness;
1015                 
1016                 if(boids->options & BOID_ALLOW_FLIGHT && bbd->wanted_co[2] > 0.0f) {
1017                         float cvel[3], dir[3];
1018
1019                         VECCOPY(dir, pa->prev_state.ave);
1020                         normalize_v2(dir);
1021
1022                         VECCOPY(cvel, bbd->wanted_co);
1023                         normalize_v2(cvel);
1024
1025                         if(dot_v2v2(cvel, dir) > 0.95f / mul)
1026                                 bpa->data.mode = eBoidMode_Liftoff;
1027                 }
1028                 else if(val.jump_speed > 0.0f) {
1029                         float jump_v[3];
1030                         int jump = 0;
1031
1032                         /* jump to get to a location */
1033                         if(bbd->wanted_co[2] > 0.0f) {
1034                                 float cvel[3], dir[3];
1035                                 float z_v, ground_v, cur_v;
1036                                 float len;
1037
1038                                 VECCOPY(dir, pa->prev_state.ave);
1039                                 normalize_v2(dir);
1040
1041                                 VECCOPY(cvel, bbd->wanted_co);
1042                                 normalize_v2(cvel);
1043
1044                                 len = len_v2(pa->prev_state.vel);
1045
1046                                 /* first of all, are we going in a suitable direction? */
1047                                 /* or at a suitably slow speed */
1048                                 if(dot_v2v2(cvel, dir) > 0.95f / mul || len <= state->rule_fuzziness) {
1049                                         /* try to reach goal at highest point of the parabolic path */
1050                                         cur_v = len_v2(pa->prev_state.vel);
1051                                         z_v = sasqrt(-2.0f * bbd->sim->scene->physics_settings.gravity[2] * bbd->wanted_co[2]);
1052                                         ground_v = len_v2(bbd->wanted_co)*sasqrt(-0.5f * bbd->sim->scene->physics_settings.gravity[2] / bbd->wanted_co[2]);
1053
1054                                         len = sasqrt((ground_v-cur_v)*(ground_v-cur_v) + z_v*z_v);
1055
1056                                         if(len < val.jump_speed * mul || bbd->part->boids->options & BOID_ALLOW_FLIGHT) {
1057                                                 jump = 1;
1058
1059                                                 len = MIN2(len, val.jump_speed);
1060
1061                                                 VECCOPY(jump_v, dir);
1062                                                 jump_v[2] = z_v;
1063                                                 mul_v3_fl(jump_v, ground_v);
1064
1065                                                 normalize_v3(jump_v);
1066                                                 mul_v3_fl(jump_v, len);
1067                                                 add_v2_v2v2(jump_v, jump_v, pa->prev_state.vel);
1068                                         }
1069                                 }
1070                         }
1071
1072                         /* jump to go faster */
1073                         if(jump == 0 && val.jump_speed > val.max_speed && bbd->wanted_speed > val.max_speed) {
1074                                 
1075                         }
1076
1077                         if(jump) {
1078                                 VECCOPY(pa->prev_state.vel, jump_v);
1079                                 bpa->data.mode = eBoidMode_Falling;
1080                         }
1081                 }
1082         }
1083 }
1084 /* tries to realize the wanted velocity taking all constraints into account */
1085 void boid_body(BoidBrainData *bbd, ParticleData *pa)
1086 {
1087         BoidSettings *boids = bbd->part->boids;
1088         BoidParticle *bpa = pa->boid;
1089         BoidValues val;
1090         EffectedPoint epoint;
1091         float acc[3] = {0.0f, 0.0f, 0.0f}, tan_acc[3], nor_acc[3];
1092         float dvec[3], bvec[3];
1093         float new_dir[3], new_speed;
1094         float old_dir[3], old_speed;
1095         float wanted_dir[3];
1096         float q[4], mat[3][3]; /* rotation */
1097         float ground_co[3] = {0.0f, 0.0f, 0.0f}, ground_nor[3] = {0.0f, 0.0f, 1.0f};
1098         float force[3] = {0.0f, 0.0f, 0.0f};
1099         float pa_mass=bbd->part->mass, dtime=bbd->dfra*bbd->timestep;
1100
1101         set_boid_values(&val, boids, pa);
1102
1103         /* make sure there's something in new velocity, location & rotation */
1104         copy_particle_key(&pa->state,&pa->prev_state,0);
1105
1106         if(bbd->part->flag & PART_SIZEMASS)
1107                 pa_mass*=pa->size;
1108
1109         /* if boids can't fly they fall to the ground */
1110         if((boids->options & BOID_ALLOW_FLIGHT)==0 && ELEM(bpa->data.mode, eBoidMode_OnLand, eBoidMode_Climbing)==0 && psys_uses_gravity(bbd->sim))
1111                 bpa->data.mode = eBoidMode_Falling;
1112
1113         if(bpa->data.mode == eBoidMode_Falling) {
1114                 /* Falling boids are only effected by gravity. */
1115                 acc[2] = bbd->sim->scene->physics_settings.gravity[2];
1116         }
1117         else {
1118                 /* figure out acceleration */
1119                 float landing_level = 2.0f;
1120                 float level = landing_level + 1.0f;
1121                 float new_vel[3];
1122
1123                 if(bpa->data.mode == eBoidMode_Liftoff) {
1124                         bpa->data.mode = eBoidMode_InAir;
1125                         bpa->ground = boid_find_ground(bbd, pa, ground_co, ground_nor);
1126                 }
1127                 else if(bpa->data.mode == eBoidMode_InAir && boids->options & BOID_ALLOW_LAND) {
1128                         /* auto-leveling & landing if close to ground */
1129
1130                         bpa->ground = boid_find_ground(bbd, pa, ground_co, ground_nor);
1131                         
1132                         /* level = how many particle sizes above ground */
1133                         level = (pa->prev_state.co[2] - ground_co[2])/(2.0f * pa->size) - 0.5f;
1134
1135                         landing_level = - boids->landing_smoothness * pa->prev_state.vel[2] * pa_mass;
1136
1137                         if(pa->prev_state.vel[2] < 0.0f) {
1138                                 if(level < 1.0f) {
1139                                         bbd->wanted_co[0] = bbd->wanted_co[1] = bbd->wanted_co[2] = 0.0f;
1140                                         bbd->wanted_speed = 0.0f;
1141                                         bpa->data.mode = eBoidMode_Falling;
1142                                 }
1143                                 else if(level < landing_level) {
1144                                         bbd->wanted_speed *= (level - 1.0f)/landing_level;
1145                                         bbd->wanted_co[2] *= (level - 1.0f)/landing_level;
1146                                 }
1147                         }
1148                 }
1149
1150                 VECCOPY(old_dir, pa->prev_state.ave);
1151                 new_speed = normalize_v3_v3(wanted_dir, bbd->wanted_co);
1152
1153                 /* first check if we have valid direction we want to go towards */
1154                 if(new_speed == 0.0f) {
1155                         VECCOPY(new_dir, old_dir);
1156                 }
1157                 else {
1158                         float old_dir2[2], wanted_dir2[2], nor[3], angle;
1159                         copy_v2_v2(old_dir2, old_dir);
1160                         normalize_v2(old_dir2);
1161                         copy_v2_v2(wanted_dir2, wanted_dir);
1162                         normalize_v2(wanted_dir2);
1163
1164                         /* choose random direction to turn if wanted velocity */
1165                         /* is directly behind regardless of z-coordinate */
1166                         if(dot_v2v2(old_dir2, wanted_dir2) < -0.99f) {
1167                                 wanted_dir[0] = 2.0f*(0.5f - BLI_frand());
1168                                 wanted_dir[1] = 2.0f*(0.5f - BLI_frand());
1169                                 wanted_dir[2] = 2.0f*(0.5f - BLI_frand());
1170                                 normalize_v3(wanted_dir);
1171                         }
1172
1173                         /* constrain direction with maximum angular velocity */
1174                         angle = saacos(dot_v3v3(old_dir, wanted_dir));
1175                         angle = MIN2(angle, val.max_ave);
1176
1177                         cross_v3_v3v3(nor, old_dir, wanted_dir);
1178                         axis_angle_to_quat( q,nor, angle);
1179                         VECCOPY(new_dir, old_dir);
1180                         mul_qt_v3(q, new_dir);
1181                         normalize_v3(new_dir);
1182
1183                         /* save direction in case resulting velocity too small */
1184                         axis_angle_to_quat( q,nor, angle*dtime);
1185                         VECCOPY(pa->state.ave, old_dir);
1186                         mul_qt_v3(q, pa->state.ave);
1187                         normalize_v3(pa->state.ave);
1188                 }
1189
1190                 /* constrain speed with maximum acceleration */
1191                 old_speed = len_v3(pa->prev_state.vel);
1192                 
1193                 if(bbd->wanted_speed < old_speed)
1194                         new_speed = MAX2(bbd->wanted_speed, old_speed - val.max_acc);
1195                 else
1196                         new_speed = MIN2(bbd->wanted_speed, old_speed + val.max_acc);
1197
1198                 /* combine direction and speed */
1199                 VECCOPY(new_vel, new_dir);
1200                 mul_v3_fl(new_vel, new_speed);
1201
1202                 /* maintain minimum flying velocity if not landing */
1203                 if(level >= landing_level) {
1204                         float len2 = dot_v2v2(new_vel,new_vel);
1205                         float root;
1206
1207                         len2 = MAX2(len2, val.min_speed*val.min_speed);
1208                         root = sasqrt(new_speed*new_speed - len2);
1209
1210                         new_vel[2] = new_vel[2] < 0.0f ? -root : root;
1211
1212                         normalize_v2(new_vel);
1213                         mul_v2_fl(new_vel, sasqrt(len2));
1214                 }
1215
1216                 /* finally constrain speed to max speed */
1217                 new_speed = normalize_v3(new_vel);
1218                 mul_v3_fl(new_vel, MIN2(new_speed, val.max_speed));
1219
1220                 /* get acceleration from difference of velocities */
1221                 sub_v3_v3v3(acc, new_vel, pa->prev_state.vel);
1222
1223                 /* break acceleration to components */
1224                 project_v3_v3v3(tan_acc, acc, pa->prev_state.ave);
1225                 sub_v3_v3v3(nor_acc, acc, tan_acc);
1226         }
1227
1228         /* account for effectors */
1229         pd_point_from_particle(bbd->sim, pa, &pa->state, &epoint);
1230         pdDoEffectors(bbd->sim->psys->effectors, bbd->sim->colliders, bbd->part->effector_weights, &epoint, force, NULL);
1231
1232         if(ELEM(bpa->data.mode, eBoidMode_OnLand, eBoidMode_Climbing)) {
1233                 float length = normalize_v3(force);
1234
1235                 length = MAX2(0.0f, length - boids->land_stick_force);
1236
1237                 mul_v3_fl(force, length);
1238         }
1239         
1240         add_v3_v3(acc, force);
1241
1242         /* store smoothed acceleration for nice banking etc. */
1243         VECADDFAC(bpa->data.acc, bpa->data.acc, acc, dtime);
1244         mul_v3_fl(bpa->data.acc, 1.0f / (1.0f + dtime));
1245
1246         /* integrate new location & velocity */
1247
1248         /* by regarding the acceleration as a force at this stage we*/
1249         /* can get better control allthough it's a bit unphysical       */
1250         mul_v3_fl(acc, 1.0f/pa_mass);
1251
1252         VECCOPY(dvec, acc);
1253         mul_v3_fl(dvec, dtime*dtime*0.5f);
1254         
1255         VECCOPY(bvec, pa->prev_state.vel);
1256         mul_v3_fl(bvec, dtime);
1257         add_v3_v3(dvec, bvec);
1258         add_v3_v3(pa->state.co, dvec);
1259
1260         VECADDFAC(pa->state.vel, pa->state.vel, acc, dtime);
1261
1262         //if(bpa->data.mode != eBoidMode_InAir)
1263         bpa->ground = boid_find_ground(bbd, pa, ground_co, ground_nor);
1264
1265         /* change modes, constrain movement & keep track of down vector */
1266         switch(bpa->data.mode) {
1267                 case eBoidMode_InAir:
1268                 {
1269                         float grav[3];
1270
1271                         grav[0]= 0.0f;
1272                         grav[1]= 0.0f;
1273                         grav[2]= bbd->sim->scene->physics_settings.gravity[2] < 0.0f ? -1.0f : 0.0f;
1274
1275                         /* don't take forward acceleration into account (better banking) */
1276                         if(dot_v3v3(bpa->data.acc, pa->state.vel) > 0.0f) {
1277                                 project_v3_v3v3(dvec, bpa->data.acc, pa->state.vel);
1278                                 sub_v3_v3v3(dvec, bpa->data.acc, dvec);
1279                         }
1280                         else {
1281                                 VECCOPY(dvec, bpa->data.acc);
1282                         }
1283
1284                         /* gather apparent gravity */
1285                         VECADDFAC(bpa->gravity, grav, dvec, -boids->banking);
1286                         normalize_v3(bpa->gravity);
1287
1288                         /* stick boid on goal when close enough */
1289                         if(bbd->goal_ob && boid_goal_signed_dist(pa->state.co, bbd->goal_co, bbd->goal_nor) <= pa->size * boids->height) {
1290                                 bpa->data.mode = eBoidMode_Climbing;
1291                                 bpa->ground = bbd->goal_ob;
1292                                 boid_find_ground(bbd, pa, ground_co, ground_nor);
1293                                 boid_climb(boids, pa, ground_co, ground_nor);
1294                         }
1295                         else if(pa->state.co[2] <= ground_co[2] + pa->size * boids->height) {
1296                                 /* land boid when below ground */
1297                                 if(boids->options & BOID_ALLOW_LAND) {
1298                                         pa->state.co[2] = ground_co[2] + pa->size * boids->height;
1299                                         pa->state.vel[2] = 0.0f;
1300                                         bpa->data.mode = eBoidMode_OnLand;
1301                                 }
1302                                 /* fly above ground */
1303                                 else if(bpa->ground) {
1304                                         pa->state.co[2] = ground_co[2] + pa->size * boids->height;
1305                                         pa->state.vel[2] = 0.0f;
1306                                 }
1307                         }
1308                         break;
1309                 }
1310                 case eBoidMode_Falling:
1311                 {
1312                         float grav[3];
1313
1314                         grav[0]= 0.0f;
1315                         grav[1]= 0.0f;
1316                         grav[2]= bbd->sim->scene->physics_settings.gravity[2] < 0.0f ? -1.0f : 0.0f;
1317
1318
1319                         /* gather apparent gravity */
1320                         VECADDFAC(bpa->gravity, bpa->gravity, grav, dtime);
1321                         normalize_v3(bpa->gravity);
1322
1323                         if(boids->options & BOID_ALLOW_LAND) {
1324                                 /* stick boid on goal when close enough */
1325                                 if(bbd->goal_ob && boid_goal_signed_dist(pa->state.co, bbd->goal_co, bbd->goal_nor) <= pa->size * boids->height) {
1326                                         bpa->data.mode = eBoidMode_Climbing;
1327                                         bpa->ground = bbd->goal_ob;
1328                                         boid_find_ground(bbd, pa, ground_co, ground_nor);
1329                                         boid_climb(boids, pa, ground_co, ground_nor);
1330                                 }
1331                                 /* land boid when really near ground */
1332                                 else if(pa->state.co[2] <= ground_co[2] + 1.01f * pa->size * boids->height){
1333                                         pa->state.co[2] = ground_co[2] + pa->size * boids->height;
1334                                         pa->state.vel[2] = 0.0f;
1335                                         bpa->data.mode = eBoidMode_OnLand;
1336                                 }
1337                                 /* if we're falling, can fly and want to go upwards lets fly */
1338                                 else if(boids->options & BOID_ALLOW_FLIGHT && bbd->wanted_co[2] > 0.0f)
1339                                         bpa->data.mode = eBoidMode_InAir;
1340                         }
1341                         else
1342                                 bpa->data.mode = eBoidMode_InAir;
1343                         break;
1344                 }
1345                 case eBoidMode_Climbing:
1346                 {
1347                         boid_climb(boids, pa, ground_co, ground_nor);
1348                         //float nor[3];
1349                         //copy_v3_v3(nor, ground_nor);
1350
1351                         ///* gather apparent gravity to r_ve */
1352                         //VECADDFAC(pa->r_ve, pa->r_ve, ground_nor, -1.0);
1353                         //normalize_v3(pa->r_ve);
1354
1355                         ///* raise boid it's size from surface */
1356                         //mul_v3_fl(nor, pa->size * boids->height);
1357                         //add_v3_v3v3(pa->state.co, ground_co, nor);
1358
1359                         ///* remove normal component from velocity */
1360                         //project_v3_v3v3(v, pa->state.vel, ground_nor);
1361                         //sub_v3_v3v3(pa->state.vel, pa->state.vel, v);
1362                         break;
1363                 }
1364                 case eBoidMode_OnLand:
1365                 {
1366                         /* stick boid on goal when close enough */
1367                         if(bbd->goal_ob && boid_goal_signed_dist(pa->state.co, bbd->goal_co, bbd->goal_nor) <= pa->size * boids->height) {
1368                                 bpa->data.mode = eBoidMode_Climbing;
1369                                 bpa->ground = bbd->goal_ob;
1370                                 boid_find_ground(bbd, pa, ground_co, ground_nor);
1371                                 boid_climb(boids, pa, ground_co, ground_nor);
1372                         }
1373                         /* ground is too far away so boid falls */
1374                         else if(pa->state.co[2]-ground_co[2] > 1.1f * pa->size * boids->height)
1375                                 bpa->data.mode = eBoidMode_Falling;
1376                         else {
1377                                 /* constrain to surface */
1378                                 pa->state.co[2] = ground_co[2] + pa->size * boids->height;
1379                                 pa->state.vel[2] = 0.0f;
1380                         }
1381
1382                         if(boids->banking > 0.0f) {
1383                                 float grav[3];
1384                                 /* Don't take gravity's strength in to account, */
1385                                 /* otherwise amount of banking is hard to control. */
1386                                 negate_v3_v3(grav, ground_nor);
1387
1388                                 project_v3_v3v3(dvec, bpa->data.acc, pa->state.vel);
1389                                 sub_v3_v3v3(dvec, bpa->data.acc, dvec);
1390
1391                                 /* gather apparent gravity */
1392                                 VECADDFAC(bpa->gravity, grav, dvec, -boids->banking);
1393                                 normalize_v3(bpa->gravity);
1394                         }
1395                         else {
1396                                 /* gather negative surface normal */
1397                                 VECADDFAC(bpa->gravity, bpa->gravity, ground_nor, -1.0f);
1398                                 normalize_v3(bpa->gravity);
1399                         }
1400                         break;
1401                 }
1402         }
1403
1404         /* save direction to state.ave unless the boid is falling */
1405         /* (boids can't effect their direction when falling) */
1406         if(bpa->data.mode!=eBoidMode_Falling && len_v3(pa->state.vel) > 0.1f*pa->size) {
1407                 copy_v3_v3(pa->state.ave, pa->state.vel);
1408                 pa->state.ave[2] *= bbd->part->boids->pitch;
1409                 normalize_v3(pa->state.ave);
1410         }
1411
1412         /* apply damping */
1413         if(ELEM(bpa->data.mode, eBoidMode_OnLand, eBoidMode_Climbing))
1414                 mul_v3_fl(pa->state.vel, 1.0f - 0.2f*bbd->part->dampfac);
1415
1416         /* calculate rotation matrix based on forward & down vectors */
1417         if(bpa->data.mode == eBoidMode_InAir) {
1418                 VECCOPY(mat[0], pa->state.ave);
1419
1420                 project_v3_v3v3(dvec, bpa->gravity, pa->state.ave);
1421                 sub_v3_v3v3(mat[2], bpa->gravity, dvec);
1422                 normalize_v3(mat[2]);
1423         }
1424         else {
1425                 project_v3_v3v3(dvec, pa->state.ave, bpa->gravity);
1426                 sub_v3_v3v3(mat[0], pa->state.ave, dvec);
1427                 normalize_v3(mat[0]);
1428
1429                 VECCOPY(mat[2], bpa->gravity);
1430         }
1431         negate_v3(mat[2]);
1432         cross_v3_v3v3(mat[1], mat[2], mat[0]);
1433         
1434         /* apply rotation */
1435         mat3_to_quat_is_ok( q,mat);
1436         copy_qt_qt(pa->state.rot, q);
1437 }
1438
1439 BoidRule *boid_new_rule(int type)
1440 {
1441         BoidRule *rule = NULL;
1442         if(type <= 0)
1443                 return NULL;
1444
1445         switch(type) {
1446                 case eBoidRuleType_Goal:
1447                 case eBoidRuleType_Avoid:
1448                         rule = MEM_callocN(sizeof(BoidRuleGoalAvoid), "BoidRuleGoalAvoid");
1449                         break;
1450                 case eBoidRuleType_AvoidCollision:
1451                         rule = MEM_callocN(sizeof(BoidRuleAvoidCollision), "BoidRuleAvoidCollision");
1452                         ((BoidRuleAvoidCollision*)rule)->look_ahead = 2.0f;
1453                         break;
1454                 case eBoidRuleType_FollowLeader:
1455                         rule = MEM_callocN(sizeof(BoidRuleFollowLeader), "BoidRuleFollowLeader");
1456                         ((BoidRuleFollowLeader*)rule)->distance = 1.0f;
1457                         break;
1458                 case eBoidRuleType_AverageSpeed:
1459                         rule = MEM_callocN(sizeof(BoidRuleAverageSpeed), "BoidRuleAverageSpeed");
1460                         ((BoidRuleAverageSpeed*)rule)->speed = 0.5f;
1461                         break;
1462                 case eBoidRuleType_Fight:
1463                         rule = MEM_callocN(sizeof(BoidRuleFight), "BoidRuleFight");
1464                         ((BoidRuleFight*)rule)->distance = 100.0f;
1465                         ((BoidRuleFight*)rule)->flee_distance = 100.0f;
1466                         break;
1467                 default:
1468                         rule = MEM_callocN(sizeof(BoidRule), "BoidRule");
1469                         break;
1470         }
1471
1472         rule->type = type;
1473         rule->flag |= BOIDRULE_IN_AIR|BOIDRULE_ON_LAND;
1474         BLI_strncpy(rule->name, boidrule_type_items[type-1].name, sizeof(rule->name));
1475
1476         return rule;
1477 }
1478 void boid_default_settings(BoidSettings *boids)
1479 {
1480         boids->air_max_speed = 10.0f;
1481         boids->air_max_acc = 0.5f;
1482         boids->air_max_ave = 0.5f;
1483         boids->air_personal_space = 1.0f;
1484
1485         boids->land_max_speed = 5.0f;
1486         boids->land_max_acc = 0.5f;
1487         boids->land_max_ave = 0.5f;
1488         boids->land_personal_space = 1.0f;
1489
1490         boids->options = BOID_ALLOW_FLIGHT;
1491
1492         boids->landing_smoothness = 3.0f;
1493         boids->banking = 1.0f;
1494         boids->pitch = 1.0f;
1495         boids->height = 1.0f;
1496
1497         boids->health = 1.0f;
1498         boids->accuracy = 1.0f;
1499         boids->aggression = 2.0f;
1500         boids->range = 1.0f;
1501         boids->strength = 0.1f;
1502 }
1503
1504 BoidState *boid_new_state(BoidSettings *boids)
1505 {
1506         BoidState *state = MEM_callocN(sizeof(BoidState), "BoidState");
1507
1508         state->id = boids->last_state_id++;
1509         if(state->id)
1510                 sprintf(state->name, "State %i", state->id);
1511         else
1512                 strcpy(state->name, "State");
1513
1514         state->rule_fuzziness = 0.5;
1515         state->volume = 1.0f;
1516         state->channels |= ~0;
1517
1518         return state;
1519 }
1520
1521 BoidState *boid_duplicate_state(BoidSettings *boids, BoidState *state) {
1522         BoidState *staten = MEM_dupallocN(state);
1523
1524         BLI_duplicatelist(&staten->rules, &state->rules);
1525         BLI_duplicatelist(&staten->conditions, &state->conditions);
1526         BLI_duplicatelist(&staten->actions, &state->actions);
1527
1528         staten->id = boids->last_state_id++;
1529
1530         return staten;
1531 }
1532 void boid_free_settings(BoidSettings *boids)
1533 {
1534         if(boids) {
1535                 BoidState *state = boids->states.first;
1536
1537                 for(; state; state=state->next) {
1538                         BLI_freelistN(&state->rules);
1539                         BLI_freelistN(&state->conditions);
1540                         BLI_freelistN(&state->actions);
1541                 }
1542
1543                 BLI_freelistN(&boids->states);
1544
1545                 MEM_freeN(boids);
1546         }
1547 }
1548 BoidSettings *boid_copy_settings(BoidSettings *boids)
1549 {
1550         BoidSettings *nboids = NULL;
1551
1552         if(boids) {
1553                 BoidState *state;
1554                 BoidState *nstate;
1555
1556                 nboids = MEM_dupallocN(boids);
1557
1558                 BLI_duplicatelist(&nboids->states, &boids->states);
1559
1560                 state = boids->states.first;
1561                 nstate = nboids->states.first;
1562                 for(; state; state=state->next, nstate=nstate->next) {
1563                         BLI_duplicatelist(&nstate->rules, &state->rules);
1564                         BLI_duplicatelist(&nstate->conditions, &state->conditions);
1565                         BLI_duplicatelist(&nstate->actions, &state->actions);
1566                 }
1567         }
1568
1569         return nboids;
1570 }
1571 BoidState *boid_get_current_state(BoidSettings *boids)
1572 {
1573         BoidState *state = boids->states.first;
1574
1575         for(; state; state=state->next) {
1576                 if(state->flag & BOIDSTATE_CURRENT)
1577                         break;
1578         }
1579
1580         return state;
1581 }
1582