//=========================================================================== // TRAFFIC FLOW - March 2007 // Angles are computed in RADIANS // There are 2PI , or approximately 6.28 RADIANS to a full circle. // 0.01744 RADIANS equals 1.0 DEGREE or 3.49 PIXELS on the circumference. // 0.00174 RADIANS equals 0.1 DEGREE or 0.35 PIXELS on the circumference. // 0.00497 RADIANS equals 0.3 DEGREE or 1.00 PIXELS on the circumference. // // This is a 1-dimensional FLOCKING simulation. // The only direction is FORWARD. // The distance is measured by the ANGLE in RADIANS. // The position is measured by the X and Y components of the ANGLE. // The speed is measured by the VELOCITY (distance/angle per iteration) // //=========================================================================== //--------------------------------------------------------------------------- #include #include #pragma hdrstop #include "Unit1.h" // The following two lines are needed to enable the randomizer #include "stdlib.h" #include "time.h" #include //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" TForm1 *Form1; //--------------------------------------------------------------------------- __fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner) { // Double buffering eliminates some screen flicker... DoubleBuffered = true; } //--------------------------------------------------------------------------- //=========================================================================== // GLOBAL VARIABLES //=========================================================================== // ------------------------------------------------- your program begins here int midiport = 0; HMIDIOUT device; union { public: unsigned long word; unsigned char data[4]; } message; int soundType = 0; int instrument; int note; TShape *shape[24] = {0}; // sets up an array of shapes class anAgent { public: double angle; double lastAngle; double deltaAngle; double velocity; double lastVelocity; double deltaVelocity; double angleAhead; double L1AngleAhead; double L2AngleAhead; double L3AngleAhead; double deltaAngleAhead; double x; double y; } agent[24]; double increment = 2.0; float deltaAngle; bool stop = true; bool wasStopped = false; int iterations; int i, next; int chosenAgent; int shapeDownX, shapeDownY; bool agentWasJustChosen = false; int delay = 2; //=========================================================================== // FUNCTIONS //=========================================================================== //---------------------------------------------------------------- color ramp int colorRamp(int range, int value) { int pixelDistanceAlongPath = (value * 1792) / range; int red, green, blue; // Which edge of the color cube are we on? if (pixelDistanceAlongPath < 256) { // Edge 1 from BLACK to BLUE red=0; green=0; blue=pixelDistanceAlongPath; } else if (pixelDistanceAlongPath < 512) { // Edge 2 from BLUE to CYAN red =0; green=pixelDistanceAlongPath-256; blue=255; } else if (pixelDistanceAlongPath < 768) { // Edge 3 from CYAN to GREEN red =0; green =255; blue= 255-(pixelDistanceAlongPath-512); } else if (pixelDistanceAlongPath < 1024) { // Edge 4 from GREEN to YELLOW red= (pixelDistanceAlongPath-768); green =255; blue =0; } else if (pixelDistanceAlongPath <1280) { // Edge 5 from YELLOW to RED red =255; green=255-(pixelDistanceAlongPath-1024); blue =0; } else if (pixelDistanceAlongPath < 1536) { // Edge 6 from RED to MAGENTA red =255; green=0; blue=pixelDistanceAlongPath -1280; } else { // Edge 7 from MAGENTA to WHITE red =255; green=pixelDistanceAlongPath-1536; blue =255; } return (RGB(red, green, blue)); } //------------------------------------------------------------------- shuffle void shuffle (void) { for (int i = 0; i < 24; i++) { agent[i].x = random(400) + 30; shape[i]->Left = agent[i].x - shape[i]->Width / 2; agent[i].y = random(400) + 30; shape[i]->Top = agent[i].y - shape[i]->Height / 2; agent[i].velocity = float(random(1000)) / 100000 + .001; } } //--------------------------------------------------------------------- reset void reset (void) { iterations = 0; Form1->EditIterations->Text = iterations; shuffle(); } //-------------------------------------------------------------------- circle void circle (void) { for (int i = 0; i < 24; i++) { agent[i].angle = i * (2 * M_PI / 24); agent[i].angleAhead = 2 * M_PI / 24; agent[i].L1AngleAhead = agent[i].angleAhead; agent[i].x = 200 + 180 * cos(agent[i].angle) + 30; agent[i].y = 200 + 180 * sin(agent[i].angle) + 30; shape[i]->Left = agent[i].x - shape[i]->Width / 2; shape[i]->Top = agent[i].y - shape[i]->Height / 2; } } //---------------------------------------------------------- nearest neighbor int nearestNeighbor (int me) { int myNeighbor; double x, y, z; int dist = 10000; for (int i = 0; i < 24; i++) { if (i == me) continue; x = agent[i].x - agent[me].x; y = agent[i].y - agent[me].y; z = sqrt(x * x + y * y); if (z < dist) { dist = z; myNeighbor = i; } } return myNeighbor; } //---------------------------------------------------------------------- step void step (void) { iterations++; Form1->EditIterations->Text = iterations; increment = Form1->TrackBarIncrement->Position; for (i = 0; i < 24; i++) { // update memory agent[i].L3AngleAhead = agent[i].L2AngleAhead; agent[i].L2AngleAhead = agent[i].L1AngleAhead; agent[i].L1AngleAhead = agent[i].angleAhead; agent[i].lastVelocity = agent[i].velocity; agent[i].lastAngle = agent[i].angle; // calculate the new angle ahead if (i == 23) next = 0; else next = i + 1; agent[i].angleAhead = agent[next].angle - agent[i].angle; if (agent[i].angleAhead < 0) { agent[i].angleAhead += 2 * M_PI; } // delay preception of velocity change switch (delay) { case 0: { agent[i].deltaAngle = agent[i].L1AngleAhead - agent[i].angleAhead; break; } case 1: { agent[i].deltaAngle = agent[i].L2AngleAhead - agent[i].L1AngleAhead; break; } case 2: { agent[i].deltaAngle = agent[i].L3AngleAhead - agent[i].L2AngleAhead; break; } } /////////////////////////////////////////////////////////////////////// ///////////////////// FLOCKING BEHAVIORS BELOW //////////////////////// /////////////////////////////////////////////////////////////////////// // calculate the new velocity // Ignore vehicle ahead if (Form1->RadioGroupDrivingBehavior->ItemIndex == 0) { // don't change velocity } // if (Form1->RadioGroupDrivingBehavior->ItemIndex == 1) { if (agent[i].deltaAngle > 0) { // closing too fast agent[i].velocity -= 0.0005; // slow down } if (agent[i].deltaAngle < 0) { // falling behind agent[i].velocity += 0.0005; // speed up } if (agent[i].velocity > .01) { // speed limit agent[i].velocity = .01; } if (agent[i].velocity < 0) { // don't go backwards agent[i].velocity = 0; } } // if (Form1->RadioGroupDrivingBehavior->ItemIndex == 2) { if (agent[i].deltaAngle > 0) { // closing too fast agent[i].velocity -= 0.0008; // slow down } if (agent[i].deltaAngle < 0) { // falling behind agent[i].velocity += 0.0008; // speed up } if (agent[i].velocity > .01) { // speed limit agent[i].velocity = .01; } if (agent[i].velocity < 0) { // don't go backwards agent[i].velocity = 0; } } // if (Form1->RadioGroupDrivingBehavior->ItemIndex == 3) { if (agent[i].deltaAngle > 0) { // closing too fast agent[i].velocity -= 0.0015; // slow down } if (agent[i].deltaAngle < 0) { // falling behind agent[i].velocity += 0.0015; // speed up } if (agent[i].velocity > .01) { // speed limit agent[i].velocity = .01; } if (agent[i].velocity < 0) { // don't go backwards agent[i].velocity = 0; } } // if (Form1->RadioGroupDrivingBehavior->ItemIndex == 4) { if (agent[i].deltaAngle > 0) { // closing too fast agent[i].velocity -= 0.0005 * agent[i].angleAhead; // slow down } if (agent[i].deltaAngle < 0) { // falling behind agent[i].velocity += 0.0005 * agent[i].angleAhead; // speed up } if (agent[i].velocity > .01) { // speed limit agent[i].velocity = .01; } if (agent[i].velocity < 0) { // don't go backwards agent[i].velocity = 0; } } // if (Form1->RadioGroupDrivingBehavior->ItemIndex == 5) { if (agent[i].angleAhead > 0.3) { agent[i].velocity -= 0.008; } if (agent[i].angleAhead < 0.3) { agent[i].velocity += 0.008; } if (agent[i].velocity > .01) { agent[i].velocity = .01; } if (agent[i].velocity < 0) { agent[i].velocity = 0; } } // if (Form1->RadioGroupDrivingBehavior->ItemIndex == 6) { if (agent[i].deltaAngle > 0) { agent[i].velocity -= 0.01; } if (agent[i].deltaAngle < 0) { agent[i].velocity += 0.01; } if (agent[i].velocity > .01) { agent[i].velocity = .01; } if (agent[i].velocity < 0) { agent[i].velocity = 0; } } /////////////////////////////////////////////////////////////////////// ///////////////////// FLOCKING BEHAVIORS ABOVE /////////////////////// /////////////////////////////////////////////////////////////////////// // Calculate the new angle agent[i].angle += agent[i].velocity * increment; // modulo divide if (agent[i].angle > 2 * M_PI) { agent[i].angle = agent[i].angle - 2 * M_PI; } // calculate the new x/y position agent[i].x = 200 + 180 * cos(agent[i].angle) + 30; agent[i].y = 200 + 180 * sin(agent[i].angle) + 30; // move the visualization on the screen accordingly shape[i]->Left = agent[i].x - shape[i]->Width / 2; shape[i]->Top = agent[i].y - shape[i]->Height / 2; } } //---------------------------------------------------------------------- Run void run (void) { stop = false; message.data[0] = 0xC0; message.data[1] = 6; message.data[2] = 100; message.data[3] = 0; midiOutShortMsg(device, message.word); while (stop == false) { step(); Application->ProcessMessages(); } } //=========================================================================== // EVENT HANDLERS //=========================================================================== //------------------------------------------------------------ On Form Create void __fastcall TForm1::FormCreate(TObject *Sender) { midiOutOpen(&device, midiport, 0, 0, CALLBACK_NULL); randomize(); // defines an array of shapes with properties and events for (int i = 0; i < 24; i++) { shape[i] = new TShape(this); shape[i]->Parent = Form1; shape[i]->Visible = true; shape[i]->OnMouseDown = ShapeMouseDown; shape[i]->OnMouseUp = ShapeMouseUp; shape[i]->OnMouseMove = ShapeMouseMove; shape[i]->Height = 40; shape[i]->Width = 40; shape[i]->Left = 0; shape[i]->Top = 0; shape[i]->Shape = stCircle; shape[i]->Tag = i; shape[i]->Pen->Width = 2; shape[i]->Pen->Color = static_cast(colorRamp(25, 24 - shape[i]->Tag)); shape[i]->Brush->Color = static_cast(colorRamp(25, shape[i]->Tag)); } shuffle(); circle(); } //------------------------------------------------------- On Shape Mouse Down // An exception to the rule which says "Let Borland write event handlers." // This one you must type in yourself in addition to a reference to it // in Unit1.h (look at the source code in that unit). void __fastcall TForm1::ShapeMouseDown(TObject *Sender, TMouseButton Button, TShiftState Shift, int X, int Y) { TShape *shape = dynamic_cast(Sender); // The following will be used for mouseMove and mouseUp events... // Captures the index number of the shape that was clicked chosenAgent = shape->Tag; // remembers is we were stopped or running wasStopped = stop; stop = true; if (Button == 0) { // Begin drag object // Remembers that an shape was chosen for mouseMove and mouseUp agentWasJustChosen = true; // Remembers where on the shape the mouse was downed shapeDownX = X; shapeDownY = Y; } else { // Show nearest neighbor Form1->Canvas->MoveTo(agent[chosenAgent].x, agent[chosenAgent].y); Form1->Canvas->LineTo(agent[nearestNeighbor(chosenAgent)].x, agent[nearestNeighbor(chosenAgent)].y); } } //------------------------------------------------------- On Shape Mouse Move // An exception to the rule which says "Let Borland write event handlers." // This one you must type in yourself in addition to a reference to it // in Unit1.h (look at the source code in that unit). void __fastcall TForm1::ShapeMouseMove(TObject *Sender, TShiftState Shift, int X, int Y) { TShape *shape = dynamic_cast(Sender); chosenAgent = shape->Tag; if (agentWasJustChosen) { // this drags the shape along... shape->Left = shape->Left + X - shapeDownX; shape->Top = shape->Top + Y - shapeDownY; agent[chosenAgent].x = shape->Left + shape->Width / 2;; agent[chosenAgent].y = shape->Top + shape->Height / 2;; } // When the mouse moves over an shape its values are displayed EditAgent->Text = shape->Tag; EditX->Text = int(agent[chosenAgent].x); EditY->Text = int(agent[chosenAgent].y); EditVelocity->Text = agent[shape->Tag].velocity; EditDeltaVelocity->Text = agent[shape->Tag].deltaAngle; EditAngle->Text = agent[shape->Tag].angle; EditAngleAhead->Text = agent[shape->Tag].angleAhead; EditLast1AngleAhead->Text = agent[shape->Tag].L1AngleAhead; EditLast2AngleAhead->Text = agent[shape->Tag].L2AngleAhead; EditLast3AngleAhead->Text = agent[shape->Tag].L3AngleAhead; } //--------------------------------------------------------- On Shape Mouse Up // An exception to the rule which says "Let Borland write event handlers." // This one you must type in yourself in addition to a reference to it // in Unit1.h (look at the source code in that unit). void __fastcall TForm1::ShapeMouseUp(TObject *Sender, TMouseButton Button, TShiftState Shift, int X, int Y) { TShape *shape = dynamic_cast(Sender); // this is the end of the drag... agentWasJustChosen = false; EditAgent->Text = shape->Tag; // When the mouse moves over an shape its values are displayed EditX->Text = int(agent[chosenAgent].x); EditY->Text = int(agent[chosenAgent].y); EditVelocity->Text = agent[shape->Tag].velocity; // if we were running before the drag, then run... Form1->Refresh(); if (!wasStopped) { run(); } } //---------------------------------------------------------------- run button void __fastcall TForm1::ButtonRunClick(TObject *Sender) { run(); } //--------------------------------------------------------------- step button void __fastcall TForm1::ButtonStepClick(TObject *Sender) { stop = true; step(); } //--------------------------------------------------------------- stop button void __fastcall TForm1::ButtonStopClick(TObject *Sender) { stop = true; } //---------------------------------------------------------- randomize button void __fastcall TForm1::ButtonResetClick(TObject *Sender) { reset(); circle(); } //------------------------------------------------------------- circle button void __fastcall TForm1::ButtonCircleClick(TObject *Sender) { circle(); } //------------------------------------------------------ size change trackBar void __fastcall TForm1::TrackBarSizeChange(TObject *Sender) { int size = TrackBarSize->Position; for (int i = 0; i < 24; i++) { shape[i]->Height = size; shape[i]->Width = size; } Form1->EditAgentDiameter->Text = size; } //----------------------------------------------------- sound type RadioGroup void __fastcall TForm1::RadioGroupDelayClick(TObject *Sender) { delay = RadioGroupDelay->ItemIndex; } //--------------------------------------------------------------------------- void __fastcall TForm1::TrackBarIncrementChange(TObject *Sender) { int pos = TrackBarIncrement->Position; if (pos < 10) { Form1->EditTimeIncrement->Text = "0.0000" + IntToStr(pos); } else { Form1->EditTimeIncrement->Text = "0.000" + IntToStr(pos); } increment = pos / 10000; } //--------------------------------------------------------------------------- void __fastcall TForm1::RadioGroupDrivingBehaviorClick(TObject *Sender) { reset(); circle(); } //---------------------------------------------------------------------------