[image of digits]

Flocking - Borland C++ Builder 6 Applications
Do not assume that all code blocks in any one application are entirely compatible with the code in other applications.
Please verify the compatibility yourself before you cut-and-paste.

Canvas->Polygon Agents - Version 11 - 3D (a work in progress)

Converting Version 10 to 3D is conceptually straightforward, but in practice, a bit more difficult.
(Much of the difficulty arises in coordinating user choices with functions and renderings.)
This 3D version is unfinished, but it does illustrate where we can go with the enhancement.
The depth of the world is set to the same as the height of the monitor.
The visualization of depth is foreshortened, because otherwise one's eyes have difficulty converging.
The agents do move in 3D. The agents perceive in 3D.
However, their directions and velocities are still only calculated in 2D. (This needs to be added.)
Also, the rules need to exclude 3D calculations when the visualization is not anaglyphic.
Rendering the agents needs to allow for a uniform size, or a size decreasing with depth.
A Pen->Width of 2 enhances the visualization, but slows computation considerably.
A Pen->Width of 3 creates artifacts on the screen.


Flocking Images by Julie Stevenson, Fall 2010


Flocking Polygons by Matt Newcomb, Fall 2010


Flocking Polygons by Yang Su, Fall 2010


Flocking Polygons by Amy Peniston, Fall 2010

   

Canvas->Polygon Agents - Version 10 - Full Screen - Multiple Timers

This application automatically expands to the size of the display:
Form1->AutoSize = false;
Form1->BorderStyle = bsNone;
Form1->WindowsState = wsNormal; *
Form1 and PaintBox1 sizes are set to MonitorHeight and MonitorWidth.

Since the standard Windows controls do not appear:
Event handlers must be created to execute Form1->Close().
A PopUp Menu is used to show and hide the controls.

To make the application run with continuously varying parameters:
Nine timers control the positions of nine TrackBars.
The suspect population timer has been dis-enabled.*

*wsMaximized appears to have caused the Access Violations in the previous version #9.

Canvas->Polygon Agents - Versions 7 & 8

Variable and function names have been made more intuitive. Coloring has been improved. Trails may be displayed without the Pen->Color = clBlack;. Agents may be colored by their speed, location or number of neighbors in their perceptual radius. TrackBars for Perceptual Radius, Independence and Variance. Rules include Nearest Neighbor, Weighted Neighbors within a Radius and Follow the Moving or Fixed Cursor. Left-click to "fix" or "unfix" the cursor position as the target.

Try this: Set color to speed; set rule to follow; set independence to high. Stir up the agents by leading them with a large circular motion of the mouse. Once the agents are in sync, quickly fix the cursor target in the center of the paintbox with a left-click. Now you can use the Mouse to adjust the other parameters.

Try this: Set color to speed; set rule to follow and fix the cursor target in the center. Slide independence trackbar to 0 until all agents are churning nicely at the center, then quickly slide it to maximum. Watch the oscillations which will become more subtle you press Reset.

Version 7 - Manually Controlled
(User sets all parameters)
Version 8 - Automatically Controlled
(Multiple timers set parameters)

Canvas->Polygon Agents - Version 5

The agents are represented as Canvas->Polygons pointing in the direction of travel and with sizes based upon their speed. Instead of velocities, agents are given the distance they travel per timestep in the X direction (dX) and in the Y direction (dY). Three options for coloring are included. Two functions for agent interaction are included. What functionality must you add to give the agents more realistic behavior?

Canvas->Rectangle Agents - Versions 2 and 3

Wandering squares is an attempt to add more power to the simulation, to make it run faster and with more agents. It takes many more computer cycles to move TImages around. In contrast, drawing squares on the canvas and erasing them is orders of magnitude faster. In fact, drawing a square is ten times faster than drawing circles. Additionally, instead of the velocities and directions given to agents in the "Flocking" series, which need to be reduced to their components with each time step, the "Wandering Squares" series simply uses the change in the x and y directions, dX and dY in the code, as the steps each agent will use per time step.

This is a demonstration version, which will run smoothly if you don't change the size of the squares. Feel free to add code to give agents more realistic behavior...

