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