This PDF 1.5 document has been generated by PScript5.dll Version 5.2.2 / Acrobat Distiller 9.4.2 (Windows), and has been sent on pdf-archive.com on 07/05/2011 at 16:48, from IP address 82.3.x.x.
The current document download page has been viewed 1933 times.
File size: 2.45 MB (82 pages).
Privacy: public file
Modelling the flight of starlings
By
Simon Byford ‐ sjb17u@cs.nott.ac.uk
Supervised by
Dr. Jason Atkin ‐ jaa@cs.nott.ac.uk
School of Computer Science
University of Nottingham
Submitted May 2011, in partial fulfilment of the conditions of the award of the degree:
BSc (Hons) Mathematics and Computer Science
I hereby declare that this dissertation is all my own work, except as indicated in the text
Signature:
May 6th, 2011
Abstract
A project was undertaken to build a software model capable of accurately simulating
the flocking behaviour of starlings. After reviewing the relevant literature and studying
the mechanics of flocking, such a model was carefully designed and implemented in the
Java programming language. The model is capable of exhibiting a range of flocking
behaviours with simulations comprising upwards of 200 individual birds. A great
number of behavioural parameters are available to edit before and during simulations,
where their effects can be viewed in real time. The ability to spawn virtual falcons as
well as starlings introduces the notion of a predator which is an area largely unexplored
in previous models. A number of interesting observations were made during the
analysis phase of this project, including the fact that simulations employing metric and
topological distances induce much the same flocking behaviour, and that the application
can typically handle simulations comprising up to 500 individual birds before
experiencing significant drops in performance. In summary, the project was deemed
highly successful and a number of possible future extensions were proposed.
1
Table of contents
Abstract ................................................................................................................................................... 1
1 ‐ Introduction and motivation .............................................................................................................. 5
1.1 ‐ Aims and objectives .................................................................................................................... 5
1.2 ‐ Motivation .................................................................................................................................. 6
2 ‐ Related work ...................................................................................................................................... 7
2.1 ‐ Literature .................................................................................................................................... 7
2.1.1 ‐ Flocks, Herds, and Schools: A Distributed Behavioral Model .............................................. 7
2.1.2 ‐ An empirical study of large, naturally occurring starling flocks: a benchmark in collective
animal behaviour ............................................................................................................................ 8
2.1.3 ‐ Self‐organised complex aerial displays of thousands of starlings: a model ........................ 8
2.1.4 ‐ Interaction ruling animal collective behavior depends on topological rather than metric
distance: Evidence from a field study ............................................................................................. 9
2.1.5 ‐ Steering Behaviors for Autonomous Characters ................................................................. 9
2.1.6 ‐ An efficient algorithm to find k‐nearest neighbours in flocking behaviour ....................... 10
2.1.7 ‐ Aerial flocking patterns of wintering starlings, Sturnus vulgaris, under different predation
risk ................................................................................................................................................. 10
2.1.8 ‐ Parallel Bird Flocking Simulation ........................................................................................ 10
2.1.9 ‐ Simulating and Visualizing Natural Flocking Behaviour ..................................................... 11
2.1.10 ‐ Less related work ............................................................................................................. 11
2.2 ‐ Models ...................................................................................................................................... 12
2.2.1 ‐ Boids model ....................................................................................................................... 12
2.2.2 ‐ NetLogo Flocking model .................................................................................................... 13
2.2.3 ‐ 3D Flocking Boids II ............................................................................................................ 14
2.3 ‐ Other sources ............................................................................................................................ 14
3 ‐ Some theory ..................................................................................................................................... 15
3.1 ‐ The three urges ......................................................................................................................... 15
3.1.1 ‐ Separation .......................................................................................................................... 15
3.1.2 ‐ Alignment ........................................................................................................................... 15
3.1.3 ‐ Cohesion ............................................................................................................................ 15
3.2 ‐ Additional urges ........................................................................................................................ 16
3.2.1 ‐ Predator avoidance ............................................................................................................ 16
3.2.2 ‐ Randomness ....................................................................................................................... 16
3.2.3 ‐ Migration and obstacle avoidance ..................................................................................... 16
3.3 ‐ Combining urges ....................................................................................................................... 17
2
3.4 ‐ Steering processing chains ........................................................................................................ 18
3.4.1 ‐ Falcons ............................................................................................................................... 19
3.4.2 ‐ Starlings .............................................................................................................................. 20
3.5 ‐ Metric vs topological distance .................................................................................................. 21
4 ‐ Description of the work ................................................................................................................... 23
5 ‐ Design............................................................................................................................................... 26
5.1 ‐ Language, libraries and platform .............................................................................................. 26
5.2 ‐ Prototyping ............................................................................................................................... 27
5.3 ‐ GUI Design................................................................................................................................. 28
5.4 ‐ Class diagram ............................................................................................................................ 31
6 ‐ Implementation ............................................................................................................................... 32
6.1 ‐ Design changes ......................................................................................................................... 32
6.1.1 ‐ Awareness circle ................................................................................................................ 32
6.1.2 ‐ Save/load functionality ...................................................................................................... 33
6.1.3 ‐ Removal of viewing angle attribute ................................................................................... 33
6.1.4 ‐ Anti‐aliasing ....................................................................................................................... 33
6.1.5 ‐ FPS counter ........................................................................................................................ 34
6.1.6 ‐ Sizable window .................................................................................................................. 34
6.2 ‐ Classes ....................................................................................................................................... 35
6.2.1 ‐ AwarenessCircle ................................................................................................................. 35
6.2.2 ‐ Bird ..................................................................................................................................... 35
6.2.3 ‐ DynamicSimProperties ....................................................................................................... 36
6.2.4 ‐ FPSCounter......................................................................................................................... 36
6.2.5 ‐ Falcon ................................................................................................................................. 37
6.2.6 ‐ FlockManager .................................................................................................................... 38
6.2.7 ‐ GUIPanel ............................................................................................................................ 41
6.2.8‐ SimDims .............................................................................................................................. 42
6.2.9‐ SimulationManager ............................................................................................................ 42
6.2.10 ‐ SimulationPanel ............................................................................................................... 43
6.2.11 ‐ Starling ............................................................................................................................. 43
6.2.12 ‐ StaticSimProperties .......................................................................................................... 44
6.2.13 ‐ Window ............................................................................................................................ 44
6.3 ‐ Algorithms of interest ............................................................................................................... 46
6.3.1 ‐ Calculating the distance between birds ............................................................................. 46
3
6.3.2 ‐ Calculating the average bearing ........................................................................................ 47
6.3.3 ‐ Calculating the nearest n birds (topological distance) ...................................................... 49
6.3.4 ‐ Drawing the "awareness circle" ......................................................................................... 50
6.4 ‐ Notable problems faced ........................................................................................................... 51
6.4.1 ‐ Bias towards flocking in one particular direction .............................................................. 51
6.5 ‐ Testing ....................................................................................................................................... 52
6.5.1 ‐ “Continuous testing”.......................................................................................................... 52
6.5.2 ‐ Unit testing ........................................................................................................................ 52
7 ‐ Analysis and evaluation ................................................................................................................... 53
7.1 ‐ Analysis ..................................................................................................................................... 53
7.1.1 ‐ Tests involving starlings ..................................................................................................... 53
7.1.2 ‐ Tests involving starlings and falcons .................................................................................. 62
7.1.3 ‐ Metric vs topological distance ........................................................................................... 67
7.1.4 ‐ Performance testing .......................................................................................................... 68
7.2 ‐ Evaluation ................................................................................................................................. 70
8 ‐ Summary and further work .............................................................................................................. 74
8.1 ‐ Summary ................................................................................................................................... 74
8.2 ‐ Further work ............................................................................................................................. 75
8.2.1 ‐ 3D modelling ...................................................................................................................... 75
8.2.2 ‐ Obstacles ............................................................................................................................ 75
8.2.3 ‐ Walls................................................................................................................................... 75
8.2.4 ‐ More intelligent steering algorithms ................................................................................. 75
8.2.5 ‐ Larger scenes ..................................................................................................................... 76
8.2.6 ‐ Viewing angle attribute ..................................................................................................... 76
8.2.7 ‐ Collision penalty ................................................................................................................. 76
8.2.8 ‐ Wind ................................................................................................................................... 76
8.2.9 ‐ Separate behavioural attributes for falcons and starlings................................................. 77
8.2.10 ‐ Killing and evolution modelling ....................................................................................... 77
8.2.11 ‐ Variable speeds ................................................................................................................ 77
8.2.12 ‐ Migration urge ................................................................................................................. 78
8.2.13 ‐ Custom initial bird placement .......................................................................................... 78
8.2.14 ‐ Algorithmic optimisations ................................................................................................ 78
Appendix A – Related work ................................................................................................................... 79
Bibliography .......................................................................................................................................... 80
4
1 ‐ Introduction and motivation
The sight of thousands of starlings forming great flocks and wheeling, diving and
convulsing through the air is an impressive one. The remarkable thing is that there is no
leader: the system is completely decentralised and each bird is just following a
collection of simple, local rules. The visually striking organisation and structure of the
flock emerges as a by‐product of these simple rules being obeyed by thousands of
individual birds simultaneously.
This project seeks to realistically simulate the beauty of flocking in a software
environment. As we shall see, this is an already well‐explored area of research with a
number of models in existence and some major developments being made as recently as
2008. It is therefore important to understand where my project fits into this exciting
field.
In the chapters that follow, I will review previous work relating to flocking and cover
some additional theory necessary to fully understand it. I will then clearly describe my
model, outline its relevance, specify in which respects it goes beyond current models
and express in detail exactly how it works in terms of classes and functions. Finally, I
will analyse the various behaviours observable using the model, formally evaluate the
system in relation to my original aims and objectives, give a personal reflection on how I
thought the project went and propose some possible future extensions to the model.
1.1 ‐ Aims and objectives
The following aim and objectives are taken directly from the project proposal
document, which was originally submitted in October 2010.
Aim: To design, implement and evaluate an application that simulates the flocking
behaviour of starlings.
Objectives:
To complete a review of literature and web resources relating to existing flocking
models.
To research what is currently known about the mechanics of flocking and learn
about the local rules that dictate the behaviour of each individual bird within a
flock.
5
To develop a suitable application that allows for the simulation of large numbers
of virtual birds.
To run the simulation and systematically alter the parameters relating to the
behaviour of individual birds, observing the effects both locally and globally.
To introduce the notion of a predator and observe how this influences the
behaviour of the flock.
To evaluate the model and suggest possible improvements and optimisations.
The extent of my adherence to these objectives will be formally analysed in the
evaluation section of this report (see 7.2 ‐ Evaluation).
1.2 ‐ Motivation
There are several motivations for my undertaking this project. Firstly, it is an exciting
area of research that genuinely interests me and many others. The consequence of this
is that ample material on the subject is freely available to learn from and expand upon.
It is also important to mention that the topic is not yet fully understood, with some
important questions still remaining unanswered. For example, the question of whether
birds rely on metric or topological distance when observing neighbouring birds. For
more information on this topic, please refer to 3 ‐ Some theory.
Secondly, the lessons learned from modelling flocks of birds can also be applied to other
animal group phenomena like herding, schooling and swarming. It might even be
possible to generalise certain aspects of the research to all crowds, including crowds of
humans, which has obvious benefits.
Finally, the visual nature of this project appeals to me and should make demonstrating
the software an engaging experience.
With no specific end‐user in mind, the question of “who will use my software?” might
seem like a pertinent one. However, the real value of this project lies not in the finished
product but in the knowledge I acquired along the way, whilst developing and testing it.
This project was driven by my curiosity about how easily one could accurately model
apparently complex phenomena such as flocking. The extent to which my software
mimics nature represents a measure of my success, rather than a favourable appraisal
from a real end‐user.
6
2 ‐ Related work
2.1 ‐ Literature
A great number of academic papers exist on the subject of flocking from a range of
different perspectives: some biological, some mathematical, some relating to computer
science. Here is a brief overview of the nine papers I considered most relevant to my
own project. Relevance was taken to mean directly addressing the issue of flocking
(preferably the flocking of starlings) while having the potential to inspire some design
decision or putting forward some hypothesis that could be tested by my own model.
Furthermore, highly‐cited papers were favoured over less‐cited papers.
2.1.1 ‐ Flocks, Herds, and Schools: A Distributed Behavioral Model
This landmark paper by Reynolds (1987), details the first attempt at animating a flock
of birds using a technique known as the “boid flock model”, which has since become the
norm. The model works in the following general way: time is spent programming the
behaviour of a single boid, setting the various local rules that accommodate flocking.
Rules like “don't get too close to your neighbour” and “try to align your speed and
direction with the rest of the flock”. After creating a satisfactory blueprint for a single
boid, create many instances and “set them free”, allowing them to interact and
manipulate the behaviour one another. The expected flock‐like motion should emerge
as a product of these many low‐level interactions. This model was developed in contrast
to existing methods that used complex, inflexible motion paths as their central
animation technique.
While the paper is somewhat verbose and lacking technical specificities, it still contains
a great deal of valuable information. The three general behavioural rules (alignment,
cohesion and separation) are covered very comprehensively. In particular, the paper
highlights the need to create a system that combines, prioritises, and arbitrates between
these three potentially conflicting urges to produce a sensible result. For example,
steering to avoid a potential collision may result in the bird drifting further from the
centre of the flock, but it remains the correct solution and my system should reflect that.
Certain aspects of the paper are not directly related to my project. These include details
about 3D modelling concepts such as bank, roll and pitch which were ignored because
my project was restricted to simulation in two dimensions only.
7
2.1.2 ‐ An empirical study of large, naturally occurring starling flocks: a benchmark in
collective animal behaviour
This important paper by Ballerini, et al. (2008), documents the first large‐scale
investigation into real‐life flocking using stereo photography. Important because no
previous studies have been able to record the positions of such large numbers of
individual birds (up to 2700) very accurately due to technological constraints. The
paper draws many conclusions from the empirical data including that population
density is not homogenous (since birds are packed more tightly at the borders) and that
flock sizes vary but proportions do not.
The general lessons gained from this paper were important. In particular, the “three
general behavioural rules” that were discussed were of fundamental importance to the
design of my application. These rules, which originate from Reynolds’ 1987 paper, are
the following: alignment (move in the same direction as your neighbours), cohesion
(remain close to them) and separation (avoid collisions).
Much of what is discussed in this paper goes beyond the scope of my project.
Measurements relating to flock shape, movement, density and structure are described
in 3D using complicated mathematics and statistical techniques, the details of which are
superfluous to my project.
2.1.3 ‐ Self‐organised complex aerial displays of thousands of starlings: a model
This paper by Hildenbrandt, Carere, & Hemelrijk (2009), details an attempt to build a
computer model capable of producing similar patterns to those observed in large‐scale
empirical studies of flocking amongst starlings, such as the previous study. It discovers
that in addition to the “three general behavioural rules”, a number of characteristics
specific to starling behaviour must be considered to achieve realistic results. Amongst
these considerations is the one that starlings must have “a low and constant number of
interaction‐partners”, which is in agreement with a number of other studies. It
concludes by comparing the model to quantitative empirical data, with the model
judged as bearing a close resemblance.
This paper is relevant to my project because it sets out to achieve a very similar goal: to
accurately model the flight of starlings that conforms approximately to real‐life
8
measurements. The focus is very specifically on starlings as opposed to general swarms
which is important.
Unfortunately, as with the previous study, much of what is said appears to go beyond
the scope of my project, dabbling in mathematics not required for 2D simulations.
Furthermore, the effects of predators on the flock are not discussed in detail.
2.1.4 ‐ Interaction ruling animal collective behavior depends on topological rather than
metric distance: Evidence from a field study
This paper by Ballerini, et al. (2008), looks into the precise nature of interaction
between individual birds in a flock. Specifically, whether or not metric distance (i.e. “all
birds within 2m”) or topological distance (i.e. “the 5 closest birds, regardless of actual
distance”) between neighbouring birds plays a part when making decisions about
steering. It concludes that evidence points strongly towards topological rather than
metric distance being utilized in nature and even gives a calculated estimation
regarding numbers: only the 6 or 7 closest birds are taken into account, it claims. The
paper argues this is likely not simply the average number of unobstructed visible
neighbours; rather a limit on the number of neighbours the bird is able to track
effectively.
While the claim that only the 6 or 7 nearest birds topologically are taken into account
was fascinating to scrutinise during the analysis phase of this project, this paper did not
directly inspire any design choices except to encourage the inclusion of a topological
distance facility.
It is worth noting that the data analysed in this paper are taken from a real study which
tracked movement in three dimensions. The “magic number” of 6/7 is likely to differ
(specifically, decrease) when simulating in fewer dimensions, so might not be suitable
for 2D modelling. Again, this fact was of interest primarily during the analysis phase.
2.1.5 ‐ Steering Behaviors for Autonomous Characters
This second paper by Reynolds (1999) looks into a variety of steering behaviours
exhibited by autonomous characters in the context of computer games and virtual
reality. These include behaviours like seek, flee, pursuit, evasion, obstacle avoidance
and path following. The section on separation, cohesion and alignment (the “three
general behavioural rules”) goes into nice detail about collision avoidance amongst
9
multiple autonomous characters. This is the only section concerned with flocking,
however. The remainder of the paper focuses on behaviours not directly relevant to my
project.
2.1.6 ‐ An efficient algorithm to find k‐nearest neighbours in flocking behaviour
This paper by Lee (2010), notes that conventional algorithms for finding the k‐nearest
neighbours, a crucial part of any flocking program, run with complexity O(n2). This is
undesirable when dealing with very large numbers of birds. It goes on to talk in detail
about an alternative algorithm based on the observation than proximate agents often
share many common neighbours. The paper concludes by making a bold claim that
execution time can be improved by 43% when using this algorithm compared with
using the conventional one.
The algorithm has an obvious direct relevance to my project. Even though I decided not
to use it (since the relatively small number of spawned birds did not warrant this level
of optimisation), many of the factors influencing the author's choice were considered
when deciding upon my own suitable implementation.
2.1.7 ‐ Aerial flocking patterns of wintering starlings, Sturnus vulgaris, under different
predation risk
This biologically‐focussed paper by Carere, et al. (2009), reviews the effects of
predators on the flocking patterns of starlings. Using real world data, it tests and
confirms the widely held hypothesis that starlings form larger, more compact flocks in
areas of high predation and that such flocking patterns decrease the chance of
successful attacks. It was interesting to examine these claims using my own model
during the analysis phase of my project (see 7.1.2 ‐ Tests involving starlings and falcons). The
section pertaining to interaction between geographically separate flocks was irrelevant
to my project because of the small area occupied by my simulated birds.
2.1.8 ‐ Parallel Bird Flocking Simulation
This paper by Lorek, Informatik & White (1993), documents an effort into improving
the efficiency of Reynolds's flocking algorithm by employing parallelisation techniques.
It begins by explaining the basics of modelling flocks and goes on to talk about a
parallelised implementation. Interestingly, the author adds “obstacle avoidance” and
“migration” to the three conventional behavioural rules of alignment, cohesion and
10
separation. In designing my solution, I reviewed these additional rules and considered a
further one: “predator avoidance”.
The thinking behind the implementation, if not the implementation itself, was important
when developing my own application. Of special interest was the section on "Urge
Integration", which describes how to prioritise the different urges experienced by each
bird in response to their environment.
Ultimately, much of the paper turned out to be irrelevant since my solution did not
employ parallelisation. It should be taken into account that this paper was published in
1993 when processor speeds were a fraction of what they currently are and thus
performance was far less of an issue. I certainly did not have (or need to have) access to
machines with numbers of processers comparable to the number of starlings, as was the
case in this paper.
2.1.9 ‐ Simulating and Visualizing Natural Flocking Behaviour
This paper by Schnapauff & Schule (1998), describes the implementation of a model to
simulate flocking and its visualisation. As with several previous papers, the section on
the three urges was especially important. Please refer to 3.1 ‐ The three urges for my own
explanation of this topic, much of which is derived from this paper and others.
Unfortunately, this paper focuses quite heavily on obstacle avoidance, which is
something I did not implement due to its complexity. A sound understanding of force
fields and ray tracing is required in order to make any headway on this topic. Please see
8.2 ‐ Further work for details on the possible future introduction of obstacle avoidance.
2.1.10 ‐ Less related work
In addition to the above papers, I reviewed several others which I considered less
relevant. These included papers by Reynolds (1993) and by Spector, Klein & Perry
(2003), which both focus strongly on the concept of evolutionary flocking algorithms, an
idea outscoped in this project but suggested as a possible future improvement in 8.2 ‐
Further work. Other less relevant papers included one by Funge, Tu & Terzopoulos
(1999), which explored the behaviour of autonomous characters in terms of cognitive
models, and one by Gazi & Passino (2004), which investigated the foraging behaviour of
autonomous agents whilst not being directly related to flocking.
11
2.2 ‐ Models
Several flocking models are freely available on the internet ranging greatly in scope,
purpose and language of implementation. Here, I very briefly consider three such
models.
2.2.1 ‐ Boids model
Extremely basic and uncustomisable, this was the model by Reynolds (1986) that
accompanied his landmark paper “Flocks, Herds, and Schools: A Distributed Behavioral
Model” (1986). Reynolds's model can be thought of as the ancestor of all other boids‐
based flocking models. Compared with more modern implementations, only a relatively
small number of boids can be created which limits the complexity of any emergent
flocks.
12
2.2.2 ‐ NetLogo Flocking model
Written using the agent‐based simulation framework "NetLogo", this model by
Wilensky (1998), allows the user to spawn large numbers of triangular boids in 2D
space and observe their flocking behaviour. I drew much inspiration from Wilensky's
model because it sets out to achieve very similar goals to my own. The ability to edit
behavioural parameters such as maximum turning angles "on the fly" was something I
found particularly interesting so I emulated and expanded upon the idea in my own
model. My own model deviates from Wilensky’s with the inclusion of original features
such as predator spawning and metric/topological distance facilities.
13
2.2.3 ‐ 3D Flocking Boids II
This visually impressive 3D flocking model by Wetmore (2010) allows the user to rotate
and zoom around the simulation during execution, but is otherwise far less
customisable than other models, including my own. One unique feature is included
however: the ability to disable wrapping (i.e. the ability of birds to travel through one
wall and emerge from the opposite), which truly confines the simulation to within the
bounds of the cube. This "wall avoidance" concept provokes some interesting flocking
behaviours.
2.3 ‐ Other sources
Because flocking is a topic of public as well as academic interest, a number of less formal
sources of information were consulted in addition to the aforementioned literature and
computer models. These included blogs, online newspaper articles and YouTube videos.
A full listing of URLs can be found in the appendix of this report.
14
3 ‐ Some theory
3.1 ‐ The three urges
“The three urges” (sometimes called “the three steering behaviours” or “the three
flocking rules”) comprise the basic rules which, when obeyed simultaneously by
sufficiently many birds, accommodate flocking. They are outlined as follows in
Reynolds’s 1987 paper “Flocks, Herds, and Schools: A Distributed Behavioral Model”.
3.1.1 ‐ Separation
“Steer to avoid crowding local flockmates”
Separation represents the birds desire to avoid
collisions. Separation is effective over short
distances and takes precedence over the other
urges when the threat of collision is sufficiently
high.
3.1.2 ‐ Alignment
“Steer towards the average heading of local flockmates”
Alignment ensures flocks travel in some
coherent direction. In systems where speed is
non‐constant, velocity matching could also be
considered alignment.
3.1.3 ‐ Cohesion
“Steer to move toward the average position of local flockmates”
Cohesion can be thought of as the inverse of
separation and represents a bird’s desire to
move to the centre of the flock. It is effective
over long distances.
15
3.2 ‐ Additional urges
In theory, the three urges are sufficient to accommodate lifelike flocking. However, I
chose to include two additional urges in my model which I considered important.
3.2.1 ‐ Predator avoidance
“Steer away from nearby predators”
Predator avoidance works in the same way as
separation but only applies between birds and
predators and is effective over long distances. It
has high priority and overrides all other urges
(including separation) whenever a predator is
within viewing distance.
3.2.2 ‐ Randomness
Randomness models the birds' tendency to fly
“Steer randomly”
imperfectly because of miscalculations caused by
sudden changes in wind direction, for example.
When randomness is enabled, a random value is
added to the steering value generated by the
other urges, regardless of precedence. This is
because birds fly imperfectly even when
dangerously close to other birds or when being
chased by predators. When randomness is
disabled, simulations can be thought of as being
entirely deterministic.
3.2.3 ‐ Migration and obstacle avoidance
I considered two final urges, which I call “migration” and "obstacle avoidance".
Migration encourages birds to flock to a specific point in space while obstacle avoidance
discourages collisions between birds and stationary objects/walls. These urges were
not implemented but are discussed in the “Further work” section of this report.
16
3.3 ‐ Combining urges
Writing good algorithms that intelligently combine, prioritise, and arbitrate between
the three potentially conflicting urges to produce a sensible result is not trivial. There
are no right or wrong answers; just rules of thumb. Reynolds nicely summarises one
difficulty behind urge combination, indecision, in the following extract from “Flocks,
Herds, and Schools: A Distributed Behavioral Model” (1987):
“The main cause of indecision is that each behaviour [urge] might be shouting
advice about which way to turn to avoid disaster, but if those acceleration
[steering] requests happen to lie in approximately opposite directions, they will
largely cancel out under a simple weighted averaging scheme. The boid would
make a very small turn and so continue in the same direction, perhaps to crash
into the obstacle.”
I make the distinction between urges that act over "long distances" and ones that act
over "short distances" by dividing the birds' perception of the world into two zones.
"Viewing distance" encompasses everything a bird can see, and is defined by the user as
either a metric or topological distance, while "minimum separation distance" is a subset
of viewing distance representing the ideal spacing between flockmates the bird would
like to maintain. "Minimum separation distance" is defined by the user as a metric
distance. When a neighbouring bird enters a bird's minimum separation zone, the
"separation" urge kicks in and attempts to widen the gap to prevent a possible collision.
"Minimum separation distance" should always be at most "viewing distance" but both
values can equal zero, whereupon the bird can be thought of as "flying blind".
17
My chosen implementation of urge combination works in the following way. The user
assigns a "maximum steering value" to each urge which defines the maximum number
of degrees a bird can turn in response to that urge per iteration. On each iteration, every
relevant urge (relevant means taking into consideration the fact certain urges might not
require consideration because of the presence of predators, for example) is "consulted"
for a steering request. This is like asking each urge: "if you were in charge, which
direction would you steer?" These ideal steering values are then truncated so as not to
exceed the maximum steering values imposed by the user. The resulting values are then
summed and this defines where the bird turns. A careful choice of maximum steering
values can limit the problems caused by indecision.
3.4 ‐ Steering processing chains
A good way to understand my implementation of urge combination is to consider the
following "steering process chain" diagrams, which show the sequence of steps taken
during each iteration of the urge combination algorithm.
18
3.4.1 ‐ Falcons
Get close birds
none
some
Cohesion
Random
Set direction
Note: Falcons use a special variant of "cohesion" that considers only starlings, not
falcons. This urge could sensibly be renamed "hunting".
19
3.4.2 ‐ Starlings
Get close birds
none
some
some
Check for falcons
none
Predator
avoidance
some
Check for starlings
within minimum
separation distance
none
Cohesion
Separation
Alignment
Random
Set direction
20
Finally, it is important to note that updating the steering values of the flock members is
split into two separate passes. The first pass computes the new steering value for each
bird using the algorithm described above, while the second pass actually updates the
values. This ensures each bird steers independently of one another. If the steering
values were computed and updated at the same time, the steering behaviour of one bird
could potentially affect that of another, creating a sequence of dependencies.
3.5 ‐ Metric vs topological distance
I have previously mentioned the concepts of metric and topological distances without
properly explaining their meaning. Metric distance is distance in the usual sense. For
example, all birds within a metric distance of 90 pixels of the target bird (highlighted
blue) are shown below:
Topological distance, on the other hand, considers the n closest birds regardless of
actual distance. For example, all birds within a topological distance of seven birds of
the target bird (highlighted in blue) are shown below:
21
Ballerini et al. (2008) concludes that evidence points strongly towards topological
rather than metric distance being utilized in nature. It gives a calculated estimate that
only the 6 or 7 closest birds are taken into account and argues this is due to a limitation
on the number of neighbours the bird can track effectively, which itself is a product of
the bird's mental capacity. This is different from the number of neighbours the bird can
physically discern, which would typically be a much larger number than 6 or 7.
Finally, note that while "viewing distance" can sensibly be defined as either a metric or a
topological distance, it only makes sense for "minimum separation distance" to be
defined as a metric distance. This is because "minimum separation distance" can be
thought of as the distance at which birds attempt to escape from one another, which, by
definition, is impossible to achieve for birds within any (nonzero) topological distance.
22
4 ‐ Description of the work
In this chapter I will attempt to outline exactly what the completed system is capable of
doing with an emphasis on original features. Only the high‐level functionality of the
application will be discussed without consideration for its implementation. For details
about the implementation, please see 6 ‐ Implementation.
The system allows the user to:
Run the application with a custom‐sized "simulation panel" (the area where
flocking is observed). The lower size limit is 100 x 100 pixels and there is no
upper size limit. If dimensions are not specified by the user, the default size value
of 800 x 800 pixels is used.
Create any number of virtual starlings and add them to the simulation panel
with random coordinates and random directional values. The speed of the
starlings can be set between 0 (stationary) and 40 (extremely fast).
Create either:
o a single user‐controlled virtual falcon
o any number of computer‐controlled virtual falcons
and add it/them to the simulation panel with random coordinates and random
directional values. The speed of the falcon(s) can be set between 0 and 40. It is
recommended that falcons are assigned a greater speed than starlings.
Edit the behavioural attributes of the birds in the simulation panel. The
attributes available for editing are:
o Viewing distance. Specified as either a metric or a topological distance.
There is a lower bound of 0 in both cases, which is equivalent to every
bird "flying blind". There is no upper bound for metric viewing distance,
while the upper bound for topological viewing distance is the total
number of birds present in the simulation panel minus one. This
uppermost value is equivalent to every bird being aware of every other
bird.
o Minimum separation distance. Specified as a metric distance. This is
the distance birds attempt to maintain from one another to avoid
collisions.
23
o Maximum turn values. These are the maximum angles, measured in
degrees, that a bird can turn in response to a particular urge per
iteration. In each case, values can range between 0 (where birds are
"paralysed" with respect to that urge) and 180 (where birds can turn
instantaneously with respect to that urge). The five urges, outlined fully
in the theory section of this report, are as follows:
Alignment ‐ “Steer towards the average heading of local
flockmates.”
Cohesion ‐ “Steer to move toward the average position of local
flockmates.”
Separation ‐ “Steer to avoid crowding local flockmates.”
Predator avoidance ‐ “Steer away from nearby predators.”
Random ‐ “Steer randomly.”
o Enable/disable "awareness circle". Enabling the awareness circle
doesn't change the behaviour of the birds. It is a visual tool intended to
give the user insight into the perceived crowdedness of an arbitrarily
chosen bird.
Please note that all of these attributes can also be edited during the execution of
the simulation, where their effects can be observed in real time.
Save and load scenario files. Scenario files can used to store the entire
contents of the GUI, which is useful for repeating simulations with the same
setup values and behavioural attributes.
Begin the simulation by pressing the "Play" button.
While the simulation is in progress, the user can:
Observe flocking. Assuming the behavioural attributes have been set in an
arrangement that accommodates flocking (for instance, the default values), it
shouldn't take long for discernable flocks to form. If a user‐controlled falcon has
been added to the simulation panel, the user can direct its movement using the
arrow keys (up ‐ move forward, left ‐ steer left, right ‐ steer right). This
effectively allows the user to manipulate the flock in real time.
Edit the behavioural attributes, as described above. The "Update" button must
be pressed for the changes to take effect.
24
Pause the simulation by pressing the "Pause" button.
Halt the simulation by pressing the "Stop" button. This cancels the simulation
and removes all the birds from the simulation panel.
Enable or disable the frames per second (FPS) counter.
Enable or disable anti‐aliasing, which improves the quality of the rendering
but may lead to a drop in performance.
25
5 ‐ Design
5.1 ‐ Language, libraries and platform
Chosen language: Java
I chose to implement the flocking model in Java for a number of reasons. Firstly, Java
applications are cross‐platform: any machine capable of running the Java Virtual
Machine (JVM) is capable of running any Java application. Since distributions of the JVM
exist for the majority of popular operating systems, portability between machines
would certainly not be an issue.
Secondly, Java is the programming language I feel most comfortable using, having
written plenty of it both at university and professionally during my industrial placement
year at Ultra Electronics. Although it can be harmful to be sentimental when choosing a
suitable programming language for a given task, familiarity is still an important
consideration because learning new technologies can be extremely time consuming.
Finally, I chose Java because it is suitable for the job in hand. Flocking programs lend
themselves very well to being implemented in object‐oriented (OO) languages. This is
because flocking is based around the idea of writing a blueprint for some simple entity
(a bird) which defines how it behaves and how it interacts with other such entities,
before creating many such instances of this entity and observing how they behave
collectively. Clearly this translates very naturally to implementation in an OO language
such as Java or C++. Java was favoured over C++ because of my familiarity of Java and
because I did not foresee it being necessary to perform any low‐level memory
management tasks, as enabled by C++.
Chosen third‐party libraries: none
After some research and careful thought, I decided against linking to any third‐party
graphics libraries. This was because I was already familiar with the low‐level graphics
libraries bundled natively with Java and decided these would be perfectly adequate for
the purposes of my application since I would only ever need to render simple 2D shapes
and efficiency was an important consideration. I decided to use the bundled Swing
widget toolkit instead of a third‐party alternative like Qt for the same reason.
26
Chosen platform: cross‐platform
For the sake of convenience, I developed the flocking model on my home machine
(which runs Windows 7) but the beauty of Java means the application can run on any
machine with the JVM installed, independent of operating system. I have since tested it
on Windows XP, Mac OS X and Ubuntu (Linux) operating systems.
Chosen integrated development environment (IDE): NetBeans
Once again, my choice of IDE was heavily reliant on previous experience. I have
developed software using JCreator, Eclipse and NetBeans in the past and selected
NetBeans simply because I enjoyed using it most. Strengths include its clean layout and
its excellent visual GUI builder “Matisse”, which I made extensive use of when designing
the user interface.
5.2 ‐ Prototyping
Although I had worked with Java’s graphics libraries before, I had no previous
experience dealing with animation. To alleviate many of the risks associated with basing
my entire project around some unknown programming technique, I decided to work on
a prototype alongside designing the model itself. This prototype consisted of an
application that created a
window containing a number of
triangles that moved around in
random directions, always
pointing towards their direction
of motion. The prototype was
successful in assuring me that I
could feasibly implement the
more complex flocking model
using the same technique. Much
of the code from the prototype
was reused in the final
application.
27
5.3 ‐ GUI Design
Once I had thought carefully about which parameters should be available for editing, I
produced the following mock‐up of what I hoped the GUI would look like.
The area in which
flocking occurs is
known as the
“simulation panel”.
I considered it important to
distinguish between
parameters that could only
be edited before the
simulation had begun
(“setup”), and parameters
that could be edited during
execution (“behaviour”).
The playback buttons
were intentionally
oversized to help
distinguish them from
the rest of the GUI.
28
There are a number of aspects I considered unsatisfactory with this mock‐up. These are
best explained with reference to images of the final version of the GUI, which can be
found below.
The ratio between the size of the
simulation panel and the size of the GUI
was drastically revised to shift the focus
onto flocking. The simulation panel was
overlaid with an image of the sky to add
realism.
The playback controls are
more intuitive when
expressed as familiar media
playback buttons. These
images were obtained from a
website specialising in
royalty‐free icons. Support
for pausing was also added.
These sliders allow the user to
select speeds only within the
correct range enforced by the GUI.
29
These buttons were added to control
two new functions: anti‐aliasing and
the FPS counter. They are discussed
more fully in the implementation
section of this report.
To further make clear the distinction
between “setup” and “behaviour”
parameters, they were separated into two
different tabs. This also helps ensure the
GUI is compact and tidy.
New widgets were added to accommodate
the update button and the awareness circle
tickbox. These features are described in the
implementation section of this report.
The third tab is occupied by the
controls used to save and load
scenario settings. The icons were
obtained from the same website
as the media playback icons.
30
5.4 ‐ Class diagram
The following UML class diagram was created to guide my implementation of the
system by setting out how the main classes should interact with one another. It is
important to note that this diagram is slightly out of date since new methods and classes
have since been added, but the fundamental structure remains identical. I will devote
time to explaining the final version of each class in the implementation section of this
report.
31
6 ‐ Implementation
6.1 ‐ Design changes
The following changes were made to the design during the implementation phase of the
project. The justification for the addition or removal of each feature is explained in turn.
It should be noted that none of the below constitutes a major design alteration. This can
be seen as a testament to my unambiguous specification and strong design.
6.1.1 ‐ Awareness circle
When implementing the different awareness modes, it became clear I needed some way
to test whether or not they were working correctly. I developed the so‐called
“Awareness circle” to illustrate clearly both the viewing distance and the minimum
separation distance of an arbitrarily chosen member of the flock. These measurements
are displayed as two circles of differing radii centred on the bird in question. To further
enhance the illustration, other birds within each circle are temporarily painted white or
pink to signify them being “in view” and “too close”, respectively. Having successfully
used the awareness circle as a debugging tool, I chose not to remove it because it
remained an interesting visual tool that gave insight into the perceived crowdedness of
a given bird.
32
6.1.2 ‐ Save/load functionality
During development, I was often required to run the application and input the same
simulation parameters (number of birds, behavioural attributes, etc.) whenever
changes were made to the codebase to ensure there had been no unexpected side‐
effects. Entering these parameters manually each time was tiresome so I decided to
build a feature that could save them to a text file and reload them later when necessary.
This feature is also useful when demonstrating the software to quickly exhibit a range of
different flocking behaviours without having to remember the required parameter
values.
6.1.3 ‐ Removal of viewing angle attribute
Early on in the design phase, there was talk of including a “viewing angle” attribute
which could be used to restrict the birds’ angle of sight. However, it was decided that
the amount of time required to implement such an attribute was not proportional to its
benefits. Furthermore, at a practical level, the viewing angle attribute would be badly
suited to an environment that used coordinate wrapping. To understand this, consider
that even when restricted to only “seeing ahead”, a bird projected onto a torus (which is
topologically equivalent to wrapping the x and y axes) can still see behind itself. For
discussion on the possible future introduction of a viewing angle attribute, please see
8.2 ‐ Further work.
6.1.4 ‐ Anti‐aliasing
Java supports anti‐aliasing with the addition of just a few lines of code. I decided to
implement it because I was interested in how much it improved the image quality and
the extent to which it slowed down the simulation. Anti‐aliasing can be switched on/off
by the user and is disabled by default.
Anti‐aliasing disabled Anti‐aliasing enabled
33
6.1.5 ‐ FPS counter
Drops in frame rate occur occasionally when the number of starlings in the simulation
exceeds the number the application can properly handle. I decided to implement a
frames per second counter to accurately measure this tendency. Ideally, it should
always display 50 since the simulation is coded to refresh fifty times per second, but this
doesn’t always happen in reality. The FPS counter can be switched on/off by the user
and is disabled by default.
6.1.6 ‐ Sizable window
A common problem I encountered when distributing my application occurred because
the window was a fixed size. More precisely, the simulation panel occupied exactly 800
x 800 pixels, which was too large for some displays to render correctly, meaning the
application was unusable. To combat this, I added support for command line attributes
that allowed the user to specify the required width and height of the simulation panel in
pixels. Here in an example usage:
java -jar "Starlings.jar" 800 600
This has the further advantage of allowing the user to make full use of their available
screen real estate. Larger simulation panels give the birds more free space in which to
form flocks.
34
6.2 ‐ Classes
The system is comprised of a number of interrelated Java classes contained in files of
the form ExampleClass.java. The UML class diagram found the previous section of this
report gives some idea about the relationship between these classes. Here follows an
alphabetically ordered listing of every class with details about their purpose,
inheritance and their most important methods.
6.2.1 ‐ AwarenessCircle
Extends: JComponent
The swing component representing the "awareness circle": a pair of primitively drawn
concentric circles used to indicate the viewing distance and minimum separation
distance of an arbitrarily chosen bird. It doesn't make sense to instantiate this class
more than once and the singleton design pattern is used to enforce this restriction.
Method: public void updateCircle(int x_, int y_, int radAwareness_, int
radMinSep_)
Updates the location and radiuses of the two circles using the values passed as
arguments. Called by the FlockManager class inside the drawAwarenessCircle()
method.
Method: public void paintComponent(Graphics g)
Overrides the paintComponent() method of the JComponent class to draw the circles.
The inner circle (representing minimum separation distance) is coloured red and the
outter circle (representing viewing distance) is coloured white.
6.2.2 ‐ Bird
Extends: JComponent
The swing component representing a generic bird object. This class is never actually
instantiated; instead it is used to define state and functionality common to both its
subclasses: Falcon and Starling.
Method: public void setDirection(int direction_)
35
Checks whether the directional value passed as an argument is within the correct
bounds (between -179 and 180) and sets the mDirection member variable accordingly.
If the direction is not between -179 and 180, 360 is repeatedly added (or subtracted) to
account for angular wrapping, noting that -180 = 180.
Method: public void advance(double distance_)
Uses trigonometry to calculate the new location of the bird given an advancement in the
current direction for a distance matching the value passed as an argument. If the new
location is outside the bounds of the simulation panel in either dimension, the height or
width of the simulation panel is repeatedly added (or subtracted) to account for
coordinate wrapping, noting that -1 = SCREEN_WIDTH and -1 = SCREEN_HEIGHT.
6.2.3 ‐ DynamicSimProperties
Extends: Object
A class used to bundle together the dynamic (also called “behavioural”) simulation
properties: the maximum turning angles for alignment, cohesion, separation, predator
avoidance and random; the metric and topological viewing distances; the minimum
separation distance and a boolean flag representing whether or not the awareness circle
should be displayed.
The advantage of packaging together these properties is that they can be passed around
as a single argument instead of nine. The GUI is responsible for creating
DynamicSimProperties objects (see GUIPanel) but they are ultimately stored inside and
referenced by the FlockManager class.
This class has no methods. All fields are public and are accessed like a C++ struct.
6.2.4 ‐ FPSCounter
Extends: JComponent
The swing component representing the frames per second (FPS) counter. This counter
sits in the top right hand corner of the simulation panel displaying the current FPS in
36
large red text. If the current FPS is unknown, a question mark (?) is displayed instead.
The FPS counter is invisible by default and remains hidden until enabled by the user.
Method: public void setFPS(int FPS_)
Updates the counter with the integer passed as an argument. Called by the
SimulationManager object, where the actual FPS calculations are performed.
6.2.5 ‐ Falcon
Extends: Bird
An extension of the Bird class representing a falcon. Only the task of actually drawing
the falcon is delegated to this class since most interesting functionality was already
defined in Bird.
Method: public void paintComponent(Graphics g)
Overrides the paintComponent() method of the JComponent class to draw the falcon,
which is painted red. The shape of the falcon is defined as a polygon whose vertices I
calculated manually by creating the following template:
37
6.2.6 ‐ FlockManager
Extends: Object
The most important and interesting class in the system, FlockManager is responsible for
keeping track of the birds and updating their positions with respect to the rules of
flocking. Its many responsibilities are best understood by investigating its methods.
Method: public Vector<Bird> getBirds()
Concatenates the list of starlings with the list of falcons to form a list containing every
bird currently in the simulation. This is ultimately required to add the birds to the
simulation panel in the Window object.
Method: private void buildFlock()
Builds the flock by repeatedly creating Starling and Falcon objects before assigning
them random coordinates and directional values. The stored StaticSimProperties
object is referenced to determine the number of required starlings and falcons.
Method: public void updatePositions()
Updates the positions of the birds with respect to the rules of flocking. This is the most
significant of the very few public methods in this class: almost every other method is a
helper function for updatePositions(). It works by first calculating the new steering
values for all the starlings, then for all the falcons. It then draws the "awareness circle"
before finally advancing the positions of all birds.
Method: private void drawAwarenessCircle()
Assuming the user has enabled this feature, this method updates the position of the
awareness circle and paints the surrounding birds pink or white depending on their
proximity to the arbitrarily chosen "target bird". The behavioural parameters required
to perform these computations (such as minimum separation distance) are referenced
from the stored DynamicSimProperties object.
Method: private void calculateStarlingSteering()
Employs the two‐pass system of urge integration to calculate the new steering values of
each starling. The first pass computes the turning values while the second pass effects
38
these turns. It is not possible to fully explain the code here because of how extensive it
is. However, it can be easily understood by making careful reference to the sections on
"combining urges" and "steering processing chains" which can be found in 3 ‐ Some
theory.
Method: private void calculateFalconSteering()
As above, but with falcons instead of starlings. One key difference is that falcons may be
user‐controlled and the code required to handle this case can be found in this method.
Method: private int getValidTurn(Bird bird_, int newDirection_, int
maxTurn_)
Compares the current direction of the bird (given as an argument) with the proposed
new direction (also given as an argument) and decides whether this turn is valid with
respect to the maximum turning value (given as a final argument) and taking into
account angular wrapping. If the turn is valid, it is returned. Otherwise, it is sufficiently
truncated and then returned.
Method: private Vector<Bird> getNearestMetric(int distance_, Bird bird_)
Fetches the set of all birds within some metric distance of a given target bird. This is
achieved by looping through every starling and every falcon and performing a simple
distance comparison on each iteration.
Method: private Vector<Bird> getNearestTopological(int numBirds_, Bird
bird_)
Fetches the set of all birds within some topological distance of a given target bird. For
more detailed information on this function, please refer to 6.3 ‐ Algorithms of interest.
Method: private double distanceBetweenBirds(Bird bird1_, Bird bird2_)
Calculates the distance between two given birds, taking into account coordinate
wrapping. For more detailed information on this function, please refer to 6.3 ‐ Algorithms
of interest.
39
Method: private int angleBetweenBirds(Bird bird1_, Bird bird2_)
Uses trigonometry to calculate the angle between two given birds.
Method: private static int averageBearing(Vector<Integer> bearings_)
Calculates the directional value that can be thought of as the "average" from a given list
of angles. For a more precise definition and further details on this function, please refer
to 6.3 ‐ Algorithms of interest.
Method: private int idealTurnCohesion(Bird bird_, Vector closeBirds_,
boolean ignoreFalcons_)
Calculates and returns the ideal turning value with respect to the cohesion urge. This
works by calculating the "centre of mass" of the neighbouring birds and redirecting the
target bird to face towards this position. Falcons are not considered in the calculations
because neither starlings nor falcons should be attracted to falcons.
Method: private int idealTurnSeparation(Bird bird_, Vector closeBirds_)
Calculates and returns the ideal turning value with respect to the separation urge. Note
that separation is essentially the same urge as cohesion except for two important
differences: the direction is reversed, and we must consider falcons as well as starlings.
Method: private int idealTurnAlignment(Vector closeBirds_)
Calculates and returns the ideal turning value with respect to the alignment urge. It
works by observing the directions of the neighbouring birds and calculating the
"average bearing" of these directions.
Method: private Vector<Falcon> getCloseFalcons(Vector<Bird> closeBirds_)
Extracts the subset of Falcon objects from a set containing a mixture of both Starling
objects and Falcon objects. Uses Java's instanceof operator to differentiate between
friend and foe.
40
Method: private Vector<Bird> getMinSepBirds(Starling starling_,
Vector<Bird> closeBirds_)
Extracts the Bird objects from a list of Bird objects whose distance from the target bird
is less than the minimum separation distance. This is achieved using the same technique
from getNearestMetric() and by referencing the minimum separation distance from
the stored StaticSimProperties object.
6.2.7 ‐ GUIPanel
Extends: JPanel
A large class defining the graphical user interface (GUI) panel. Responsible for laying
out the GUI and dealing with all actions relating to its use. Most of the code was
automatically generated by the NetBeans GUI building tool “Matisse”; I simply
completed the empty callback functions. Some of the more interesting callback
functions perform tasks like reading and writing so‐called “scenario files”. Scenario files
are simply text files containing a list of variables representing the current state of the
GUI, separated by line breaks.
Method: private void enforceBounds(JTextField field_, int lower_, int
upper_)
Ensures the value of some text field is within the bounds specified as arguments. Called
immediately after the user has made changes to a field whose contents must be
validated. Such fields include topological distance (where the lower bound is 0 and the
upper bound is numStarlings + numFalcons - 1) and the max steering angles (where
the lower bound is 0 and the upper bound is 180).
41
6.2.8‐ SimDims
Extends: Object
A globally‐accessible singleton class instantiated by the Window object when the
application is first executed. Used to store the user‐defined dimensions of the
simulation panel. Accessed by any class requiring knowledge of these dimensions,
namely: Bird, FlockManager, AwarenessCircle, FPSCounter, GUIPanel and
SimulationPanel.
6.2.9‐ SimulationManager
Extends: Object
An important interface between the GUI and the FlockManager class,
SimulationManager is responsible for aspects of the simulation relating to timing and
playback. It also keeps track of the framerate for the purposes of updating the value
displayed in FPSCounter.
Method: public void startSimulation()
Starts the simulation by creating a Timer object and scheduling a call to
FlockManager.updatePositions() followed by a repaint every 20 milliseconds. This
means the positions of the starlings are recalculated and redrawn at a frequency of
50Hz.
Method: public void stopSimulation()
Stops the simulation by cancelling the Timer object.
Method: public void pauseSimulation()
Pauses or unpauses the simulation by inverting the value of the boolean flag referenced
in the run() method of the TimerTask object. This has the effect of skipping the call to
FlockManager.updatePositions()when the mPaused flag is set to true, effectively
suspending the simulation.
42
Method: private void updateFPSCounter()
Computes the time elapsed between iterations of the run() method to accurately
calculate the number of frames per second the system is currently running at, before
updating the value displayed on the counter via a call to FPSCounter.setFPS(). This
value should always be 50 if the system is behaving correctly.
6.2.10 ‐ SimulationPanel
Extends: JPanel
This class represents the simulation panel where flocking takes place.
Method: public void paintComponent(Graphics g)
Overrides the paintComponent() method of the JPanel class to draw the sky image
(sky.jpg) onto the background of the panel. Also ensures that components added to the
simulation panel are rendered with anti‐aliasing enabled if the user has requested so.
6.2.11 ‐ Starling
Extends: Bird
An extension of the Bird class representing a starling. Only the task of actually drawing
the starling is delegated to this class since most interesting functionality was already
defined in Bird.
Method: public void paintComponent(Graphics g)
Overrides the paintComponent() method of the JComponent class to draw the starling,
which is painted black. The shape of the starling is defined as a polygon whose vertices I
calculated manually using the template found under the description of the Falcon class.
43
6.2.12 ‐ StaticSimProperties
Extends: Object
A class used to bundle together the static (also called “setup”) simulation properties: the
number and speed of starlings; the number and speed of falcons and a boolean flag
representing whether or not the falcon should be user controlled.
Please see 6.2.3 ‐ DynamicSimProperties.
6.2.13 ‐ Window
Extends: JFrame
This class represents the window object containing the GUI and the simulation panel. It
is also the entry point for the application and as such has a number of key
responsibilities.
Method: public static void main(String[] args)
Parses the command line arguments to extract the dimensions of the simulation panel
requested by the user, before creating a window large enough to house this panel. If no
arguments are supplied, the default value of 800 x 800 is used. The chosen dimensions
are stored in a globally‐accessible SimDims object.
Method: public void addBirds(Vector<Bird> birds_)
Removes all birds previously occupying the simulation panel and replaces them with
the list of birds passed as an argument. Called from within SimulationManager during
its creation.
44
Method: public Window()
Constructs the window and lays out the various components, ensuring each panel has
the correct dimensions. Also creates listeners and defines callback functions to check for
keypresses used to direct user‐controlled falcons.
45
6.3 ‐ Algorithms of interest
The following algorithms required some special thought.
6.3.1 ‐ Calculating the distance between birds
An operation fundamental to modelling flocking behaviour is computing the distance
between two given birds. This isn’t as trivial as it might first appear since wrapping
must be taken into account. Topologically, it is equivalent to calculating the distance
between two points on a torus.
The trick is to handle the x and y coordinates separately, ensuring the lesser distances
are considered in each case. For instance, when the difference in x coordinates exceeds
half the width of the grid, we should instead consider the width of the grid minus that
distance. We then use Pythagoras' theorem to calculate the distance as usual. This can
be understood geometrically as follows:
Incorrect Correct
Here is my implementation of the algorithm:
private double distanceBetweenBirds(Bird bird1_, Bird bird2_){
double deltaX = Math.abs(bird1_.getXPos()
- bird2_.getXPos());
double deltaY = Math.abs(bird1_.getYPos() - bird2_.getYPos());
double minX = Math.min(deltaX, (SCREEN_WIDTH - deltaX));
minX *= minX;
double minY = Math.min(deltaY, (SCREEN_HEIGHT - deltaY));
minY *= minY;
return Math.sqrt(minX + minY);
}
46
6.3.2 ‐ Calculating the average bearing
Computing the optimal turning angle in response to the “alignment” urge requires that a
bird observe its neighbours and decide upon a new direction that best mimics the
overall direction of the flock. The question of how to calculate this quantity, which I
shall call “average bearing”, is made more difficult by the nature in which directional
values are stored, namely as integers between ‐180 (exclusive) and 180 (inclusive). To
illustrate the problem, consider the following:
If we naïvely calculate the average in the usual way, we obtain:
100
120
3
160
20
Intuition suggests this is obviously wrong because it corresponds to the following:
47
The reason for this error relates to wrapping. Whenever the directional values differ by
more than 180, the average bearing is calculated by incorrectly bisecting the "greater
angle" instead of the "lesser angle".
The technique that produces the correct solution works as follows:
1) Compute a unit vector from each angle.
2) Compose these vectors.
3) Calculate the angle between 0 and the resultant vector.
To illustrate this method, we return to the previous example:
It should be noted that in the exceptional case where the resultant vector is 0, the
concept of an “average bearing” doesn’t make sense. For instance, the average bearing
of 90° and ‐90° is undefined.
Here is my implementation of the algorithm:
private static int averageBearing(Vector<Integer> bearings_){
Iterator<Integer> bearingsIt = bearings_.iterator();
int bearing;
double sinAverage = 0;
double cosAverage = 0;
double deg2Rad = Math.PI/180;
double rad2Deg = 1/deg2Rad;
double result;
while(bearingsIt.hasNext()){
bearing = bearingsIt.next();
sinAverage += Math.sin(deg2Rad * bearing);
cosAverage += Math.cos(deg2Rad * bearing);
}
result = Math.atan2(sinAverage,cosAverage);
result = rad2Deg * result;
48
return (int) result;
}
6.3.3 ‐ Calculating the nearest n birds (topological distance)
Calculating the set of birds within some metric distance is trivial because, for any given
bird, a single distance comparison is sufficient to determine membership. If the bird
falls within a certain distance, it is included. Otherwise, it is not. Topological distance
(which considers the n closest birds regardless of actual distance) is more complicated
because the distances of every other bird must be known before one can determine the
membership of any given bird. To facilitate this, an array containing the n closest birds
is maintained throughout the procedure. This array is ordered by increasing distance.
Each bird is considered in turn and the following steps are taken:
1) Calculate the distance from the bird to the target bird.
2) Loop through the array, checking whether the distance is less than any of its
members. If so, insert the bird at the relevant index. Otherwise, discard the bird.
3) When every bird has been considered, return the array.
To illustrate this, please refer to the following code snippet which was taken from the
getNearestTopological() method. Note that a special nested class DistanceBird is
required to store bird objects alongside their distance values. Note also that because of
the frequency with which this method is called, an array implementation was favoured
over a Vector (or any other higher‐level container class) implementation for reasons of
efficiency.
// Check for close starlings
while(starlingIt.hasNext()){
starling = starlingIt.next();
if(starling != bird_){
// Calculate distance
distance = distanceBetweenBirds(bird_,starling);
for(int i = 0 ; i < closeDistanceBirds.length ; i++){
try{
if(distance < closeDistanceBirds[i].distance){
// Shift values along
for(int j = closeDistanceBirds.length - 1 ; j > i ; j--){
closeDistanceBirds[j] = closeDistanceBirds[j - 1];
}
// Insert new value
closeDistanceBirds[i] = new DistanceBird(distance,starling);
break;
}
}catch(NullPointerException e_){
// Insert new value
closeDistanceBirds[i] = new DistanceBird(distance,starling);
break;
}
}
}
}
49
dissertation.pdf (PDF, 2.45 MB)
Use the permanent link to the download page to share your document on Facebook, Twitter, LinkedIn, or directly with a contact by e-Mail, Messenger, Whatsapp, Line..
Use the short link to share your document on Twitter or by text message (SMS)
Copy the following HTML code to share your document on a Website or Blog