sim: Remove "continue physics" code
[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                 }
107                 else if (pd->forcefield == PFIELD_BOID && mul * pd->f_strength > 0.0f && get_effector_data(cur, &cur_efd, &epoint, 0)) {
108                         float temp = mul * pd->f_strength * effector_falloff(cur, &cur_efd, &epoint, bbd->part->effector_weights);
109
110                         if (temp == 0.0f) {
111                                 /* do nothing */
112                         }
113                         else if (temp > priority) {
114                                 priority = temp;
115                                 eff = cur;
116                                 efd = cur_efd;
117                                 len = efd.distance;
118                         }
119                         /* choose closest object with same priority */
120                         else if (temp == priority && efd.distance < len) {
121                                 eff = cur;
122                                 efd = cur_efd;
123                                 len = efd.distance;
124                         }
125                 }
126         }
127
128         /* if the object doesn't have effector data we have to fake it */
129         if (eff == NULL && gabr->ob) {
130                 memset(&temp_eff, 0, sizeof(EffectorCache));
131                 temp_eff.ob = gabr->ob;
132                 temp_eff.scene = bbd->sim->scene;
133                 eff = &temp_eff;
134                 get_effector_data(eff, &efd, &epoint, 0);
135                 priority = 1.0f;
136         }
137
138         /* then use that effector */
139         if (priority > (rule->type==eBoidRuleType_Avoid ? gabr->fear_factor : 0.0f)) { /* with avoid, factor is "fear factor" */
140                 Object *eob = eff->ob;
141                 PartDeflect *pd = eff->pd;
142                 float surface = (pd && pd->shape == PFIELD_SHAPE_SURFACE) ? 1.0f : 0.0f;
143
144                 if (gabr->options & BRULE_GOAL_AVOID_PREDICT) {
145                         /* estimate future location of target */
146                         get_effector_data(eff, &efd, &epoint, 1);
147
148                         mul_v3_fl(efd.vel, efd.distance / (val->max_speed * bbd->timestep));
149                         add_v3_v3(efd.loc, efd.vel);
150                         sub_v3_v3v3(efd.vec_to_point, pa->prev_state.co, efd.loc);
151                         efd.distance = len_v3(efd.vec_to_point);
152                 }
153
154                 if (rule->type == eBoidRuleType_Goal && boids->options & BOID_ALLOW_CLIMB && surface!=0.0f) {
155                         if (!bbd->goal_ob || bbd->goal_priority < priority) {
156                                 bbd->goal_ob = eob;
157                                 copy_v3_v3(bbd->goal_co, efd.loc);
158                                 copy_v3_v3(bbd->goal_nor, efd.nor);
159                         }
160                 }
161                 else if (rule->type == eBoidRuleType_Avoid && bpa->data.mode == eBoidMode_Climbing &&
162                         priority > 2.0f * gabr->fear_factor) {
163                         /* detach from surface and try to fly away from danger */
164                         negate_v3_v3(efd.vec_to_point, bpa->gravity);
165                 }
166
167                 copy_v3_v3(bbd->wanted_co, efd.vec_to_point);
168                 mul_v3_fl(bbd->wanted_co, mul);
169
170                 bbd->wanted_speed = val->max_speed * priority;
171
172                 /* with goals factor is approach velocity factor */
173                 if (rule->type == eBoidRuleType_Goal && boids->landing_smoothness > 0.0f) {
174                         float len2 = 2.0f*len_v3(pa->prev_state.vel);
175
176                         surface *= pa->size * boids->height;
177
178                         if (len2 > 0.0f && efd.distance - surface < len2) {
179                                 len2 = (efd.distance - surface)/len2;
180                                 bbd->wanted_speed *= powf(len2, boids->landing_smoothness);
181                         }
182                 }
183
184                 ret = 1;
185         }
186
187         return ret;
188 }
189
190 static int rule_avoid_collision(BoidRule *rule, BoidBrainData *bbd, BoidValues *val, ParticleData *pa)
191 {
192         BoidRuleAvoidCollision *acbr = (BoidRuleAvoidCollision*) rule;
193         KDTreeNearest *ptn = NULL;
194         ParticleTarget *pt;
195         BoidParticle *bpa = pa->boid;
196         ColliderCache *coll;
197         float vec[3] = {0.0f, 0.0f, 0.0f}, loc[3] = {0.0f, 0.0f, 0.0f};
198         float co1[3], vel1[3], co2[3], vel2[3];
199         float  len, t, inp, t_min = 2.0f;
200         int n, neighbors = 0, nearest = 0;
201         int ret = 0;
202
203         //check deflector objects first
204         if (acbr->options & BRULE_ACOLL_WITH_DEFLECTORS && bbd->sim->colliders) {
205                 ParticleCollision col;
206                 BVHTreeRayHit hit;
207                 float radius = val->personal_space * pa->size, ray_dir[3];
208
209                 copy_v3_v3(col.co1, pa->prev_state.co);
210                 add_v3_v3v3(col.co2, pa->prev_state.co, pa->prev_state.vel);
211                 sub_v3_v3v3(ray_dir, col.co2, col.co1);
212                 mul_v3_fl(ray_dir, acbr->look_ahead);
213                 col.f = 0.0f;
214                 hit.index = -1;
215                 hit.dist = col.original_ray_length = len_v3(ray_dir);
216
217                 /* find out closest deflector object */
218                 for (coll = bbd->sim->colliders->first; coll; coll=coll->next) {
219                         /* don't check with current ground object */
220                         if (coll->ob == bpa->ground)
221                                 continue;
222
223                         col.current = coll->ob;
224                         col.md = coll->collmd;
225
226                         if (col.md && col.md->bvhtree)
227                                 BLI_bvhtree_ray_cast(col.md->bvhtree, col.co1, ray_dir, radius, &hit, BKE_psys_collision_neartest_cb, &col);
228                 }
229                 /* then avoid that object */
230                 if (hit.index>=0) {
231                         t = hit.dist/col.original_ray_length;
232
233                         /* avoid head-on collision */
234                         if (dot_v3v3(col.pce.nor, pa->prev_state.ave) < -0.99f) {
235                                 /* don't know why, but uneven range [0.0, 1.0] */
236                                 /* works much better than even [-1.0, 1.0] */
237                                 bbd->wanted_co[0] = BLI_frand();
238                                 bbd->wanted_co[1] = BLI_frand();
239                                 bbd->wanted_co[2] = BLI_frand();
240                         }
241                         else {
242                                 copy_v3_v3(bbd->wanted_co, col.pce.nor);
243                         }
244
245                         mul_v3_fl(bbd->wanted_co, (1.0f - t) * val->personal_space * pa->size);
246
247                         bbd->wanted_speed = sqrtf(t) * len_v3(pa->prev_state.vel);
248                         bbd->wanted_speed = MAX2(bbd->wanted_speed, val->min_speed);
249
250                         return 1;
251                 }
252         }
253
254         //check boids in own system
255         if (acbr->options & BRULE_ACOLL_WITH_BOIDS) {
256                 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);
257                 if (neighbors > 1) for (n=1; n<neighbors; n++) {
258                         copy_v3_v3(co1, pa->prev_state.co);
259                         copy_v3_v3(vel1, pa->prev_state.vel);
260                         copy_v3_v3(co2, (bbd->sim->psys->particles + ptn[n].index)->prev_state.co);
261                         copy_v3_v3(vel2, (bbd->sim->psys->particles + ptn[n].index)->prev_state.vel);
262
263                         sub_v3_v3v3(loc, co1, co2);
264
265                         sub_v3_v3v3(vec, vel1, vel2);
266                         
267                         inp = dot_v3v3(vec, vec);
268
269                         /* velocities not parallel */
270                         if (inp != 0.0f) {
271                                 t = -dot_v3v3(loc, vec)/inp;
272                                 /* cpa is not too far in the future so investigate further */
273                                 if (t > 0.0f && t < t_min) {
274                                         madd_v3_v3fl(co1, vel1, t);
275                                         madd_v3_v3fl(co2, vel2, t);
276                                         
277                                         sub_v3_v3v3(vec, co2, co1);
278
279                                         len = normalize_v3(vec);
280
281                                         /* distance of cpa is close enough */
282                                         if (len < 2.0f * val->personal_space * pa->size) {
283                                                 t_min = t;
284
285                                                 mul_v3_fl(vec, len_v3(vel1));
286                                                 mul_v3_fl(vec, (2.0f - t)/2.0f);
287                                                 sub_v3_v3v3(bbd->wanted_co, vel1, vec);
288                                                 bbd->wanted_speed = len_v3(bbd->wanted_co);
289                                                 ret = 1;
290                                         }
291                                 }
292                         }
293                 }
294         }
295         if (ptn) { MEM_freeN(ptn); ptn=NULL; }
296
297         /* check boids in other systems */
298         for (pt=bbd->sim->psys->targets.first; pt; pt=pt->next) {
299                 ParticleSystem *epsys = psys_get_target_system(bbd->sim->ob, pt);
300
301                 if (epsys) {
302                         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);
303                         if (neighbors > 0) for (n=0; n<neighbors; n++) {
304                                 copy_v3_v3(co1, pa->prev_state.co);
305                                 copy_v3_v3(vel1, pa->prev_state.vel);
306                                 copy_v3_v3(co2, (epsys->particles + ptn[n].index)->prev_state.co);
307                                 copy_v3_v3(vel2, (epsys->particles + ptn[n].index)->prev_state.vel);
308
309                                 sub_v3_v3v3(loc, co1, co2);
310
311                                 sub_v3_v3v3(vec, vel1, vel2);
312                                 
313                                 inp = dot_v3v3(vec, vec);
314
315                                 /* velocities not parallel */
316                                 if (inp != 0.0f) {
317                                         t = -dot_v3v3(loc, vec)/inp;
318                                         /* cpa is not too far in the future so investigate further */
319                                         if (t > 0.0f && t < t_min) {
320                                                 madd_v3_v3fl(co1, vel1, t);
321                                                 madd_v3_v3fl(co2, vel2, t);
322                                                 
323                                                 sub_v3_v3v3(vec, co2, co1);
324
325                                                 len = normalize_v3(vec);
326
327                                                 /* distance of cpa is close enough */
328                                                 if (len < 2.0f * val->personal_space * pa->size) {
329                                                         t_min = t;
330
331                                                         mul_v3_fl(vec, len_v3(vel1));
332                                                         mul_v3_fl(vec, (2.0f - t)/2.0f);
333                                                         sub_v3_v3v3(bbd->wanted_co, vel1, vec);
334                                                         bbd->wanted_speed = len_v3(bbd->wanted_co);
335                                                         ret = 1;
336                                                 }
337                                         }
338                                 }
339                         }
340
341                         if (ptn) { MEM_freeN(ptn); ptn=NULL; }
342                 }
343         }
344
345
346         if (ptn && nearest==0)
347                 MEM_freeN(ptn);
348
349         return ret;
350 }
351 static int rule_separate(BoidRule *UNUSED(rule), BoidBrainData *bbd, BoidValues *val, ParticleData *pa)
352 {
353         KDTreeNearest *ptn = NULL;
354         ParticleTarget *pt;
355         float len = 2.0f * val->personal_space * pa->size + 1.0f;
356         float vec[3] = {0.0f, 0.0f, 0.0f};
357         int neighbors = BLI_kdtree_range_search(bbd->sim->psys->tree, 2.0f * val->personal_space * pa->size, pa->prev_state.co, NULL, &ptn);
358         int ret = 0;
359
360         if (neighbors > 1 && ptn[1].dist!=0.0f) {
361                 sub_v3_v3v3(vec, pa->prev_state.co, bbd->sim->psys->particles[ptn[1].index].state.co);
362                 mul_v3_fl(vec, (2.0f * val->personal_space * pa->size - ptn[1].dist) / ptn[1].dist);
363                 add_v3_v3(bbd->wanted_co, vec);
364                 bbd->wanted_speed = val->max_speed;
365                 len = ptn[1].dist;
366                 ret = 1;
367         }
368         if (ptn) { MEM_freeN(ptn); ptn=NULL; }
369
370         /* check other boid systems */
371         for (pt=bbd->sim->psys->targets.first; pt; pt=pt->next) {
372                 ParticleSystem *epsys = psys_get_target_system(bbd->sim->ob, pt);
373
374                 if (epsys) {
375                         neighbors = BLI_kdtree_range_search(epsys->tree, 2.0f * val->personal_space * pa->size, pa->prev_state.co, NULL, &ptn);
376                         
377                         if (neighbors > 0 && ptn[0].dist < len) {
378                                 sub_v3_v3v3(vec, pa->prev_state.co, ptn[0].co);
379                                 mul_v3_fl(vec, (2.0f * val->personal_space * pa->size - ptn[0].dist) / ptn[1].dist);
380                                 add_v3_v3(bbd->wanted_co, vec);
381                                 bbd->wanted_speed = val->max_speed;
382                                 len = ptn[0].dist;
383                                 ret = 1;
384                         }
385
386                         if (ptn) { MEM_freeN(ptn); ptn=NULL; }
387                 }
388         }
389         return ret;
390 }
391 static int rule_flock(BoidRule *UNUSED(rule), BoidBrainData *bbd, BoidValues *UNUSED(val), ParticleData *pa)
392 {
393         KDTreeNearest ptn[11];
394         float vec[3] = {0.0f, 0.0f, 0.0f}, loc[3] = {0.0f, 0.0f, 0.0f};
395         int neighbors = BLI_kdtree_find_n_nearest(bbd->sim->psys->tree, 11, pa->state.co, pa->prev_state.ave, ptn);
396         int n;
397         int ret = 0;
398
399         if (neighbors > 1) {
400                 for (n=1; n<neighbors; n++) {
401                         add_v3_v3(loc, bbd->sim->psys->particles[ptn[n].index].prev_state.co);
402                         add_v3_v3(vec, bbd->sim->psys->particles[ptn[n].index].prev_state.vel);
403                 }
404
405                 mul_v3_fl(loc, 1.0f/((float)neighbors - 1.0f));
406                 mul_v3_fl(vec, 1.0f/((float)neighbors - 1.0f));
407
408                 sub_v3_v3(loc, pa->prev_state.co);
409                 sub_v3_v3(vec, pa->prev_state.vel);
410
411                 add_v3_v3(bbd->wanted_co, vec);
412                 add_v3_v3(bbd->wanted_co, loc);
413                 bbd->wanted_speed = len_v3(bbd->wanted_co);
414
415                 ret = 1;
416         }
417         return ret;
418 }
419 static int rule_follow_leader(BoidRule *rule, BoidBrainData *bbd, BoidValues *val, ParticleData *pa)
420 {
421         BoidRuleFollowLeader *flbr = (BoidRuleFollowLeader*) rule;
422         float vec[3] = {0.0f, 0.0f, 0.0f}, loc[3] = {0.0f, 0.0f, 0.0f};
423         float mul, len;
424         int n = (flbr->queue_size <= 1) ? bbd->sim->psys->totpart : flbr->queue_size;
425         int i, ret = 0, p = pa - bbd->sim->psys->particles;
426
427         if (flbr->ob) {
428                 float vec2[3], t;
429
430                 /* first check we're not blocking the leader */
431                 sub_v3_v3v3(vec, flbr->loc, flbr->oloc);
432                 mul_v3_fl(vec, 1.0f/bbd->timestep);
433
434                 sub_v3_v3v3(loc, pa->prev_state.co, flbr->oloc);
435
436                 mul = dot_v3v3(vec, vec);
437
438                 /* leader is not moving */
439                 if (mul < 0.01f) {
440                         len = len_v3(loc);
441                         /* too close to leader */
442                         if (len < 2.0f * val->personal_space * pa->size) {
443                                 copy_v3_v3(bbd->wanted_co, loc);
444                                 bbd->wanted_speed = val->max_speed;
445                                 return 1;
446                         }
447                 }
448                 else {
449                         t = dot_v3v3(loc, vec)/mul;
450
451                         /* possible blocking of leader in near future */
452                         if (t > 0.0f && t < 3.0f) {
453                                 copy_v3_v3(vec2, vec);
454                                 mul_v3_fl(vec2, t);
455
456                                 sub_v3_v3v3(vec2, loc, vec2);
457
458                                 len = len_v3(vec2);
459
460                                 if (len < 2.0f * val->personal_space * pa->size) {
461                                         copy_v3_v3(bbd->wanted_co, vec2);
462                                         bbd->wanted_speed = val->max_speed * (3.0f - t)/3.0f;
463                                         return 1;
464                                 }
465                         }
466                 }
467
468                 /* not blocking so try to follow leader */
469                 if (p && flbr->options & BRULE_LEADER_IN_LINE) {
470                         copy_v3_v3(vec, bbd->sim->psys->particles[p-1].prev_state.vel);
471                         copy_v3_v3(loc, bbd->sim->psys->particles[p-1].prev_state.co);
472                 }
473                 else {
474                         copy_v3_v3(loc, flbr->oloc);
475                         sub_v3_v3v3(vec, flbr->loc, flbr->oloc);
476                         mul_v3_fl(vec, 1.0f/bbd->timestep);
477                 }
478                 
479                 /* fac is seconds behind leader */
480                 madd_v3_v3fl(loc, vec, -flbr->distance);
481
482                 sub_v3_v3v3(bbd->wanted_co, loc, pa->prev_state.co);
483                 bbd->wanted_speed = len_v3(bbd->wanted_co);
484                         
485                 ret = 1;
486         }
487         else if (p % n) {
488                 float vec2[3], t, t_min = 3.0f;
489
490                 /* first check we're not blocking any leaders */
491                 for (i = 0; i< bbd->sim->psys->totpart; i+=n) {
492                         copy_v3_v3(vec, bbd->sim->psys->particles[i].prev_state.vel);
493
494                         sub_v3_v3v3(loc, pa->prev_state.co, bbd->sim->psys->particles[i].prev_state.co);
495
496                         mul = dot_v3v3(vec, vec);
497
498                         /* leader is not moving */
499                         if (mul < 0.01f) {
500                                 len = len_v3(loc);
501                                 /* too close to leader */
502                                 if (len < 2.0f * val->personal_space * pa->size) {
503                                         copy_v3_v3(bbd->wanted_co, loc);
504                                         bbd->wanted_speed = val->max_speed;
505                                         return 1;
506                                 }
507                         }
508                         else {
509                                 t = dot_v3v3(loc, vec)/mul;
510
511                                 /* possible blocking of leader in near future */
512                                 if (t > 0.0f && t < t_min) {
513                                         copy_v3_v3(vec2, vec);
514                                         mul_v3_fl(vec2, t);
515
516                                         sub_v3_v3v3(vec2, loc, vec2);
517
518                                         len = len_v3(vec2);
519
520                                         if (len < 2.0f * val->personal_space * pa->size) {
521                                                 t_min = t;
522                                                 copy_v3_v3(bbd->wanted_co, loc);
523                                                 bbd->wanted_speed = val->max_speed * (3.0f - t)/3.0f;
524                                                 ret = 1;
525                                         }
526                                 }
527                         }
528                 }
529
530                 if (ret) return 1;
531
532                 /* not blocking so try to follow leader */
533                 if (flbr->options & BRULE_LEADER_IN_LINE) {
534                         copy_v3_v3(vec, bbd->sim->psys->particles[p-1].prev_state.vel);
535                         copy_v3_v3(loc, bbd->sim->psys->particles[p-1].prev_state.co);
536                 }
537                 else {
538                         copy_v3_v3(vec, bbd->sim->psys->particles[p - p%n].prev_state.vel);
539                         copy_v3_v3(loc, bbd->sim->psys->particles[p - p%n].prev_state.co);
540                 }
541                 
542                 /* fac is seconds behind leader */
543                 madd_v3_v3fl(loc, vec, -flbr->distance);
544
545                 sub_v3_v3v3(bbd->wanted_co, loc, pa->prev_state.co);
546                 bbd->wanted_speed = len_v3(bbd->wanted_co);
547                 
548                 ret = 1;
549         }
550
551         return ret;
552 }
553 static int rule_average_speed(BoidRule *rule, BoidBrainData *bbd, BoidValues *val, ParticleData *pa)
554 {
555         BoidParticle *bpa = pa->boid;
556         BoidRuleAverageSpeed *asbr = (BoidRuleAverageSpeed*)rule;
557         float vec[3] = {0.0f, 0.0f, 0.0f};
558
559         if (asbr->wander > 0.0f) {
560                 /* abuse pa->r_ave for wandering */
561                 bpa->wander[0] += asbr->wander * (-1.0f + 2.0f * BLI_frand());
562                 bpa->wander[1] += asbr->wander * (-1.0f + 2.0f * BLI_frand());
563                 bpa->wander[2] += asbr->wander * (-1.0f + 2.0f * BLI_frand());
564
565                 normalize_v3(bpa->wander);
566
567                 copy_v3_v3(vec, bpa->wander);
568
569                 mul_qt_v3(pa->prev_state.rot, vec);
570
571                 copy_v3_v3(bbd->wanted_co, pa->prev_state.ave);
572
573                 mul_v3_fl(bbd->wanted_co, 1.1f);
574
575                 add_v3_v3(bbd->wanted_co, vec);
576
577                 /* leveling */
578                 if (asbr->level > 0.0f && psys_uses_gravity(bbd->sim)) {
579                         project_v3_v3v3(vec, bbd->wanted_co, bbd->sim->scene->physics_settings.gravity);
580                         mul_v3_fl(vec, asbr->level);
581                         sub_v3_v3(bbd->wanted_co, vec);
582                 }
583         }
584         else {
585                 copy_v3_v3(bbd->wanted_co, pa->prev_state.ave);
586
587                 /* may happen at birth */
588                 if (dot_v2v2(bbd->wanted_co, bbd->wanted_co)==0.0f) {
589                         bbd->wanted_co[0] = 2.0f*(0.5f - BLI_frand());
590                         bbd->wanted_co[1] = 2.0f*(0.5f - BLI_frand());
591                         bbd->wanted_co[2] = 2.0f*(0.5f - BLI_frand());
592                 }
593                 
594                 /* leveling */
595                 if (asbr->level > 0.0f && psys_uses_gravity(bbd->sim)) {
596                         project_v3_v3v3(vec, bbd->wanted_co, bbd->sim->scene->physics_settings.gravity);
597                         mul_v3_fl(vec, asbr->level);
598                         sub_v3_v3(bbd->wanted_co, vec);
599                 }
600
601         }
602         bbd->wanted_speed = asbr->speed * val->max_speed;
603         
604         return 1;
605 }
606 static int rule_fight(BoidRule *rule, BoidBrainData *bbd, BoidValues *val, ParticleData *pa)
607 {
608         BoidRuleFight *fbr = (BoidRuleFight*)rule;
609         KDTreeNearest *ptn = NULL;
610         ParticleTarget *pt;
611         ParticleData *epars;
612         ParticleData *enemy_pa = NULL;
613         BoidParticle *bpa;
614         /* friends & enemies */
615         float closest_enemy[3] = {0.0f, 0.0f, 0.0f};
616         float closest_dist = fbr->distance + 1.0f;
617         float f_strength = 0.0f, e_strength = 0.0f;
618         float health = 0.0f;
619         int n, ret = 0;
620
621         /* calculate own group strength */
622         int neighbors = BLI_kdtree_range_search(bbd->sim->psys->tree, fbr->distance, pa->prev_state.co, NULL, &ptn);
623         for (n=0; n<neighbors; n++) {
624                 bpa = bbd->sim->psys->particles[ptn[n].index].boid;
625                 health += bpa->data.health;
626         }
627
628         f_strength += bbd->part->boids->strength * health;
629
630         if (ptn) { MEM_freeN(ptn); ptn=NULL; }
631
632         /* add other friendlies and calculate enemy strength and find closest enemy */
633         for (pt=bbd->sim->psys->targets.first; pt; pt=pt->next) {
634                 ParticleSystem *epsys = psys_get_target_system(bbd->sim->ob, pt);
635                 if (epsys) {
636                         epars = epsys->particles;
637
638                         neighbors = BLI_kdtree_range_search(epsys->tree, fbr->distance, pa->prev_state.co, NULL, &ptn);
639                         
640                         health = 0.0f;
641
642                         for (n=0; n<neighbors; n++) {
643                                 bpa = epars[ptn[n].index].boid;
644                                 health += bpa->data.health;
645
646                                 if (n==0 && pt->mode==PTARGET_MODE_ENEMY && ptn[n].dist < closest_dist) {
647                                         copy_v3_v3(closest_enemy, ptn[n].co);
648                                         closest_dist = ptn[n].dist;
649                                         enemy_pa = epars + ptn[n].index;
650                                 }
651                         }
652                         if (pt->mode==PTARGET_MODE_ENEMY)
653                                 e_strength += epsys->part->boids->strength * health;
654                         else if (pt->mode==PTARGET_MODE_FRIEND)
655                                 f_strength += epsys->part->boids->strength * health;
656
657                         if (ptn) { MEM_freeN(ptn); ptn=NULL; }
658                 }
659         }
660         /* decide action if enemy presence found */
661         if (e_strength > 0.0f) {
662                 sub_v3_v3v3(bbd->wanted_co, closest_enemy, pa->prev_state.co);
663
664                 /* attack if in range */
665                 if (closest_dist <= bbd->part->boids->range + pa->size + enemy_pa->size) {
666                         float damage = BLI_frand();
667                         float enemy_dir[3];
668
669                         normalize_v3_v3(enemy_dir, bbd->wanted_co);
670
671                         /* fight mode */
672                         bbd->wanted_speed = 0.0f;
673
674                         /* must face enemy to fight */
675                         if (dot_v3v3(pa->prev_state.ave, enemy_dir)>0.5f) {
676                                 bpa = enemy_pa->boid;
677                                 bpa->data.health -= bbd->part->boids->strength * bbd->timestep * ((1.0f-bbd->part->boids->accuracy)*damage + bbd->part->boids->accuracy);
678                         }
679                 }
680                 else {
681                         /* approach mode */
682                         bbd->wanted_speed = val->max_speed;
683                 }
684
685                 /* check if boid doesn't want to fight */
686                 bpa = pa->boid;
687                 if (bpa->data.health/bbd->part->boids->health * bbd->part->boids->aggression < e_strength / f_strength) {
688                         /* decide to flee */
689                         if (closest_dist < fbr->flee_distance * fbr->distance) {
690                                 negate_v3(bbd->wanted_co);
691                                 bbd->wanted_speed = val->max_speed;
692                         }
693                         else { /* wait for better odds */
694                                 bbd->wanted_speed = 0.0f;
695                         }
696                 }
697
698                 ret = 1;
699         }
700
701         return ret;
702 }
703
704 typedef int (*boid_rule_cb)(BoidRule *rule, BoidBrainData *data, BoidValues *val, ParticleData *pa);
705
706 static boid_rule_cb boid_rules[] = {
707         rule_none,
708         rule_goal_avoid,
709         rule_goal_avoid,
710         rule_avoid_collision,
711         rule_separate,
712         rule_flock,
713         rule_follow_leader,
714         rule_average_speed,
715         rule_fight,
716         //rule_help,
717         //rule_protect,
718         //rule_hide,
719         //rule_follow_path,
720         //rule_follow_wall
721 };
722
723 static void set_boid_values(BoidValues *val, BoidSettings *boids, ParticleData *pa)
724 {
725         BoidParticle *bpa = pa->boid;
726
727         if (ELEM(bpa->data.mode, eBoidMode_OnLand, eBoidMode_Climbing)) {
728                 val->max_speed = boids->land_max_speed * bpa->data.health/boids->health;
729                 val->max_acc = boids->land_max_acc * val->max_speed;
730                 val->max_ave = boids->land_max_ave * (float)M_PI * bpa->data.health/boids->health;
731                 val->min_speed = 0.0f; /* no minimum speed on land */
732                 val->personal_space = boids->land_personal_space;
733                 val->jump_speed = boids->land_jump_speed * bpa->data.health/boids->health;
734         }
735         else {
736                 val->max_speed = boids->air_max_speed * bpa->data.health/boids->health;
737                 val->max_acc = boids->air_max_acc * val->max_speed;
738                 val->max_ave = boids->air_max_ave * (float)M_PI * bpa->data.health/boids->health;
739                 val->min_speed = boids->air_min_speed * boids->air_max_speed;
740                 val->personal_space = boids->air_personal_space;
741                 val->jump_speed = 0.0f; /* no jumping in air */
742         }
743 }
744
745 static Object *boid_find_ground(BoidBrainData *bbd, ParticleData *pa, float ground_co[3], float ground_nor[3])
746 {
747         BoidParticle *bpa = pa->boid;
748
749         if (bpa->data.mode == eBoidMode_Climbing) {
750                 SurfaceModifierData *surmd = NULL;
751                 float x[3], v[3];
752                 
753                 surmd = (SurfaceModifierData *)modifiers_findByType(bpa->ground, eModifierType_Surface );
754
755                 /* take surface velocity into account */
756                 closest_point_on_surface(surmd, pa->state.co, x, NULL, v);
757                 add_v3_v3(x, v);
758
759                 /* get actual position on surface */
760                 closest_point_on_surface(surmd, x, ground_co, ground_nor, NULL);
761
762                 return bpa->ground;
763         }
764         else {
765                 float zvec[3] = {0.0f, 0.0f, 2000.0f};
766                 ParticleCollision col;
767                 ColliderCache *coll;
768                 BVHTreeRayHit hit;
769                 float radius = 0.0f, t, ray_dir[3];
770
771                 if (!bbd->sim->colliders)
772                         return NULL;
773
774                 /* first try to find below boid */
775                 copy_v3_v3(col.co1, pa->state.co);
776                 sub_v3_v3v3(col.co2, pa->state.co, zvec);
777                 sub_v3_v3v3(ray_dir, col.co2, col.co1);
778                 col.f = 0.0f;
779                 hit.index = -1;
780                 hit.dist = col.original_ray_length = len_v3(ray_dir);
781                 col.pce.inside = 0;
782
783                 for (coll = bbd->sim->colliders->first; coll; coll = coll->next) {
784                         col.current = coll->ob;
785                         col.md = coll->collmd;
786                         col.fac1 = col.fac2 = 0.f;
787
788                         if (col.md && col.md->bvhtree)
789                                 BLI_bvhtree_ray_cast(col.md->bvhtree, col.co1, ray_dir, radius, &hit, BKE_psys_collision_neartest_cb, &col);
790                 }
791                 /* then use that object */
792                 if (hit.index>=0) {
793                         t = hit.dist/col.original_ray_length;
794                         interp_v3_v3v3(ground_co, col.co1, col.co2, t);
795                         normalize_v3_v3(ground_nor, col.pce.nor);
796                         return col.hit;
797                 }
798
799                 /* couldn't find below, so find upmost deflector object */
800                 add_v3_v3v3(col.co1, pa->state.co, zvec);
801                 sub_v3_v3v3(col.co2, pa->state.co, zvec);
802                 sub_v3_v3(col.co2, zvec);
803                 sub_v3_v3v3(ray_dir, col.co2, col.co1);
804                 col.f = 0.0f;
805                 hit.index = -1;
806                 hit.dist = col.original_ray_length = len_v3(ray_dir);
807
808                 for (coll = bbd->sim->colliders->first; coll; coll = coll->next) {
809                         col.current = coll->ob;
810                         col.md = coll->collmd;
811
812                         if (col.md && col.md->bvhtree)
813                                 BLI_bvhtree_ray_cast(col.md->bvhtree, col.co1, ray_dir, radius, &hit, BKE_psys_collision_neartest_cb, &col);
814                 }
815                 /* then use that object */
816                 if (hit.index>=0) {
817                         t = hit.dist/col.original_ray_length;
818                         interp_v3_v3v3(ground_co, col.co1, col.co2, t);
819                         normalize_v3_v3(ground_nor, col.pce.nor);
820                         return col.hit;
821                 }
822
823                 /* default to z=0 */
824                 copy_v3_v3(ground_co, pa->state.co);
825                 ground_co[2] = 0;
826                 ground_nor[0] = ground_nor[1] = 0.0f;
827                 ground_nor[2] = 1.0f;
828                 return NULL;
829         }
830 }
831 static int boid_rule_applies(ParticleData *pa, BoidSettings *UNUSED(boids), BoidRule *rule)
832 {
833         BoidParticle *bpa = pa->boid;
834
835         if (rule==NULL)
836                 return 0;
837         
838         if (ELEM(bpa->data.mode, eBoidMode_OnLand, eBoidMode_Climbing) && rule->flag & BOIDRULE_ON_LAND)
839                 return 1;
840         
841         if (bpa->data.mode==eBoidMode_InAir && rule->flag & BOIDRULE_IN_AIR)
842                 return 1;
843
844         return 0;
845 }
846 void boids_precalc_rules(ParticleSettings *part, float cfra)
847 {
848         BoidState *state = part->boids->states.first;
849         BoidRule *rule;
850         for (; state; state=state->next) {
851                 for (rule = state->rules.first; rule; rule=rule->next) {
852                         if (rule->type==eBoidRuleType_FollowLeader) {
853                                 BoidRuleFollowLeader *flbr = (BoidRuleFollowLeader*) rule;
854
855                                 if (flbr->ob && flbr->cfra != cfra) {
856                                         /* save object locations for velocity calculations */
857                                         copy_v3_v3(flbr->oloc, flbr->loc);
858                                         copy_v3_v3(flbr->loc, flbr->ob->obmat[3]);
859                                         flbr->cfra = cfra;
860                                 }
861                         }
862                 }
863         }
864 }
865 static void boid_climb(BoidSettings *boids, ParticleData *pa, float *surface_co, float *surface_nor)
866 {
867         BoidParticle *bpa = pa->boid;
868         float nor[3], vel[3];
869         copy_v3_v3(nor, surface_nor);
870
871         /* gather apparent gravity */
872         madd_v3_v3fl(bpa->gravity, surface_nor, -1.0f);
873         normalize_v3(bpa->gravity);
874
875         /* raise boid it's size from surface */
876         mul_v3_fl(nor, pa->size * boids->height);
877         add_v3_v3v3(pa->state.co, surface_co, nor);
878
879         /* remove normal component from velocity */
880         project_v3_v3v3(vel, pa->state.vel, surface_nor);
881         sub_v3_v3v3(pa->state.vel, pa->state.vel, vel);
882 }
883 static float boid_goal_signed_dist(float *boid_co, float *goal_co, float *goal_nor)
884 {
885         float vec[3];
886
887         sub_v3_v3v3(vec, boid_co, goal_co);
888
889         return dot_v3v3(vec, goal_nor);
890 }
891 /* wanted_co is relative to boid location */
892 static int apply_boid_rule(BoidBrainData *bbd, BoidRule *rule, BoidValues *val, ParticleData *pa, float fuzziness)
893 {
894         if (rule==NULL)
895                 return 0;
896
897         if (boid_rule_applies(pa, bbd->part->boids, rule)==0)
898                 return 0;
899
900         if (boid_rules[rule->type](rule, bbd, val, pa)==0)
901                 return 0;
902
903         if (fuzziness < 0.0f || compare_len_v3v3(bbd->wanted_co, pa->prev_state.vel, fuzziness * len_v3(pa->prev_state.vel))==0)
904                 return 1;
905         else
906                 return 0;
907 }
908 static BoidState *get_boid_state(BoidSettings *boids, ParticleData *pa)
909 {
910         BoidState *state = boids->states.first;
911         BoidParticle *bpa = pa->boid;
912
913         for (; state; state=state->next) {
914                 if (state->id==bpa->data.state_id)
915                         return state;
916         }
917
918         /* for some reason particle isn't at a valid state */
919         state = boids->states.first;
920         if (state)
921                 bpa->data.state_id = state->id;
922
923         return state;
924 }
925 //static int boid_condition_is_true(BoidCondition *cond)
926 //{
927 //      /* TODO */
928 //      return 0;
929 //}
930
931 /* determines the velocity the boid wants to have */
932 void boid_brain(BoidBrainData *bbd, int p, ParticleData *pa)
933 {
934         BoidRule *rule;
935         BoidSettings *boids = bbd->part->boids;
936         BoidValues val;
937         BoidState *state = get_boid_state(boids, pa);
938         BoidParticle *bpa = pa->boid;
939         ParticleSystem *psys = bbd->sim->psys;
940         int rand;
941         //BoidCondition *cond;
942
943         if (bpa->data.health <= 0.0f) {
944                 pa->alive = PARS_DYING;
945                 pa->dietime = bbd->cfra;
946                 return;
947         }
948
949         //planned for near future
950         //cond = state->conditions.first;
951         //for (; cond; cond=cond->next) {
952         //      if (boid_condition_is_true(cond)) {
953         //              pa->boid->state_id = cond->state_id;
954         //              state = get_boid_state(boids, pa);
955         //              break; /* only first true condition is used */
956         //      }
957         //}
958
959         zero_v3(bbd->wanted_co);
960         bbd->wanted_speed = 0.0f;
961
962         /* create random seed for every particle & frame */
963         rand = (int)(PSYS_FRAND(psys->seed + p) * 1000);
964         rand = (int)(PSYS_FRAND((int)bbd->cfra + rand) * 1000);
965
966         set_boid_values(&val, bbd->part->boids, pa);
967
968         /* go through rules */
969         switch (state->ruleset_type) {
970                 case eBoidRulesetType_Fuzzy:
971                 {
972                         for (rule = state->rules.first; rule; rule = rule->next) {
973                                 if (apply_boid_rule(bbd, rule, &val, pa, state->rule_fuzziness))
974                                         break; /* only first nonzero rule that comes through fuzzy rule is applied */
975                         }
976                         break;
977                 }
978                 case eBoidRulesetType_Random:
979                 {
980                         /* use random rule for each particle (allways same for same particle though) */
981                         rule = BLI_findlink(&state->rules, rand % BLI_countlist(&state->rules));
982
983                         apply_boid_rule(bbd, rule, &val, pa, -1.0);
984                 }
985                 case eBoidRulesetType_Average:
986                 {
987                         float wanted_co[3] = {0.0f, 0.0f, 0.0f}, wanted_speed = 0.0f;
988                         int n = 0;
989                         for (rule = state->rules.first; rule; rule=rule->next) {
990                                 if (apply_boid_rule(bbd, rule, &val, pa, -1.0f)) {
991                                         add_v3_v3(wanted_co, bbd->wanted_co);
992                                         wanted_speed += bbd->wanted_speed;
993                                         n++;
994                                         zero_v3(bbd->wanted_co);
995                                         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                         copy_v3_v3(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                         copy_v3_v3(dir, pa->prev_state.ave);
1020                         normalize_v2(dir);
1021
1022                         copy_v3_v3(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                                 copy_v3_v3(dir, pa->prev_state.ave);
1039                                 normalize_v2(dir);
1040
1041                                 copy_v3_v3(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                                                 copy_v3_v3(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                                 copy_v3_v3(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                 copy_v3_v3(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                         copy_v3_v3(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 = min_ff(angle, val.max_ave);
1176
1177                         cross_v3_v3v3(nor, old_dir, wanted_dir);
1178                         axis_angle_to_quat(q, nor, angle);
1179                         copy_v3_v3(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                         copy_v3_v3(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                 copy_v3_v3(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         madd_v3_v3fl(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         copy_v3_v3(dvec, acc);
1253         mul_v3_fl(dvec, dtime*dtime*0.5f);
1254         
1255         copy_v3_v3(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         madd_v3_v3fl(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                                 copy_v3_v3(dvec, bpa->data.acc);
1282                         }
1283
1284                         /* gather apparent gravity */
1285                         madd_v3_v3v3fl(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                         madd_v3_v3fl(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                         //madd_v3_v3fl(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                                 madd_v3_v3v3fl(bpa->gravity, grav, dvec, -boids->banking);
1393                                 normalize_v3(bpa->gravity);
1394                         }
1395                         else {
1396                                 /* gather negative surface normal */
1397                                 madd_v3_v3fl(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                 copy_v3_v3(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                 copy_v3_v3(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                 BLI_snprintf(state->name, sizeof(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 {
1523         BoidState *staten = MEM_dupallocN(state);
1524
1525         BLI_duplicatelist(&staten->rules, &state->rules);
1526         BLI_duplicatelist(&staten->conditions, &state->conditions);
1527         BLI_duplicatelist(&staten->actions, &state->actions);
1528
1529         staten->id = boids->last_state_id++;
1530
1531         return staten;
1532 }
1533 void boid_free_settings(BoidSettings *boids)
1534 {
1535         if (boids) {
1536                 BoidState *state = boids->states.first;
1537
1538                 for (; state; state=state->next) {
1539                         BLI_freelistN(&state->rules);
1540                         BLI_freelistN(&state->conditions);
1541                         BLI_freelistN(&state->actions);
1542                 }
1543
1544                 BLI_freelistN(&boids->states);
1545
1546                 MEM_freeN(boids);
1547         }
1548 }
1549 BoidSettings *boid_copy_settings(BoidSettings *boids)
1550 {
1551         BoidSettings *nboids = NULL;
1552
1553         if (boids) {
1554                 BoidState *state;
1555                 BoidState *nstate;
1556
1557                 nboids = MEM_dupallocN(boids);
1558
1559                 BLI_duplicatelist(&nboids->states, &boids->states);
1560
1561                 state = boids->states.first;
1562                 nstate = nboids->states.first;
1563                 for (; state; state=state->next, nstate=nstate->next) {
1564                         BLI_duplicatelist(&nstate->rules, &state->rules);
1565                         BLI_duplicatelist(&nstate->conditions, &state->conditions);
1566                         BLI_duplicatelist(&nstate->actions, &state->actions);
1567                 }
1568         }
1569
1570         return nboids;
1571 }
1572 BoidState *boid_get_current_state(BoidSettings *boids)
1573 {
1574         BoidState *state = boids->states.first;
1575
1576         for (; state; state=state->next) {
1577                 if (state->flag & BOIDSTATE_CURRENT)
1578                         break;
1579         }
1580
1581         return state;
1582 }
1583