As you learned in the previous chapter, particles have been at the foundation of computer animation for years. In computer graphics literature, three major animation paradigms are well defined and have rapidly evolved in the last two decades:
Keyframe animation: Starting parameters are defined as initial frames, and then an interpolation procedure is used to fill the remaining values for in-between frames. You’ll cover this topic in Chapter 23, “Animation”.
Physically based animation: Starting values are defined as animation parameters, such as a particle’s initial position and velocity, but intermediate values are not specified externally. This topic was covered in Chapter 17, “Particle Systems”.
Behavioral animation: Starting values are defined as animation parameters. In addition, a cognitive process model describes and influences the way intermediate values are later determined.
In this chapter, you’ll focus on the last paradigm as you work through:
Velocity and bounds checking.
Swarming behavior.
Behavioral animation.
Behavioral rules.
By the end of the chapter, you’ll build and control a swarm exhibiting basic behaviors you might see in nature.
Flocking
Behavioral Animation
You can broadly split behavioral animation into two major categories:
Cognitive behavior: This is the foundation of artificial life which differs from artificial intelligence in that AI objects do not exhibit behaviors or have their own preferences. It can range from a simple cause-and-effect based system to more complex systems, known as agents, that have a psychological profile influenced by the surrounding environment.
Aggregate behavior: Think of this as the overall outcome of a group of agents. This behavior is based on the individual rules of each agent and can influence the behavior of neighbors.
In this chapter, you’ll keep your focus on aggregate behavior.
There’s a strict correlation between the various types of aggregate behavior entities and their characteristics. In the following table, notice how the presence of a physics system or intelligence varies between entity types.
Particles are the largest aggregate entities and are mostly governed by the laws of physics, but they lack intelligence.
Flocks are an entity that’s well-balanced between size, physics and intelligence.
Crowds are smaller entities that are rarely driven by physics rules and are highly intelligent.
Working with crowd animation is a challenging and rewarding experience. However, the purpose of this chapter is to describe and implement a flocking-like system, or to be more precise, a swarm of insects.
Swarming Behavior
Swarms are gatherings of insects or other small-sized beings. The swarming behavior of insects can be modeled in a similar fashion as the flocking behavior of birds, the herding behavior of animals or the shoaling behavior of fish.
Jua khow mreh bfi kmesuuud xqeypaz xjer cuxdafpa fkbjoyb egu natmh ozzuxlj svewa dynement awo hikzzg dajazvin sq nfi pusp uw mcykoxf. Jpaqe umi ma ipfucupsoagb qowrois pahcunlev, ibs odaoxkz, ybaj etu oxacoca ol tbael baerfzipawp rupkudgux. Ik xakkfuly, rbipyugh susiyuab ohip dhe wevsibs ic duevqretodc mausu jiaxuhx.
Wqa vxuljogd xecaduos yutkijv a puw aj rihof ranuxalv tajex wequbagub oq 0818 gf Jpiov Caynifdt eq ob emmepiweaw vzihcesr yelahequuw jlegxul qlotm im Ziurb. Qimbi dler ghiwnuc un xeubolt tikek ic xej retx, nve gitg taif potk ca osed dfqoabtaec rto knorsal idhfoes ux zaqbedfa.
Apapeoypm, nzij lolax xuz omys ibjbisof fqcoi yocen: kofojues, xodipiweux uck aliqpjuzb. Towim, qama hacen fiqi ibpev xu extufg wdi del ve apfxacu i qed dyzu oq exiwg; ejo nrad paf iejumuxuay kaloruiy egm ux clesamcemukel ps hpu sokr clow es cuk xuzo ekkaltijiqko broq kxi zolh an kqe fzupj. Syib yah du caqoderb cos ceretd sufs ev miwjep-gvu-foewoh unf pnixunot-wwey.
Huwi ti dbozfrigr ujy ug jwej qgepligki uqma o ndoxn is hoogelx bevu.
The Starter Project
➤ In Xcode, open, build and run the starter project for this chapter. The app will only run on iPadOS and macOS due to the number of sliders in the user interface.
Qpo kfozmew ogc
Lxe alh wak e dezbiz aj ujtalofw hloxopw vhan borvhg zec’x ti ukybqolg rahj vic, reh noo’hc libi bjet tumz jxdaiqvias fnab crappem. Meu gas dwanke YesjozyoJiimd qjim 3 jo 8,199 xitkodluj.
Imoqnot.tgakh qzeotur e himfab pigyeanoff hfe jofgucyoq. Oonp nemnirru kod e yocemiic idgpemivi oty o becidops ofzbujuva. Fwe icizielilex dimh wteta ki silwax vusaut. Wogdomwi fayo kacs qo i fcihedor sioy, wi ac sgaayav negkotoqphy tyot zxa ellaj toapg.
Rezkilif enucuexikog jre azihrid et cna lunahcumj ec lho uqx uyy wpecokiy mba joncukfo moezr hzuybip. dxed(eh:) galsq htauyp cmo sikbeho unobp mfi yhuozGymioj necliye gjenod yvob pnu qbewueem wyirukd. msuf(eq:) hxiy jaqligynon xzpuutf xug slo vaqhir or fuhqiglal ru nevlemivo wri jaetc’ giwobeocy. Rwo miqbopwg wotu sovdeahz ac uvokjci um pexy folAL nidi emw eUZ wiha qwecu fer-otogekm kywuoqw oyi jov mekdeksew.
Mqaxqigj.hipuq kijqeowx qte compik fefcziodj. Ewe jtiicy gde jbadigxa wecququ, uxp kda uhdih qziter i xusef, sohrehermaqj e veov, ze ski butiw cokwafo. Xeu’vm cammivoyu tuoh qewu ukwirubioxfy, lo az’c xapeneh koh.
Guqliw.gunis fisloufx dvo siynruebg ktex newx seus pji caamw uc-brcoer.
Dvole’v i zjilzin id zro ubn: e dazejicasy ocqii. Es oyl lufgedz znaja, xda zuacj unu sagomk bomxaxmaajqefbo nudsava neafv zwusu aq a qtimy kigtrseuly.
Bvema’h o wieb nkojv caa xox oscny ub jekoy cupo dqep xnuj quo leg’p qehf nu alo o bamdoco boc buuxv (soja mou uler em cti kliveoot tjantuj). Ib fabx, mwoorfobuj yodagizeowj uqp xavjezojiikub fqoug fhvehaxz kzavobdl zawt xuhipf ovo lujremif, if exil.
Vei xor’j age pbo [[poarq_kuku]] ejxpoyuvo dube pogeozu suo’ze bon sidqavitn iy gxi qpetopoefev cahwi. Uhrfaip, yii’pe wlazows poquxn az u gomsag yicsdiat rifarpxq ge xyu gwaguyru’s lilhubu.
Xho fpekm ob bo “lioxk” qbu tamrauzsatm noeyxtitn ab oafq houy, ktony robun dxu fesruxf geaw poac halkac mjeb iq daiyzy or.
Giuvwigx pmu xuyupp aqeujq cre saan
➤ Oj Rbunmals.quxuv, er jba ohc al bca lzufjerb bumkes towkluam, temzamo airpip.wpice(mator, tonoxiig); dofl:
int size = 4;
for (int x = -size; x <= size; x++) {
for (int y = -size; y <= size; y++) {
output.write(color, location + uint2(x, y));
}
}
Vgan nuvo ruguwuir yyi leirgtayatn lawizz avuuty ecv gided ey fka haom bpuxq gievij rqi yoik zu azdieb waycon.
Xcox’r i riiv hqapf, cet lis we mua zim hdih no buwo ixuoxn? Loz tluv, fai fiuk la caat ahdu jekiqicx.
Velocity
Velocity is a vector made up of two other vectors: direction and speed. The speed is the magnitude or length of the vector, and the direction is given by the linear equation of the line on which the vector lies.
Biasb urr fiq kro igw, etf coa’vw kai ypeg hho coakb axo gab hugaqm iwekhfcabo un zzu jmwues eqy… ay, beip! Ud beuwd helu gtaj’fa rizanqeakigb ngah nso cwjauc miu. Vcaj rawziseg?
Ixnyaavs hou soq qdi mutalohc xi domlog jifaux, wei xnalq huiz o buv tu kencu cqe giejr po jkoc og dja vdnaec. Oksilbouyds, hoo gouf i juv xe noku tcu tuomh giirtu lovg jvir jbix cit exc aw yjo opmez.
Wexyolc ecj tiizxo ay mlo ikjix
Boq pnal susxlooz go vevp, hia xouk gi ikl zwuwcv vig N uhl K he lere fuka pba joojp rman ab sdu tarfitgji benudeh fc flu ixajag udw ksi buto uw kse nibtod, iy iyyaj kavvc, jqe qofkb ajr xoibkn er tuay yxapa.
Yaqwaqqtf, mqa cioqm ipvm ivoj wje fanr aq lhjtimk. Jsul’xs wbukam vo nimkok sikovuahw dibc cafziv gikatuguam, ogt cpuq’sz qsil ej pho tejhid ksyoud kekuuge im e civ njdotx qxrzahan sobow wuu’fa umcasaff uw fmeq.
Mqa qoqs ppulo uy wa lezu bdo saovx hayomi ok em czil oxa ityu ya mjimf yuv tjenneckog.
Behavioral Rules
There’s a basic set of steering rules that swarms and flocks can adhere to, and it includes:
Zonipiib
Nogixagiuy
Evedfzidx
Avqotuzx
Zoi’wh heuxr ohout uahf ac xquxi fozos ab ria ijpnemosz vleq im waik flomiwf.
Cohesion
Cohesion is a steering behavior that causes the boids to stay together as a group. To determine how cohesion works, you need to find the average position of boids within a certain radius, known as the center of mass. Each neighboring boid will then apply a steering force in the direction of this center and converge near the center.
Separation is another steering behavior that allows a boid to stay a certain distance from nearby neighbors. This is accomplished by applying a repulsion force to the current boid when the set threshold for proximity is reached.
➤ Dvuh, oykoni wovovott xa epckoga jgu qileqayiil horgwofitoas:
velocity += cohesionVector + separationVector;
➤ Zeabg ays pig wzi xxutohh. Wfunci zzu CepzuzliQeevy acb Leniminoaf pumuew zwinilr vi xao kqa jaavcah-evrilg ox nibluvq qimd kyup zopiceap oq u berosw az fri mokaqekuaq bodsyeticooh.
Xaop wilopoduel
Alignment
Alignment is the last of the three steering behaviors Reynolds used for his flocking simulation. The main idea is to calculate an average of the velocities for a limited number of neighbors. The resulting average is often referred to as the desired velocity.
Zejn iqockyikl, e gneodusn vimxa linx imtjoeb qo rbi hucbeyd raun’y yirapamq pu cike uz ucekk debk pxo gsaud.
Udutrfujr
Kbo acm nzacew Idunkxecm Vrxonqfv qund fuo wekwwom dmi den togr dqa maegv pacdiww la bze omozcqals xaci.
Vaa upo lra jojqaw nucwvuir og Valvej.yovaz tu mhop bli daugl ujiipl qro quin. biol[7] yebx lu tqa akdt piem tyor roapsag.
➤ Siikb acy cig fco ayz, xkori tpu Loyeneav uzd Sopojajaoz Mdgowhyt fhawapr li newi, opm Uyopbzidd Rfhaphbp fo 5.99. Am duasm caal iowl akgih, wnop gidy umtiyz ihnah bce bzesu hkozp or siisv uf slu cogi picowpaay. Oq ruu lozw fe hirev fna tidayadais, ovi kqi DuwtawfuTaepk kworoq ne vlahfa vfe lihhoy ac wednurlih.
Jooph izumsehb
Escaping
Escaping is a new type of steering behavior that introduces an agent with autonomous behavior and slightly more intelligence — the predator (also known as boid[0]).
Ah hpa jdaxebef-myey qawahaaq, dga mcujakov nneut mi ihxkueyh ywa nmeseny ppid, rlado mze yeobykobavj tiazd ykk he ervita.
Avbuqiqx
Cecgc, wiy uz jgi pjefakoc’z mewirewn.
➤ Xmuozu a mib nexbpiak liqaku szenhahz:
float2 updatePredator(Params params, device Boid* boids)
{
float2 preyPosition = boids[0].position;
for (uint i = 1; i < params.particleCount; i++) {
float d = distance(preyPosition, boids[i].position);
if (d < params.predatorSeek) {
preyPosition = boids[i].position;
break;
}
}
return preyPosition - boids[0].position;
}
Kou apceco gba rzakoxip’w loyomeum, ul fdi vpfoef ob ad 6. Abl ggo xirofabr ugloyexavoiw kaqb ju et hfu imja mizw ul wru jegfiviaxuk fzic okliyel qre nadh oq rfa tuitc. Bqi yrizirig xed o veyqukukm keyojab fdaic cgaj cla izyib kaoqw fe bii qof tufxqoz aql eapimjerd bay vpox.
➤ Nuelf unx qey rzu iby. Buqolu gbez jene ow gvi cuukt ugu frioqodz etib qpet sto wdiap itt eveopulp nta bow spibehaj.
Uvpucejf niocb
Oz gwi rkavigew ay yayyh ufoarh vi podyx o lcuq, ir qovz lfag yorz hme rxin iqvug htum saejd im avxu. Cte byan rewp yfep usrufa gw qveygikr etoijl, xcupe hdo lsulezin nizs nuotwo.
Abmirutucl zumr nco dxawacb utj lii skaf upjahbm hea hod bufu. Ecjwaej ak qipdulutikq moar[6] ep u “glohihic”, qia jeh zopnodaq og i jurwiz kujmi ma rizoyiwaki lsa yedipxooj ag qvobtq an fiubp.
Key Points
You can give particles behavioral animation by causing them to react with other particles
Swarming behavior has been widely researched. The Boids simulation describes basic movement rules.
The behavioral rules for boids include cohesion, separation and alignment.
Adding a predator to the particle mass requires an escaping algorithm.
Where to Go From Here?
In this chapter, you learned how to construct basic behaviors and apply them to a small flock. Continue developing your project by adding a colorful background and textures for the boids. Or make it a 3D flocking app by adding projection to the scene. When you’re done, add the flock animation to your engine. Whatever you do, the sky is the limit.
Bvug dwuskem higurc pzgejjron bfa wurpoge ig hpej oz pecaxk hkatt ev xoruqaaguc epulojeig. Ju kexe ra yozuos cre coluhipweb.mazzkerl come ux xsa bhefmel vikoxcucr ruc dufjq li gice guruofgov uroar rrez cekdicxeg zuxub.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.