Version - 2 - 21 October 2009
2000 Canvas->Rectangle Agents in a 700 x 700 world.
Window size is 990 x 758 pixels.
This is the highest resolution for default settings.
Agents may be probed and colored.

Version - 3 (new and improved) - 26 October 2009
1000 Canvas->Rectangle Agents in a 900 x 900 world.
For a screen resolution of 1280 x 960.
This is the highest resolution that can be projected.
Agents may be thrown and slowed.

2000 Wandering Squares - Version 1

Wandering squares is an attempt to add more power to the simulation, to make it run faster and with more agents. It takes many more computer cycles to move TImages around. In contrast, drawing squares on the canvas and erasing them is orders of magnitude faster. In fact, drawing a square is ten times faster than drawing circles. Additionally, instead of the velocities and directions given to agents in the "Flocking" series, which need to be reduced to their components with each time step, the "Wandering Squares" series simply uses the change in the x and y directions, dX and dY in the code, as the steps each agent will use per time step.

Almost all the activity of this simualation has been written into the class structure. Also, in contrast to the flocking simulations below which use TImage or TShape objects, the agents in this simulation use Canvas draw commands. Interestingly, Canvas->Rectangle() executes about ten times faster than Canvas->Ellipse() which allows for a huge number of agent visualizations. This is not surprising since a circle is composed of many more line segments than a square.

Flocking 24a - Revised 18 March 2010

Version 24a contains a variable name change from "kind" to "sex" in the two "Couples" rules in order to make it fun properly. Otherwise, this is the same as version 23 except that the alien has been removed, more agent types have been added and the chairs will only show when rule 10 (Musical Chairs) is checked. The "agents" array now serves the double purpose of representing "persons" (from 0 to INIPOP) and "chairs" (from 90 to MAXPOP). The "persons" are at the bottom of the array and the "things" are at the top. This permits the same functions such as directionFromTo(), to be used for both "persons" and "things." The program initializes with more "persons" than "chairs" "Persons" seek out the nearest empty "chair." Both "persons" and "chairs" know that they have been sat in which prevents other "persons" from seeking them out. "Persons" with no "chairs" wander aimlessly. The same sub-variables are available for both...

Flocking 23 - Version "W" - Musical Chairs - Revised October 29, 2009

The "agents" array now serves the double purpose of representing "persons" (from 0 to INIPOP) and "chairs" (from 90 to MAXPOP). The "persons" are at the bottom of the array and the "things" are at the top. This permits the same functions such as directionFromTo(), to be used for both "persons" and "things." The program initializes with more "persons" than "chairs" "Persons" seek out the nearest empty "chair." Both "persons" and "chairs" know that they have been sat in which prevents other "persons" from seeking them out. "Persons" with no "chairs" wander aimlessly. The same sub-variables are available for both...

The "Banking" rule and all references to it have been deleted. Because of the introduction of an "alien" individual, the "couples" rule does not work, and needs to be modified to function well.

Flocking 21 - Version "U" - Revised October 21, 2009

The playing field has been enlarged to better fit the default resolution of the Classroom #6 computers. Otherwise, it is the same as version 20. A "Kill" button has been added to reduce the number of agents. The Timer is now always enabled and the timer interval can now be adjusted with a TrackBar. The findNNeighbor() and findNThing() fuctions' names have been modified to findNNeighborTo() and findNThingTo() for clarity. Additionally, the findNThingTo() function has been repaired and modified to ignore the COIN.

With regards to behavior #10, previously called "Banking" and now called "Bank," the code block within the Timer which moved the targets (the two banks) at regular intervals, has been moved to a new function called moveTargets(). A RadioGroup has been added to call moveTargets() either by "Time" (the Timer interval) or by "Dist" (the distance of some agent from either of the two bank targets). Two options for the "arriving" agent were tried. The first behavior moved the targets when the first agent arrived at either bank. Since most agents never got to the bank, that code was commented out. The second behavior moved the targets when the "last woman" (the woman with the highest Tag) arrived at either bank. The second behavior is the one that is retained in the present version. The "last woman" may in fact arrive first. Although she takes the most indirect route, here velocity may be higher than the others. In "wrap" mode some agents may never arrive. In "bounce" mode they always arrive. The "reset" button will also move the targets to prevent the agents from getting "stuck."

