Flocking response of sheep to a herding dog Laurea Magistrale in Informatica Author: Paolo Bonomi Academic year: 2021-2022 1. Introduction This paper describe how the Reynolds’ flocking model is adapted in order to simulate herd behaviour of sheep. Reynolds defines a set of three simple rules, that model the complex behaviour of a flock. These rules are applied independently to each entity in the flock. The result achieved by Reynolds is that each simulated entity (in his case he’s talking about birds) is implemented as an independent actor that navigates according to its local perception of the dynamic environ- ment, the laws of simulated physics that rule its motion, and a set of behaviors programmed into it by the ”animator”. [4] In addition to Reynolds’s model this prototype defines two more rules one describing how simulated sheep react to a herding dog, the other how them avoid boundary walls. All five rules are going to be discussed in the next sections aside from the implication inferred from real world sheep’s behaviour, because the way to simulate an animal behaviour correctly not only stands in the use of a correct model, but also knowing most of it’s behaviour facets. I contrast with the Raynold’s three dimensional model this system uses only two, issue that must be take into consideration but can be easily solved. 2. How does a sheep think? Sheep are a prey species, and their only defense is to flee. Sheep display an intensely gregarious social instinct that allows them to bond closely to other sheep and preferentially to related flock members. Flock mentality movements protect individuals from predators. Flock dynamics are apparent in groups of four or more as evidenced by willingness to follow a leader or flee in unison. When escape is pre- vented, even a ewe may charge or threaten by hoof stomping. Separation from the flock can cause stress and panic. [1] Sheep are animals which behaviour can change based on feeling emotions, therefore the more fear that affects the animal, the more it wants to stay together with the group and escape from a potential threat. In the next section it’s proposed a way to simulate this fear based on the distance of the animal from predators. 2.1. Fear factor Given the fact that no one sheep is equal to another (Dolly is the only exception) we can presume that due to many factors each sheep has its unique way to interact with the environment. This hypothesis brings necessity to introduce in- side the simulation a factor that non only repre- sents how a sheep is going to react to an immi- nent threat but also creates diversity between el- ements of the flock. This Fear factor [1] is unique for each sheep and depends to its perception ra- dius r , the distance from the wolf x and the softening constant m The radius an the con- stant is different from each individual and is set at initialization. 1 Executive summary Paolo Bonomi 0 50 100 150 200 250 300 0 0 2 0 4 0 6 0 8 1 m = 75 m = 30 m = 10 Figure 1: Fear [1] function with different values of m . The x-axis is the distance from the wolf and the peception radius r in this case is fixed for all at 320 F ear ( x ) = arctan ( r − x m ) 2 π (1 + m 500 ) (1) where: r ∈ { a ∈ IR | a > 0 } x ∈ { b ∈ IR | b ≥ 0 ∧ b ≤ r } m ∈ { c ∈ IR | c > 0 ∧ b ≤ 30 } During simulation each sheep is going to ini- tialize m with a random value within the ac- cepted range and adjust its perception radius r in a neighborhood of its default value. This two tricks ensure biodiversity inside the flock and grants a realistic overall looking of the system. In addition, all the denominators are com- puted once at initialization using the relation- ship x/y = x ∗ 1 /y ( avoiding divisions increases system’s speed). 3. Steering Behaviours Steering behaviors aim to help autonomous characters move in a realistic manner, by using simple forces that are combined to produce life-like, improvisational navigation around the characters’ environment. They are not based on complex strategies involving path planning or global calculations, but instead use local information, such as neighbors’ forces. Every physics object has a velocity represented with a vector, it defines in which direction and how much fast the object is moving. Steering behaviours are functions that can change this velocity according to some logic, their combination simulate the behaviour of the sheep and them are combined using an online weighted blending. This means that vectors are multiplied by weights updated during the simulations. If a weight is equal to zero it’s possible that also the velocity assigned to that specific steering behaviour is set to zero. Renyold’s model defines three rules: Alignment, Cohesion and Separation. This system adds two more called Flee and Avoid Walls. All these rules uses different parameters such as the perception radius, minimum distance threshold, ecc. and are analyzed in their respective subsections. The function that blend all these contributes together is called Step function. Before diving into the math it’s better to define some conventions: pos = position of the current sheep pos i = position of the i -th sheep of the flock pos w = wolf’s position vel g = global velocity of the current sheep vel g i = global velocity of the i -th sheep of the flock vel j = velocity associate to the j -th rule of current sheep vel ij = velocity of the i -th sheep of the flock associate to the j -th rule s c = Cohesion steering vector of current sheep s a = Alignment steering vector of current sheep s f = Flee steering vector of current sheep s s = Separation steering vector of current sheep s w = Avoiding walls steering vector of current sheep The steering vector is obtained with this formula s = d − v In other words the steering vector is the subtraction of the velocity to the desired velocity. 3.1. Step function The systems uses different vectors describing ve- locities: one for each rule and one for the global velocity. In this way all rules acts separately and the final velocity vel g is obtained blending together vel j for each j The system’s physics model is based on an over- simplification of the Verlet integration where: acc ← applyF orces () vel ← ( vel + acc ) ∗ drag pos ← pos + vel 2 Executive summary Paolo Bonomi The rendering speed is fixed at 30 frame per seconds, this gives the possibility to not include ∆ t in the model. Physics simulation is not intended to be a core function for this project, therefore this kind of simplification are well accepted in order to dedicate more time tuning sheep’s behaviours. The Step function [1] applies these physics model along with a velocity threshold check that set to zero all the contributes below a certain threshold. The algorithm is pretty straight-forward and can be divided in two parts. The first one (line 1-2-3) iterates through all the flock computing for each rule the vectors s ij , the second one for each sheep updates the velocities vel j with s j , then vel g with each vel j and finally the pos used in the next rendering step with vel g Algorithm 1 Step function 1: for each i ∈ Sheep do 2: for each j ∈ Rules i do 3: s ij ← F ij () 4: for each i ∈ Sheep do 5: for each j ∈ Rules i do 6: if || vel ij || < threshold ij then 7: vel ij ← vel ij ∗ 0 8: vel ij ← Limit j ( vel ij + s ij ) 9: vel g i ← vel g i + vel ij 10: vel g i ← G ( Limit g ( vel g i )) 11: vel g i ← vel g i ∗ (1 − drag i ) 12: if || vel g i || < threshold g i then 13: vel g i ← vel g i ∗ 0 14: pos i = pos i + vel g i 3.1.1 Limit function The function Limit j takes as argument a vector and limits its length to a predefined value. For each rule j is defined a value that’s the same for all the sheep, vel g instead is capped taking in consideration also the fear factor, resulting in a faster animal when the wolf is closest. 3.1.2 G function This function improves the realism of the system, simulating how a four-legged animal w v u Figure 2: Effects of the G function. Vector w inside the blue area remains unchanged. Vector v outside the blue area is shortened and rotated. The resulting output vector giving v as input is u can move, not allowing it to move backwards. The function G takes as argument a vector v and the threshold angle t . It computes the an- gle α between v and the forward vector of the sheep. If α > t then the length of v is decreased gradually reaching 0 when | α | = 180. Then v is rotated ensuring α = ± t 3.2. IsInMyView function It’s necessary to define the meaning of local perception before diving into those functions depending on it. This property takes into consideration: pos , the perception radius r and a angle of view α The radius r can be different from rule to rule, for example (3000, 3200 and 200 respectively for Cohesion, Flee and Separation), instead the angle of view α is set to 275[3] for all the rules. The combination of these two parameters is used by the IsInMyView [3] function to check if a flock-mate or the wolf is perceived. As said the radius r has different values that are chosen empirically studying the model and it’s visual appearance. 3.3. Cohesion Cohesion is steering towards the average po- sition pos 0 of local flock-mates. To increase the realism this behaviour is weighted with the Fear function, this simulates an animal that in case of danger is more attracted to the center of the flock. The following equations shows how the system computes it: 3 Executive summary Paolo Bonomi α Figure 3: Visual example on how the local per- ception works. Angle α is equal to 275, the red boxes are taken into consideration for furter op- erations, the gray one is ignored. 0 20 40 60 80 0 0 2 0 4 0 6 0 8 1 m = 2 m = 5 m = 8 Figure 4: The Squash [2] function with different values of m x -axis shows the distance, y -axis shows the result of the function. s c = d c − vel c d c = v || v || ∗ Squash ( || v || ) ∗ F ear ( pos ) v = pos 0 − pos The vector pos 0 is obtained adding together all the positions pos i of local flock-mates and di- viding it by the total number of them, the mag- nitude of the desired vector d c is set using the Squash [2] and the Fear function [1] . The steering vector s c is calculate wit the formula explained before in the Steering section [3] Squash ( x ) = ( x r ) m (2) where: r ∈ { a ∈ IR | a > 0 } x ∈ { b ∈ IR | b ≥ 0 ∧ b ≤ r } m ∈ { c ∈ IR | c > 1 } The Squash function as shown in the figure [4] takes as input the distance x = || v || re-scaling it in the interval [0 , 1] in relation to the radius r and a factor m . Once again this factor m can be different from sheep to sheep or equals to all, in this particular case the systems uses a fixed one. 0 50 100 150 200 250 300 0 0 2 0 4 0 6 0 8 1 m = 2 m = 3 m = 5 Figure 5: The negative Squash function with different values of m x -axis shows the distance, y -axis shows the result of the function. 3.4. Alignment Alignment is steering towards the average heading of local flock-mates, also these rule is conditioned to the fear felt by the sheep. The desired vector d a is simply computed averaging all vel g i for each sheep i and multiply it by the Fear function. The result is a higher speed when in proximity of the wolf, and d a = 0 when the wolf isn’t there. This last step grants the sheep to reach an idle state when not in danger. The steering vector s a is calculate by the sub- traction of vel a to d a 3.5. Flee Flee is steering away from a position in this case pos w This rule is active if the position of the wolf is inside the local perception of the sheep. The desired velocity vector d f is calculate by multiplying the vector v (the vector pointing to pos from pos w ) for the negative [3] of the Squash function along with the Fear function passing as parameter for both || v || negSquash ( x ) = 1 − Squash ( x ) (3) where: r ∈ { a ∈ IR | a > 0 } x ∈ { b ∈ IR | b ≥ 0 ∧ b ≤ r } m ∈ { c ∈ IR | c > 0 ∧ c < 1 } The formula of the steering vector is: s f = ( v ∗ negSquash ( || v || ) ∗ F ear ( || v || )) − vel f 3.6. Separation Separation is steering to avoid crowding local flock-mates. This is the most intricate function 4 Executive summary Paolo Bonomi 0 5 10 15 20 0 0 2 0 4 0 6 0 8 1 m = 0 2 m = 0 3 m = 0 4 Figure 6: The Fade Out function with different values of m x -axis shows the distance, y -axis shows the result of the function. to set up in order to achieve a realistic herding behaviour. This steering behaviour uses the following Fade- Out function in order to decrease the strength of the desired velocity vector based on it’s magni- tude relatively to the separation perception ra- dius r as shown in figure [ ?? ] f adeOut ( x ) = e − mx (4) where: e = lim n →∞ ( 1 + 1 n ) n r ∈ { a ∈ IR | a > 0 } x ∈ { b ∈ IR | b ≥ 0 ∧ b ≤ r } m ∈ { c ∈ IR | c > 0 ∧ c < 1 } To compute the desired velocity is checked first if the flock-mate i is insider the local perception, if it’s so d s is computed as the vector pointing to pos from pos i Than d s is averaged by the number of flock-mates perceived and at last is weighted with the FadeOut [4] function and also with the negation of the Fear function. Then the resulting d s is constrained using the G function with α = 45. This ensures a more realistic behaviour and movement smoothness. The formula for the desired velocity vector is: d s = G ( avg ∗ F adeOut ( || avg || ) ∗ (1 − F ear ()) , α ) 4. Avoiding Walls In real word captive animals like sheep are constrained within certain boundaries and this simulation makes no differences having the screen’s bounds act like a fence. Therefore a fifth behaviour modelling an active response to world’s bounds needs to be added to the model. This steering behaviour uses the normal n of the surface of object that act as obstacle. In this simulation. only planes are taken into considerations but the algorithm can be easily extended to other shapes. Ray tracing is used to detect if an obstacle is near the sheep. The system uses adaptive fan angle, with one long ray cast and two shorter whiskers. If an obstacle is detected then the reflection vector v of the ray is multiplied using negative squash function [3] and added to the desired velocity d w . If the sheep is really close to the obstacle weights used for Cohesion and Alignment steering behaviour are also decreased to encourage dispersion. Avoiding collision with walls is one of the hardest feature to implement using steering behaviour. In fact it was not possible to obtain an optimal solution for this problem due to the so called corner-trap. The system has been tested using implementing two specific corner-trap avoidance code [2]. The First technique involve using adaptive fan angle, the second one was a anti-corner-trap code where if a corner-trap is detected only one ray is considered. Given that none of the proposed solution solved the problem, the simplest way to resolve the problem is adding invisible walls in the same position corner-traps are to break the hard ninety-degrees angle creating a smooth one. 5. Physics Collision detection is one of if not the most con- suming operation involved in simulations where there are several dynamic objects in the same scene. In order to improve drastically the num- ber of total simulated object, the systems do not use any advanced collision detection tech- niques. The proposed solution is an over- semplification of a collision solver. In the sub- section Conclusion [7] this and others optimiza- tion are discussed. 5.1. Collisions Collision handling it’s not a core part of this project, but happens to be necessary to find a 5 Executive summary Paolo Bonomi Figure 7: Flock without the presence of a preda- tor. Sheep maintain a minimum self space be- tween each others. Figure 8: The flock compacting and showing mutual movement direction in presence of a predator. solution to overlapping sheep due to the lack of a physics simulator. This is not classified as a steering behaviour because it simply translate the position of the sheep in case of overlapping. To gain performance this function is applied taking into consideration only the set of sheep that triggers separation. First the position adjustment is computed taking into consideration all the sheep overlapping the current one, then pos is updated. This function is repeated more then one time each frame to ensure a certain level of convergence. 6. Results When the simulation starts, and the predator is far away from the flock, sheep reach a relaxed state where all are pointing in different directions and are spread evenly in the space as Figure 9: Sheep avoiding boundary wall while fleeing from predator and showing common flocking behaviour. shown in figure [7] . In this scenario Fear factor is equal to zero and therefore sheep don’t assume nor cohesion neither alignment behaviour. As the predator approaches sheep start to flee from it increasing the will to stay clumped together and sharing a common movement direction while not overlapping with each others as shown in figure [8] It’s possible to spot sheep with different colors from light for younger sheep to dark grey for the older ones. This was made to create differ- ent behaviours, sheep with lighter color can be scared easily and are slower than the dark one. In case of walls the flock is going to avoid it [9] . In this demo there are still corner-trap that causes an unrealistic behaviour. 7. Conclusions The system is robust and can be easily ex- panded with more behaviours, right now it is able to handle something more than hundred sheep with respect of the device that’s running it. In order to improve the system’s scalability and performance two major additions are proposed: shaders to optimize rendering and Partition tree to speed up local perception procedures. Results shows a realistic simulation that is not completely perfect, it lacks of some emerging behaviours like the sheep cyclone ( takes effect when a threat is in the local perception and is also near the center of the flock causing sheep 6 Executive summary Paolo Bonomi to run around it thanks to their cohesion ) and doesn’t respond well to environment’s bounds ( this can be mitigated defining bounds that fit the model such as circular fences instead of squared ones) as explained in Avoiding Walls’ section [4] References [1] Sagi Denenberg Gary M. Landsberg. Social behavior of sheep, 2014. [2] Ian Millington John Funge. Artificial intel- ligence for games, 2009. [3] Jennifer Laffan. Sheep agskills: A practical guide to farm skills, 2005. [4] Craig W. Reynolds. Flocks, herds, and schools: A distributed behavioral model, 1987. 7