Flocking 20 - Version "T" - Revised April 2, 2009

A "Kill" button has been added to reduce the number of agents. The Timer is now always enabled and the timer interval can now be adjusted with a TrackBar. The findNNeighbor() and findNThing() fuctions' names have been modified to findNNeighborTo() and findNThingTo() for clarity. Additionally, the findNThingTo() function has been repaired and modified to ignore the COIN.

With regards to behavior #10, previously called "Banking" and now called "Bank," the code block within the Timer which moved the targets (the two banks) at regular intervals, has been moved to a new function called moveTargets(). A RadioGroup has been added to call moveTargets() either by "Time" (the Timer interval) or by "Dist" (the distance of some agent from either of the two bank targets). Two options for the "arriving" agent were tried. The first behavior moved the targets when the first agent arrived at either bank. Since most agents never got to the bank, that code was commented out. The second behavior moved the targets when the "last woman" (the woman with the highest Tag) arrived at either bank. The second behavior is the one that is retained in the present version. The "last woman" may in fact arrive first. Although she takes the most indirect route, here velocity may be higher than the others. In "wrap" mode some agents may never arrive. In "bounce" mode they always arrive. The "reset" button will also move the targets to prevent the agents from getting "stuck."

xxxxx

Flocking 18 - Version "R"
Flocking 19 - Version "S" - Revised April 1, 2009
The "Add" function has been corrected. The genders and images of added agents now match. The "boundary" and "behavioral" sonification choices on the menu have been corrected so that the two types of sounds will not run simultaneously. The menu "checked" properties have been modified to reflect that change. Some new, non-human agents have been added to the end of the array of agents. For lack of a better word, let's call them "things." The things are two banks and a coin. Every few seconds, half the population goes towards each bank, which periodically changes location. Moreover, no one goes towards a bank directly. Let's say they are attracted to the direction of the bank. And in order to produce an interesting visualization of their paths, everyone is influenced by a slightly different degree. A lot of fine tuning was required to get all the images to appear in their proper places and times and with the proper layering. This could be the beginning of a number of goal-oriented behaviors. It is ready for some additional behavioral tweaking, since most of the housekeeping has been taken care of.

Running this simulation in the "bounce" (not in the "wrap-around") mode seems to reduce odd behaviors.
The nearest neighbor function has been rewritten for clarity.
A distanceFromTo function has been written.

Flocking 17 - Version "Q" -: Revised March 23, 2009
A traditional drop-downWindows menu has been added to free up real estate. The user choices that are least-likely to be changed frequently have been placed in the menu. Those subject to frequent change have been kept. The controls have been grouped more logically. The agent probe now reflects total encounters. The sonification for "Couples" has been changed from .wav to MIDI and the movement for "Gay/Lesbian Couples" has been corrected. Buttons have been added for 3d paths, but have not been implemented.

Flocking 15 - Version "O" -: Revised June 1, 2008
The direction interactions have been corrected to simulate more realistic interactions and to eliminate directional bias. A new agent variable has been added called "seeking" which is randomly filled with the identities of the other agents. In Rule #5, the agent's direction is modified by the direction to the agent-being-sought. Two variations are illustrated below. In these examples, "seeking" has been assigned randomly. If "seeking" is assigned non-randomly (e.g. hierarchically) and appropriate changes are made to the behavior, more complex networks of intereactions may be developed.

Flocking 15
Some tests of the directionFromTo() function:

xxxxx
Agents' paths colored by iteration.xxxxx Agents' paths colored by tag (id).
Rule #5 is based upon variations of the following statement:
agent[i]->direction += 0.002 * directionFromTo(i, agent[i]->seeking);

xxxxx
Agents' paths colored by iteration.xxxxx Agents' paths colored by tag (id).
Rule #5 produces "like moths to a burning flame" behavior if it is replaced by the following statement:
agent[i]->direction = 1.0 + directionFromTo(i, agent[i]->seeking);

Flocking 14: Revised May 26, 2008
Five agent types are now automatically created (Cyan, Magenta, Yellow, White & Black). Three more agent types are available (Red, Green & Blue) but are not implemented. The agent->type is shown in the probe on MouseMove.

Flocking 13: Revised May 23, 2008
The couple's behaviors have been made reciprocal. Each agent now remembers each of their encounters with all the other agents during the couple's behaviors. MouseMove will display all encounters of an individual agent with every other agent. A new button provides a visual display of every agent's encounters with every other agent.

Flocking 12: Revised May 19, 2008
The default representation of space has been changed to a toroidal (wrapped) world and all the neighbor functions reflect that representation. An "add agent" feature has been added and the simulation will accommodate 100 agents. Sounds have been added to many user commands and to the "couples" behaviors. The "Corner" button moves the selected Shapes and Images to the upper-left corner but does not effect the positions of the agents.

Flocking 11: Revised and Simplified
Retains all the functionality of the previous versions. The code has been cleaned up. The colorRamp() function has been revised. Agents' paths (trails) are recorded. Shapes are ready to display any agent information. To speed up the simulation, movement of the images and/or the shapes may be turned off.

Flocking 11

xxxxx
Agents' paths colored by iteration.xxxxx Agents' paths colored by tag (id).
With the rule set to "decrement direction by that of your nearest neighbor," the time increment set to minimum
and run to 5,000 iterations in wrap-around (toroidal) space.

xxxxx
Agents' paths colored by iteration and inverted.xxxxx Agents' paths colored by tag (id) and inverted.
Click on either small inverted image above for a larger image run to 50,000 iterations.


Flocking 10: With Throwable Agents
All movement is controlled by the Nearest Neighbor except for the "Average within Radius" rule where the radius is set by the TrackBar. In this version, code has been added to capture the time and coordinates distance between MouseDowns and MouseUps on the agents' images allowing the user to "hurl" agents to give them new directions and speeds. The Now( ) function returns the system time...

Flocking 9: + Average within a Radius Rule
A new behavior is added as option 10. Given the Neighborhood Radius selected by the TrackBar, the velocities and directions of all agents within that radius are averaged and become those of the agent. When no longer in a flock, an agent takes on a random velocity and direction. Details are critically important and seemingly minor programming changes can result in discernably different behaviors...

Flocking 8: + Gender Rule, + Bitmap
We have the ability to import a 612 by 612 bitmap image from PhotoShop to use as a geographical environment for the agents. Agents now have access to the three independent channels of data (the red, green and blue layers). The Voyager agents have solid colored bodies rather than transparent bodies as in the last version.

Flocking: + Gendered Agents & Rules
An extension of using images to visualize a problem. Images are taken from the NASA Voyager plaque and DaVinci. Agents are distinguished as male or female and two new behaviors have been added taking advantage of those differences. One behavior has same sex individuals avoiding while opposite sex individuals follow one another. The next behavior reverses the behaviors. See the source code for details of the rules. Of course, much more can be done...

Flocking Snowflakes Sonified
Many things you can do with a TShape object you can do with a TImage object. This version is identical to the last with the exception that a transparent bitmap of a snowflake has been imported (bottom right) and the dynamically created array of TImages have copied their Picture properties from that image's Picture property. Only minor modifications of the code were required to do this although there were a lot of them to be made.

Rafael's Collision Avoidance
A physically accurate simulation of pedestrian collision avoidance while travelling between points A and B.

Rafael's Vector / Vector Flocking
A physically accurate simulation of collisions with and without gravitational attraction as well as other influences on neighboring agents.

A Sampler:
Coordinated Arrays of Texts, Shapes and Images
You can use COORDINATED arrays of text, shape and image components to build up complex visualizations for agents in a simulation. In this sampler, picture properties of the images may be changed dynamically by right-clicking. The shape colors may be changed dynamically as well as the sizes of the images and shapes.

The faces Zipped, if you want to use them elsewhere.

Traffic Flow
An emergent property of freeway traffic is the wave of congestion which moves more slowly than the average speed of the vehicles. From the perspective of the driver, the wave of traffic congestion moves backwards: she sees it up ahead, whe is in it, then it passes behind. The root cause of this wave is the reaction delay of the driver.

Flocking Balls with Walls
We have introduced code to detect collisions with walls and take the appropriate "bounce" or "wrap" actions...

Flocking Behaviors Sonified
Drag and Drop with the left mouse button.
Show the nearest neighbor with right mouse button.

Expect WINDOWS to shut you down if you use the next-to-last rule - or - stop the simultion before it gets out of hand. The "wrap" (toroidal) world is fairly peaceful, but expect some chaotic behavior in the "bounce" (non-toroidal) world.

Flocking - Sonified
Each wall may emit a different sound when hit:
Beep() plays the notes G, C, E & G.
PlaySound() WINDOWS plays Windows sounds.
PlaySound() Pinball plays Pinball sounds.
Midi plays the harpsicord notes G, C, E and G.

You could have the sound indicate the agent number, speed, direction, collisions, etc.

Flocking - 2006
A foundation for a flocking simulation which consists of 24 shape objects tied with 24 agents. Agents, in this application, are blind - you will have to add your own sensors (neighborhoods). Agents have directions, velocities, diameters, outline and fill colors. Assimilation and/or approach and avoidance behaviors could be programed for each... An array of image objects could replace the array of shape objects...

Arrays of Labels, Shapes and Images
Use arrays of Borland components to represent the state of the agents in a simulation. In this sampler, we create an array of TStaticText labels, an array of TShape shapes and an array of TImage images. We also create event handlers for the images and code them to enable drag-and-drop as well as changes in the ->Picture properties of each. In this sampler, the labels, shapes and images are independent, but they could be coordinated if desired. The images are transparent .bmp bitmaps. The images could be colored if desired.

The faces Zipped, if you want to use them elsewhere.

Ball and Kitten
Two transparent bitmap images are created, for a ball and a kitten. Mouse Down, Move and Up events allow the user to drag and rop either object. The kitten is periodically attracted to or repulsed by the ball. When the kitten goes out of bounds it approaches the ball. The greater the distance between the objects the greater the speed. However, the programmer may wish to change this and other parameters.

Canvas Agents with Spatial Properties
Canvas graphics are ephemeral, meaning that they can be erased with a Refresh() call (the "Clear" button) or obliterated when another Window obscures them momentarily. The green/magenta figure is drawn when "Draw" is pressed. The blue/cyan figure is drawn when "FormPaint" is fired. The small figures are drawn by pressing the run/step/stop/initialize buttons. The order in which functions are declared, described and called is illustrated.

 

Traffic
Using an array of shape objects, this application provides each agent with a velocity and a direction of movement. Trigonometric functions (sine, cosine) and the Pythagorean Theorum are used to calculate the dynamics. In the current implementation, the "balls" may be "Reset" to random positions, velocities and directions and may be forced into a "Circle" pattern. The "balls" bounce off of the walls of the Window. The "Circulate" code does not work in its current state and has been commented out.

Executable
Project Files Zipped

Unit 1.cpp Source Code
Unit1.h Source Code

Nicholas Mei's Flocking - 2008
An elaboration on flocking and schooling behavior with multiple controls and an aesthetic sensitivity. Developed independently from Michael Chang's Aquarius.

Michael Chang's Aquarius
An elaboration on flocking and schooling behavior with multiple controls and an aesthetic sensitivity.

Michael Chang's Evolva
Swimming creatures attract and avoid one another, feed on prey, are born, grow and die in a simulated ecosystem. Fully commented geometric functions to enable dynamic spatial movement are included under "Michael's Tools."

 

Michael Chang's Transitional Lines
Developed in C and imported into Director, points follow their targets, located in clusters on a rotating invisible ring surrounding the cursor. As the speed of the cursor increases, so does the radius of the ring and the warmth of the trails left by the points.

Bob and Carol and Ted and Alice
Bob likes Carol who likes Ted who likes Alice. Depending on their individual degrees of attraction, what paths will they take to get together?

Attraction & Avoidance
This application was inspired by a *Logo program written by Jeff Shih. Each one of 100 agents is randomly assigned two other agents: one to avoid and another to be attracted to. The strengths of the attraction and avoidance may be varied and visualized. Agents paths may also be tracked and visualized.