Commits

Thejesh GN committed 7650486

modified presentation for 2d stuff (rotation and translation)

Comments (0)

Files changed (24)

examples/simple_flower/simple_flower.pde

+size(600, 400);  
+background(100);  
+smooth();
+noStroke(); 
+translate(300, 200);  
+
+for(int i = 0; i < 10; i++) {    
+fill(195, 200, 250, 60);    
+pushMatrix();    
+// rotate each petal 62 degrees  = 360/5 loops  
+rotate(radians(i*360/10));    
+ellipse(0,0,300,50);    
+popMatrix();  
+
+}  
+
+

presentation-module-1-and-2.zip

Binary file added.

presentation/img/degrees.png

Added
New image

presentation/img/moved_grid.png

Added
New image

presentation/img/rotated_grid.png

Added
New image

presentation/module1/1.html~

+<html>
+<head>
+<title>Processing 101 - Introduction</title>
+<link rel="stylesheet" href="../media/style.css" /> 
+<link rel="stylesheet" href="../media/bebas/stylesheet.css" type="text/css" charset="utf-8">
+<link rel="stylesheet" href="../media/TitilliumText/stylesheet.css" type="text/css" charset="utf-8">
+<link rel="stylesheet" href="../media/main.css" /> 
+<link rel="stylesheet" href="../media/ie6.css" /> 
+</head>
+<body>
+<div id="header-wrap">
+	<div id="header-container">
+		<div id="header">
+			<h2>Processing 101 - Introduction</h2><h1>Course&nbsp;&nbsp;organization</h1>
+			<ul>
+				<li><a href="./0.html">&lt;&nbsp;Previous</a></li>
+				<li><a href="../index.html">&nbsp;Home&nbsp;</a></li>
+				<li><a href="./2.html">Next&nbsp;&gt;</a></li>
+			</ul>
+		</div>
+			
+	</div>
+</div>
+
+<div id="ie6-container-wrap">
+	<div id="container">
+		<div id="content" class="content">
+			<p>This course is organized into three modules
+			 <ol><b><li> Introduction</li></b> 
+<ul>
+<li>Introduction to Processing
+<li>Installation of runtime and setup
+<li>Working with IDE</li>
+<li>Your Drawing sheet</li>
+<li>Co-ordinate system
+<li>Points and Lines
+<li>Arc, Circle and other geometrical shapes
+<li>Drawing order
+<li>Colors, Stroke Width and Fill
+<li>Lets create an Android
+</ul>
+
+<b><li>Programming with Processing</li> </b> 
+<ul>
+<li>Structure (statements and comments)
+<li>Operators
+<li>Variables (primitives)
+<li>Functions (custom and built in)
+<li>Conditional Flows
+<li>Looping
+<li>Loop inside a loop
+<li>Text and Font
+<li>Mouse Interactions
+<li>Keyboard Interactions
+<li>Save (text and image)
+</ul>
+<b><li> Advanced Processing </li> </b>
+<ul>
+<li>Object oriented programming (classes and objects)
+<li>Arrays
+<li>Motions
+<li>Images (load, interact and processing)
+<li>Simulations
+<li>Introduction to 3d
+</ul>
+</ol>
+</p>
+	
+
+
+		</div>
+	</div>
+</div>
+
+<div id="footer-wrap">
+	<div id="footer-container">
+		<div id="footer">
+			<div id="credits">
+				<a href="http://thejeshgn.com/"><font color="#000">Thejesh</font>&nbsp;<font color="#83BE32">GN</font></a>
+			</div>
+			<ul>
+				<li><a href="http://thejeshgn.com/teaching/processing-101/">Course</a></li>
+				<li><a href="http://code.thejeshgn.com/processing101/">Code</a></li>	
+				<li><a href="http://www.delicious.com/gnthej/processing101/">Links</a></li>	
+				<li><a href="http://thejeshgn.com/contact/">Contact</a></li>	
+
+			</ul>
+		</div>
+	</div>
+</div>
+</body>
+</html>

presentation/module1/18.html

 			<ul>
 				<li><a href="./17.html">&lt;&nbsp;Previous</a></li>
 				<li><a href="../index.html">&nbsp;Home&nbsp;</a></li>
-				<li><a href="./18.html">Next&nbsp;&gt;</a></li>
+				<li><a href="./19.html">Next&nbsp;&gt;</a></li>
 			</ul>
 		</div>
 			

presentation/module1/19.html

+<html>
+<head>
+<title>Processing 101 - Introduction</title>
+<link rel="stylesheet" href="../media/style.css" /> 
+<link rel="stylesheet" href="../media/bebas/stylesheet.css" type="text/css" charset="utf-8">
+<link rel="stylesheet" href="../media/TitilliumText/stylesheet.css" type="text/css" charset="utf-8">
+<link rel="stylesheet" href="../media/main.css" /> 
+<link rel="stylesheet" href="../media/ie6.css" /> 
+<SCRIPT src="../media/js/processing-1.2.1.min.js"></SCRIPT>
+<SCRIPT src="../media/js/init.js"></SCRIPT>
+<SCRIPT type="application/processing" target="processingArea">
+size(500, 375);
+</SCRIPT>
+
+
+</head>
+<body>
+<div id="header-wrap">
+	<div id="header-container">
+		<div id="header">
+			<h2>Processing 101 - Drawing</h2><h1>Translation&nbsp;&nbsp;Moving &nbsp;&nbsp;the&nbsp;&nbsp;Coordinates</h1>
+			<ul>
+				<li><a href="./18.html">&lt;&nbsp;Previous</a></li>
+				<li><a href="../index.html">&nbsp;Home&nbsp;</a></li>
+				<li><a href="./20.html">Next&nbsp;&gt;</a></li>
+			</ul>
+		</div>
+			
+	</div>
+</div>
+
+<div id="ie6-container-wrap">
+	<div id="container">
+		<div id="content" class="content">
+			<ol>
+				<li>Translation moves the co-ordinate system (grid or graph) by given value
+				<li>pushMatrix() is used to save the current co-ordinate system
+				<li>popMatrix() is used to go back to the previous co-ordinate system
+                    <br><img src="./../img/moved_grid.png"/>
+                <li>translate(60, 80);
+                <li>So how can we use it?
+			</ol>		</div>
+	</div>
+</div>
+
+<div id="footer-wrap">
+	<div id="footer-container">
+		<div id="footer">
+			<div id="credits">
+				<a href="http://thejeshgn.com/"><font color="#000">Thejesh</font>&nbsp;<font color="#83BE32">GN</font></a>
+			</div>
+			<ul>
+				<li><a href="http://thejeshgn.com/teaching/processing-101/">Course</a></li>
+				<li><a href="http://code.thejeshgn.com/processing101/">Code</a></li>	
+				<li><a href="http://www.delicious.com/gnthej/processing101/">Links</a></li>	
+				<li><a href="http://thejeshgn.com/contact/">Contact</a></li>	
+
+			</ul>
+		</div>
+	</div>
+</div>
+</body>
+</html>

presentation/module1/20.html

+<html>
+<head>
+<title>Processing 101 - Introduction</title>
+<link rel="stylesheet" href="../media/style.css" /> 
+<link rel="stylesheet" href="../media/bebas/stylesheet.css" type="text/css" charset="utf-8">
+<link rel="stylesheet" href="../media/TitilliumText/stylesheet.css" type="text/css" charset="utf-8">
+<link rel="stylesheet" href="../media/main.css" /> 
+<link rel="stylesheet" href="../media/ie6.css" /> 
+<SCRIPT src="../media/js/processing-1.2.1.min.js"></SCRIPT>
+<SCRIPT src="../media/js/init.js"></SCRIPT>
+<SCRIPT type="application/processing" target="processingArea">
+size(500, 375);
+</SCRIPT>
+
+
+</head>
+<body>
+<div id="header-wrap">
+	<div id="header-container">
+		<div id="header">
+			<h2>Processing 101 - Drawing</h2><h1>Rotation</h1>
+			<ul>
+				<li><a href="./19.html">&lt;&nbsp;Previous</a></li>
+				<li><a href="../index.html">&nbsp;Home&nbsp;</a></li>
+				<li><a href="./21.html">Next&nbsp;&gt;</a></li>
+			</ul>
+		</div>
+			
+	</div>
+</div>
+
+<div id="ie6-container-wrap">
+	<div id="container">
+		<div id="content" class="content">
+			<ol>
+				<li>Rotation - rotates the co-ordinate system (grid or graph) to a given radian
+                <li>Angle is generally measured in radiens and is measured at the top left point
+                <br> <img src="./../img/rotated_grid.png" />
+				<li>pushMatrix() is used to save the current co-ordinate system
+				<li>popMatrix() is used to go back to the previous co-ordinate system
+                <li>rotate(PI/2);
+                <li>So how can we use it?
+                <li>Move the coordinate system to the point where you want to rotate using Translation
+                <li>Then rotate to the required angle
+                <br><img src="./../img/degrees.png" />
+			</ol>		
+        </div>
+	</div>
+</div>
+
+<div id="footer-wrap">
+	<div id="footer-container">
+		<div id="footer">
+			<div id="credits">
+				<a href="http://thejeshgn.com/"><font color="#000">Thejesh</font>&nbsp;<font color="#83BE32">GN</font></a>
+			</div>
+			<ul>
+				<li><a href="http://thejeshgn.com/teaching/processing-101/">Course</a></li>
+				<li><a href="http://code.thejeshgn.com/processing101/">Code</a></li>	
+				<li><a href="http://www.delicious.com/gnthej/processing101/">Links</a></li>	
+				<li><a href="http://thejeshgn.com/contact/">Contact</a></li>	
+
+			</ul>
+		</div>
+	</div>
+</div>
+</body>
+</html>

presentation/module1/21.html

+<html>
+<head>
+<title>Processing 101 - Introduction</title>
+<link rel="stylesheet" href="../media/style.css" /> 
+<link rel="stylesheet" href="../media/bebas/stylesheet.css" type="text/css" charset="utf-8">
+<link rel="stylesheet" href="../media/TitilliumText/stylesheet.css" type="text/css" charset="utf-8">
+<link rel="stylesheet" href="../media/main.css" /> 
+<link rel="stylesheet" href="../media/ie6.css" /> 
+<SCRIPT src="../media/js/processing-1.2.1.min.js"></SCRIPT>
+<SCRIPT src="../media/js/init.js"></SCRIPT>
+<SCRIPT type="application/processing" target="processingArea">
+size(600, 400);  
+background(100);  
+smooth();
+noStroke(); 
+translate(300, 200);  
+for(i = 0; i < 5; i++) {    
+//fill(195, 200, 250, 60);    
+fill(240,229,7,80);
+pushMatrix();    
+// rotate each petal 62 degrees  = 360/5 loops  
+rotate(radians(i*360/5));    
+ellipse(0,0,320,60);    
+popMatrix();  
+}  
+fill(244,0,0);
+ellipse(0,0,60,60);
+</SCRIPT>
+
+
+</head>
+<body>
+<div id="header-wrap">
+	<div id="header-container">
+		<div id="header">
+			<h2>Processing 101 - Drawing</h2><h1>Lets&nbsp;&nbsp;draw&nbsp;&nbsp;a&nbsp;&nbsp;Flower</h1>
+			<ul>
+				<li><a href="./20.html">&lt;&nbsp;Previous</a></li>
+				<li><a href="../index.html">&nbsp;Home&nbsp;</a></li>
+				<li><a href="./21.html">Next&nbsp;&gt;</a></li>
+			</ul>
+		</div>
+			
+	</div>
+</div>
+
+<div id="ie6-container-wrap">
+	<div id="container">
+		<div id="content" class="content">
+			<CANVAS id="processingArea" tabindex="0" style="image-rendering: optimizequality !important; " width="500" height="375" ></CANVAS>	
+		</div>
+	</div>
+</div>
+
+<div id="footer-wrap">
+	<div id="footer-container">
+		<div id="footer">
+			<div id="credits">
+				<a href="http://thejeshgn.com/"><font color="#000">Thejesh</font>&nbsp;<font color="#83BE32">GN</font></a>
+			</div>
+			<ul>
+				<li><a href="http://thejeshgn.com/teaching/processing-101/">Course</a></li>
+				<li><a href="http://code.thejeshgn.com/processing101/">Code</a></li>	
+				<li><a href="http://www.delicious.com/gnthej/processing101/">Links</a></li>	
+				<li><a href="http://thejeshgn.com/contact/">Contact</a></li>	
+
+			</ul>
+		</div>
+	</div>
+</div>
+</body>
+</html>

project/fibonnaci/fibonnaci.pde

+float number = 1;
+float last,last2;
+float[] fibs= new float [1];
+ 
+float px,py,r,degree;
+float[] xpos = new float[0];
+float[] ypos = new float[0];
+ 
+float spacing = 6;
+int startWeight = 2;
+int maxWeight = 5;
+float weight = startWeight;
+float guldenSnede = ((sqrt(5) - 1 ) / 2);
+ 
+float lastX, lastY;
+ 
+void setup()
+{
+  size(1280, 800);
+  background(255);
+  smooth();
+  stroke(0);
+  frameRate(30);
+  px = width/2;
+  py = height/2;
+}
+ 
+void draw()
+{
+    lastX = px;
+    lastY = py;
+    degree = (frameCount * guldenSnede) * 360;
+    r = sqrt(frameCount)*spacing;
+    calculatePoint(width/2, height/2, r, (degree % 360));
+    strokeWeight(weight);
+    point(px,py);
+    //line(lastX, lastY, px,py);
+    weight += 0.00015;
+    println(degree % 360);
+    //spacing += 0.00075;
+}
+ 
+void calculatePoint(float x, float y, float r, float graden){
+  px = x + cos(radians(graden))*(r/2);
+  py = y + sin(radians(graden))*(r/2);
+}

project/filters/data/ArialMT-200.vlw

Binary file added.

project/filters/data/mlk10.jpg

Added
New image

project/filters/filters.jar

Binary file added.

project/filters/filters.java

+import processing.core.*; 
+import processing.xml.*; 
+
+import java.applet.*; 
+import java.awt.*; 
+import java.awt.image.*; 
+import java.awt.event.*; 
+import java.io.*; 
+import java.net.*; 
+import java.text.*; 
+import java.util.*; 
+import java.util.zip.*; 
+import java.util.regex.*; 
+
+public class filters extends PApplet {
+
+PFont font;
+String fontpath = "ArialMT-200.vlw";
+int fontstart = 300;
+int fontend = 8;
+float fontsize = fontstart;
+float fontsizedecrease = 0.97f;
+PImage img;
+String imgpath = "mlk10.jpg";
+String letters = "IhaveadreamIamhappytojoinwithyoutodayinwhatwillgodowninhistoryasthegreatestdemonstrationforfreedominthehistoryofournationFivescoreyearsagoagreatAmericaninwhosesymbolicshadowwestandtodaysignedtheEmancipationProclamationThismomentousdecreecameasagreatbeaconlightofhopetomillionsofNegroslaveswhohadbeensearedintheflamesofwitheringinjusticeItcameasajoyousdaybreaktoendthelongnightoftheircaptivityButonehundredyearslatertheNegrostillisnotfreeOnehundredyearslaterthelifeoftheNegroisstillsadlycrippledbythemanaclesofsegregationandthechainsofdiscriminationOnehundredyearslatertheNegrolivesonalonelyislandofpovertyinthemidstofavastoceanofmaterialprosperityOnehundredyearslatertheNegroisstilllanguishedinthecornersofAmericansocietyandfindshimselfanexileinhisownlandAndsowevecomeheretodaytodramatizeashamefulconditionInasensewevecometoournationscapitaltocashacheckWhenthearchitectsofourrepublicwrotethemagnificentwordsoftheConstitutionandtheDeclarationofIndependencetheyweresigningapromissorynotetowhicheveryAmericanwastofallheirThisnotewasapromisethatallmenyesblackmenaswellaswhitemenwouldbeguaranteedtheunalienableRightsofLifeLibertyandthepursuitofHappinessItisobvioustodaythatAmericahasdefaultedonthispromissorynoteinsofarashercitizensofcolorareconcernedInsteadofhonoringthissacredobligationAmericahasgiventheNegropeopleabadcheckacheckwhichhascomebackmarkedinsufficientfundsButwerefusetobelievethatthebankofjusticeisbankruptWerefusetobelievethatthereareinsufficientfundsinthegreatvaultsofopportunityofthisnationAndsowevecometocashthischeckacheckthatwillgiveusupondemandtherichesoffreedomandthesecurityofjusticeWehavealsocometothishallowedspottoremindAmericaofthefierceurgencyofNowThisisnotimetoengageintheluxuryofcoolingoffortotakethetranquilizingdrugofgradualismNowisthetimetomakerealthepromisesofdemocracyNowisthetimetorisefromthedarkanddesolatevalleyofsegregationtothesunlitpathofracialjusticeNowisthetimetoliftournationfromthequicksandsofracialinjusticetothesolidrockofbrotherhoodNowisthetimetomakejusticearealityforallofGodschildrenItwouldbefatalforthenationtooverlooktheurgencyofthemomentThisswelteringsummeroftheNegroslegitimatediscontentwillnotpassuntilthereisaninvigoratingautumnoffreedomandequalityNineteensixtythreeisnotanendbutabeginningAndthosewhohopethattheNegroneededtoblowoffsteamandwillnowbecontentwillhavearudeawakeningifthenationreturnstobusinessasusualAndtherewillbeneitherrestnortranquilityinAmericauntiltheNegroisgrantedhiscitizenshiprightsThewhirlwindsofrevoltwillcontinuetoshakethefoundationsofournationuntilthebrightdayofjusticeemergesButthereissomethingthatImustsaytomypeoplewhostandonthewarmthresholdwhichleadsintothepalaceofjusticeIntheprocessofgainingourrightfulplacewemustnotbeguiltyofwrongfuldeedsLetusnotseektosatisfyourthirstforfreedombydrinkingfromthecupofbitternessandhatredWemustforeverconductourstruggleonthehighplaneofdignityanddisciplineWemustnotallowourcreativeprotesttodegenerateintophysicalviolenceAgainandagainwemustrisetothemajesticheightsofmeetingphysicalforcewithsoulforceThemarvelousnewmilitancywhichhasengulfedtheNegrocommunitymustnotleadustoadistrustofallwhitepeopleformanyofourwhitebrothersasevidencedbytheirpresenceheretodayhavecometorealizethattheirdestinyistiedupwithourdestinyAndtheyhavecometorealizethattheirfreedomisinextricablyboundtoourfreedomWecannotwalkaloneAndaswewalkwemustmakethepledgethatweshallalwaysmarchaheadWecannotturnbackTherearethosewhoareaskingthedevoteesofcivilrightsWhenwillyoubesatisfiedWecanneverbesatisfiedaslongastheNegroisthevictimoftheunspeakablehorrorsofpolicebrutalityWecanneverbesatisfiedaslongasourbodiesheavywiththefatigueoftravelcannotgainlodginginthemotelsofthehighwaysandthehotelsofthecitiesWecannotbesatisfiedaslongasthenegrosbasicmobilityisfromasmallerghettotoalargeroneWecanneverbesatisfiedaslongasourchildrenarestrippedoftheirselfhoodandrobbedoftheirdignitybysignsstatingForWhitesOnlyWecannotbesatisfiedaslongasaNegroinMississippicannotvoteandaNegroinNewYorkbelieveshehasnothingforwhichtovoteNonowearenotsatisfiedandwewillnotbesatisfieduntiljusticerollsdownlikewatersandrighteousnesslikeamightystream\u00b9IamnotunmindfulthatsomeofyouhavecomehereoutofgreattrialsandtribulationsSomeofyouhavecomefreshfromnarrowjailcellsAndsomeofyouhavecomefromareaswhereyourquestquestforfreedomleftyoubatteredbythestormsofpersecutionandstaggeredbythewindsofpolicebrutalityYouhavebeentheveteransofcreativesufferingContinuetoworkwiththefaiththatunearnedsufferingisredemptiveGobacktoMississippigobacktoAlabamagobacktoSouthCarolinagobacktoGeorgiagobacktoLouisianagobacktotheslumsandghettosofournortherncitiesknowingthatsomehowthissituationcanandwillbechangedLetusnotwallowinthevalleyofdespairIsaytoyoutodaymyfriendsAndsoeventhoughwefacethedifficultiesoftodayandtomorrowIstillhaveadreamItisadreamdeeplyrootedintheAmericandreamIhaveadreamthatonedaythisnationwillriseupandliveoutthetruemeaningofitscreedWeholdthesetruthstobeselfevidentthatallmenarecreatedequalIhaveadreamthatonedayontheredhillsofGeorgiathesonsofformerslavesandthesonsofformerslaveownerswillbeabletositdowntogetheratthetableofbrotherhoodIhaveadreamthatonedayeventhestateofMississippiastateswelteringwiththeheatofinjusticeswelteringwiththeheatofoppressionwillbetransformedintoanoasisoffreedomandjusticeIhaveadreamthatmyfourlittlechildrenwillonedayliveinanationwheretheywillnotbejudgedbythecoloroftheirskinbutbythecontentoftheircharacterIhaveadreamtodayIhaveadreamthatonedaydowninAlabamawithitsviciousracistswithitsgovernorhavinghislipsdrippingwiththewordsofinterpositionandnullificationonedayrightthereinAlabamalittleblackboysandblackgirlswillbeabletojoinhandswithlittlewhiteboysandwhitegirlsassistersandbrothersIhaveadreamtodayIhaveadreamthatonedayeveryvalleyshallbeexaltedandeveryhillandmountainshallbemadelowtheroughplaceswillbemadeplainandthecrookedplaceswillbemadestraightandthegloryoftheLordshallberevealedandallfleshshallseeittogetherThisisourhopeandthisisthefaiththatIgobacktotheSouthwithWiththisfaithwewillbeabletohewoutofthemountainofdespairastoneofhopeWiththisfaithwewillbeabletotransformthejanglingdiscordsofournationintoabeautifulsymphonyofbrotherhoodWiththisfaithwewillbeabletoworktogethertopraytogethertostruggletogethertogotojailtogethertostandupforfreedomtogetherknowingthatwewillbefreeonedayAndthiswillbethedaythiswillbethedaywhenallofGodschildrenwillbeabletosingwithnewmeaningMycountrytisoftheesweetlandoflibertyoftheeIsingLandwheremyfathersdiedlandofthePilgrimsprideFromeverymountainsideletfreedomringAndifAmericaistobeagreatnationthismustbecometrueAndsoletfreedomringfromtheprodigioushilltopsofNewHampshireLetfreedomringfromthemightymountainsofNewYorkLetfreedomringfromtheheighteningAllegheniesofPennsylvaniaLetfreedomringfromthesnowcappedRockiesofColoradoLetfreedomringfromthecurvaceousslopesofCaliforniaButnotonlythatLetfreedomringfromStoneMountainofGeorgiaLetfreedomringfromLookoutMountainofTennesseeLetfreedomringfromeveryhillandmolehillofMississippiFromeverymountainsideletfreedomringAndwhenthishappenswhenweallowfreedomringwhenweletitringfromeveryvillageandeveryhamletfromeverystateandeverycitywewillbeabletospeedupthatdaywhenallofGodschildrenblackmenandwhitemenJewsandGentilesProtestantsandCatholicswillbeabletojoinhandsandsinginthewordsoftheoldNegrospiritualFreeatlastFreeatlastThankGodAlmightywearefreeatlast";
+char[] chars = new char[52];
+int nchars = 0;
+int iterations = 500;
+int c = 0;
+PGraphics letter,lettersquare,drawing;
+
+public void setup(){
+  //initialize the sketch
+  size(438,600);
+  background(255);
+  //initialize the font
+  //font = loadFont(fontpath);
+  ///*
+  for(int i=0;i<letters.length();i++){
+    boolean found = false;
+    char lc = letters.charAt(i);
+    for(int j=0;j<nchars;j++){
+      if(chars[j]==lc){
+        found = true;
+        break;
+      }
+    }
+    if(!found) chars[nchars++] = lc;
+  }
+  chars = (char[]) subset(chars,0,nchars);
+  font = createFont("Arial",200,true,chars);
+  //*/
+  textAlign(CENTER,CENTER);
+  //load the image that will be filled with letters
+  img = loadImage(imgpath);
+  //posterize the image
+  img.filter(THRESHOLD,0.4f);
+  img.filter(BLUR,3);
+  img.filter(THRESHOLD,0.6f);
+  //initialize the drawing buffers
+  letter = createGraphics((int)fontsize,(int)fontsize,JAVA2D);
+  lettersquare = createGraphics((int)fontsize,(int)fontsize,P2D);
+  drawing = createGraphics(width,height,JAVA2D);
+  drawing.beginDraw();
+  drawing.background(255);
+  drawing.endDraw();
+}
+
+public void draw(){
+  background(255);
+  if(floor(fontsize)>fontend&&c<letters.length()-1){
+    if(!letterfit()){
+      fontsize *= fontsizedecrease;
+    }else{
+      c++;
+      if(c==11){
+        fontsize *= 0.75f;
+      }
+    }
+    tint(255);
+    image(drawing,0,0);
+    if(mousePressed){
+      tint(255,100);
+      image(img,0,0);
+    }
+  }else{
+    tint(255);
+    image(drawing,0,0);
+    println(c+" "+letters.length());
+    /*
+    save("mlk-"+hour()+""+minute()+""+second()+".tif");
+    exit();
+    */
+    noLoop();
+  }
+}
+
+public boolean letterfit(){
+  letter.beginDraw();
+  letter.background(255,0);
+  letter.fill(0); 
+  letter.textAlign(CENTER,CENTER);
+  letter.translate(fontsize/2,fontsize/2); 
+  letter.rotate(random(TWO_PI));
+  letter.scale(fontsize/fontstart); 
+  letter.textFont(font); 
+  letter.smooth();
+  letter.text(letters.charAt(c),0,0); 
+  letter.endDraw();
+  lettersquare.beginDraw(); 
+  lettersquare.background(255); 
+  lettersquare.image(letter,0,0);
+  lettersquare.filter(ERODE);
+  lettersquare.filter(ERODE);
+  lettersquare.endDraw();
+  for(int i=0;i<iterations;i++){
+    int x = floor(random(width-fontsize));
+    int y = floor(random(height-fontsize));
+    boolean fits = true;
+    for(int dx=0;dx<fontsize&&fits;dx++){ 
+      for(int dy=0;dy<fontsize&&fits;dy++){
+        if(brightness(img.get(x+dx,y+dy))>127){
+          fits = false;
+          break;
+        }
+        if(brightness(lettersquare.get(dx,dy))<127){ 
+          if(brightness(drawing.get(x+dx,y+dy))<127){
+            fits = false;
+          }
+        }
+      }
+    }
+    if(fits){
+      drawing.beginDraw();
+      drawing.image(letter,x,y);
+      drawing.endDraw();
+      return true;
+    }
+  }
+  return false;
+}
+
+/*
+void mousePressed(){
+  save("mlk-"+hour()+""+minute()+""+second()+".tif");
+  exit();
+}
+*/
+
+  static public void main(String args[]) {
+    PApplet.main(new String[] { "--bgcolor=#F0F0F0", "filters" });
+  }
+}

project/filters/filters.pde

+PFont font;
+String fontpath = "ArialMT-200.vlw";
+int fontstart = 300;
+int fontend = 8;
+float fontsize = fontstart;
+float fontsizedecrease = 0.97;
+PImage img;
+String imgpath = "mlk10.jpg";
+String letters = "IhaveadreamIamhappytojoinwithyoutodayinwhatwillgodowninhistoryasthegreatestdemonstrationforfreedominthehistoryofournationFivescoreyearsagoagreatAmericaninwhosesymbolicshadowwestandtodaysignedtheEmancipationProclamationThismomentousdecreecameasagreatbeaconlightofhopetomillionsofNegroslaveswhohadbeensearedintheflamesofwitheringinjusticeItcameasajoyousdaybreaktoendthelongnightoftheircaptivityButonehundredyearslatertheNegrostillisnotfreeOnehundredyearslaterthelifeoftheNegroisstillsadlycrippledbythemanaclesofsegregationandthechainsofdiscriminationOnehundredyearslatertheNegrolivesonalonelyislandofpovertyinthemidstofavastoceanofmaterialprosperityOnehundredyearslatertheNegroisstilllanguishedinthecornersofAmericansocietyandfindshimselfanexileinhisownlandAndsowevecomeheretodaytodramatizeashamefulconditionInasensewevecometoournationscapitaltocashacheckWhenthearchitectsofourrepublicwrotethemagnificentwordsoftheConstitutionandtheDeclarationofIndependencetheyweresigningapromissorynotetowhicheveryAmericanwastofallheirThisnotewasapromisethatallmenyesblackmenaswellaswhitemenwouldbeguaranteedtheunalienableRightsofLifeLibertyandthepursuitofHappinessItisobvioustodaythatAmericahasdefaultedonthispromissorynoteinsofarashercitizensofcolorareconcernedInsteadofhonoringthissacredobligationAmericahasgiventheNegropeopleabadcheckacheckwhichhascomebackmarkedinsufficientfundsButwerefusetobelievethatthebankofjusticeisbankruptWerefusetobelievethatthereareinsufficientfundsinthegreatvaultsofopportunityofthisnationAndsowevecometocashthischeckacheckthatwillgiveusupondemandtherichesoffreedomandthesecurityofjusticeWehavealsocometothishallowedspottoremindAmericaofthefierceurgencyofNowThisisnotimetoengageintheluxuryofcoolingoffortotakethetranquilizingdrugofgradualismNowisthetimetomakerealthepromisesofdemocracyNowisthetimetorisefromthedarkanddesolatevalleyofsegregationtothesunlitpathofracialjusticeNowisthetimetoliftournationfromthequicksandsofracialinjusticetothesolidrockofbrotherhoodNowisthetimetomakejusticearealityforallofGodschildrenItwouldbefatalforthenationtooverlooktheurgencyofthemomentThisswelteringsummeroftheNegroslegitimatediscontentwillnotpassuntilthereisaninvigoratingautumnoffreedomandequalityNineteensixtythreeisnotanendbutabeginningAndthosewhohopethattheNegroneededtoblowoffsteamandwillnowbecontentwillhavearudeawakeningifthenationreturnstobusinessasusualAndtherewillbeneitherrestnortranquilityinAmericauntiltheNegroisgrantedhiscitizenshiprightsThewhirlwindsofrevoltwillcontinuetoshakethefoundationsofournationuntilthebrightdayofjusticeemergesButthereissomethingthatImustsaytomypeoplewhostandonthewarmthresholdwhichleadsintothepalaceofjusticeIntheprocessofgainingourrightfulplacewemustnotbeguiltyofwrongfuldeedsLetusnotseektosatisfyourthirstforfreedombydrinkingfromthecupofbitternessandhatredWemustforeverconductourstruggleonthehighplaneofdignityanddisciplineWemustnotallowourcreativeprotesttodegenerateintophysicalviolenceAgainandagainwemustrisetothemajesticheightsofmeetingphysicalforcewithsoulforceThemarvelousnewmilitancywhichhasengulfedtheNegrocommunitymustnotleadustoadistrustofallwhitepeopleformanyofourwhitebrothersasevidencedbytheirpresenceheretodayhavecometorealizethattheirdestinyistiedupwithourdestinyAndtheyhavecometorealizethattheirfreedomisinextricablyboundtoourfreedomWecannotwalkaloneAndaswewalkwemustmakethepledgethatweshallalwaysmarchaheadWecannotturnbackTherearethosewhoareaskingthedevoteesofcivilrightsWhenwillyoubesatisfiedWecanneverbesatisfiedaslongastheNegroisthevictimoftheunspeakablehorrorsofpolicebrutalityWecanneverbesatisfiedaslongasourbodiesheavywiththefatigueoftravelcannotgainlodginginthemotelsofthehighwaysandthehotelsofthecitiesWecannotbesatisfiedaslongasthenegrosbasicmobilityisfromasmallerghettotoalargeroneWecanneverbesatisfiedaslongasourchildrenarestrippedoftheirselfhoodandrobbedoftheirdignitybysignsstatingForWhitesOnlyWecannotbesatisfiedaslongasaNegroinMississippicannotvoteandaNegroinNewYorkbelieveshehasnothingforwhichtovoteNonowearenotsatisfiedandwewillnotbesatisfieduntiljusticerollsdownlikewatersandrighteousnesslikeamightystream¹IamnotunmindfulthatsomeofyouhavecomehereoutofgreattrialsandtribulationsSomeofyouhavecomefreshfromnarrowjailcellsAndsomeofyouhavecomefromareaswhereyourquestquestforfreedomleftyoubatteredbythestormsofpersecutionandstaggeredbythewindsofpolicebrutalityYouhavebeentheveteransofcreativesufferingContinuetoworkwiththefaiththatunearnedsufferingisredemptiveGobacktoMississippigobacktoAlabamagobacktoSouthCarolinagobacktoGeorgiagobacktoLouisianagobacktotheslumsandghettosofournortherncitiesknowingthatsomehowthissituationcanandwillbechangedLetusnotwallowinthevalleyofdespairIsaytoyoutodaymyfriendsAndsoeventhoughwefacethedifficultiesoftodayandtomorrowIstillhaveadreamItisadreamdeeplyrootedintheAmericandreamIhaveadreamthatonedaythisnationwillriseupandliveoutthetruemeaningofitscreedWeholdthesetruthstobeselfevidentthatallmenarecreatedequalIhaveadreamthatonedayontheredhillsofGeorgiathesonsofformerslavesandthesonsofformerslaveownerswillbeabletositdowntogetheratthetableofbrotherhoodIhaveadreamthatonedayeventhestateofMississippiastateswelteringwiththeheatofinjusticeswelteringwiththeheatofoppressionwillbetransformedintoanoasisoffreedomandjusticeIhaveadreamthatmyfourlittlechildrenwillonedayliveinanationwheretheywillnotbejudgedbythecoloroftheirskinbutbythecontentoftheircharacterIhaveadreamtodayIhaveadreamthatonedaydowninAlabamawithitsviciousracistswithitsgovernorhavinghislipsdrippingwiththewordsofinterpositionandnullificationonedayrightthereinAlabamalittleblackboysandblackgirlswillbeabletojoinhandswithlittlewhiteboysandwhitegirlsassistersandbrothersIhaveadreamtodayIhaveadreamthatonedayeveryvalleyshallbeexaltedandeveryhillandmountainshallbemadelowtheroughplaceswillbemadeplainandthecrookedplaceswillbemadestraightandthegloryoftheLordshallberevealedandallfleshshallseeittogetherThisisourhopeandthisisthefaiththatIgobacktotheSouthwithWiththisfaithwewillbeabletohewoutofthemountainofdespairastoneofhopeWiththisfaithwewillbeabletotransformthejanglingdiscordsofournationintoabeautifulsymphonyofbrotherhoodWiththisfaithwewillbeabletoworktogethertopraytogethertostruggletogethertogotojailtogethertostandupforfreedomtogetherknowingthatwewillbefreeonedayAndthiswillbethedaythiswillbethedaywhenallofGodschildrenwillbeabletosingwithnewmeaningMycountrytisoftheesweetlandoflibertyoftheeIsingLandwheremyfathersdiedlandofthePilgrimsprideFromeverymountainsideletfreedomringAndifAmericaistobeagreatnationthismustbecometrueAndsoletfreedomringfromtheprodigioushilltopsofNewHampshireLetfreedomringfromthemightymountainsofNewYorkLetfreedomringfromtheheighteningAllegheniesofPennsylvaniaLetfreedomringfromthesnowcappedRockiesofColoradoLetfreedomringfromthecurvaceousslopesofCaliforniaButnotonlythatLetfreedomringfromStoneMountainofGeorgiaLetfreedomringfromLookoutMountainofTennesseeLetfreedomringfromeveryhillandmolehillofMississippiFromeverymountainsideletfreedomringAndwhenthishappenswhenweallowfreedomringwhenweletitringfromeveryvillageandeveryhamletfromeverystateandeverycitywewillbeabletospeedupthatdaywhenallofGodschildrenblackmenandwhitemenJewsandGentilesProtestantsandCatholicswillbeabletojoinhandsandsinginthewordsoftheoldNegrospiritualFreeatlastFreeatlastThankGodAlmightywearefreeatlast";
+char[] chars = new char[52];
+int nchars = 0;
+int iterations = 500;
+int c = 0;
+PGraphics letter,lettersquare,drawing;
+
+void setup(){
+  //initialize the sketch
+  size(438,600);
+  background(255);
+  //initialize the font
+  //font = loadFont(fontpath);
+  ///*
+  for(int i=0;i<letters.length();i++){
+    boolean found = false;
+    char lc = letters.charAt(i);
+    for(int j=0;j<nchars;j++){
+      if(chars[j]==lc){
+        found = true;
+        break;
+      }
+    }
+    if(!found) chars[nchars++] = lc;
+  }
+  chars = (char[]) subset(chars,0,nchars);
+  font = createFont("Arial",200,true,chars);
+  //*/
+  textAlign(CENTER,CENTER);
+  //load the image that will be filled with letters
+  img = loadImage(imgpath);
+  //posterize the image
+  img.filter(THRESHOLD,0.4);
+  img.filter(BLUR,3);
+  img.filter(THRESHOLD,0.6);
+  //initialize the drawing buffers
+  letter = createGraphics((int)fontsize,(int)fontsize,JAVA2D);
+  lettersquare = createGraphics((int)fontsize,(int)fontsize,P2D);
+  drawing = createGraphics(width,height,JAVA2D);
+  drawing.beginDraw();
+  drawing.background(255);
+  drawing.endDraw();
+}
+
+void draw(){
+  background(255);
+  if(floor(fontsize)>fontend&&c<letters.length()-1){
+    if(!letterfit()){
+      fontsize *= fontsizedecrease;
+    }else{
+      c++;
+      if(c==11){
+        fontsize *= 0.75;
+      }
+    }
+    tint(255);
+    image(drawing,0,0);
+    if(mousePressed){
+      tint(255,100);
+      image(img,0,0);
+    }
+  }else{
+    tint(255);
+    image(drawing,0,0);
+    println(c+" "+letters.length());
+    /*
+    save("mlk-"+hour()+""+minute()+""+second()+".tif");
+    exit();
+    */
+    noLoop();
+  }
+}
+
+boolean letterfit(){
+  letter.beginDraw();
+  letter.background(255,0);
+  letter.fill(0); 
+  letter.textAlign(CENTER,CENTER);
+  letter.translate(fontsize/2,fontsize/2); 
+  letter.rotate(random(TWO_PI));
+  letter.scale(fontsize/fontstart); 
+  letter.textFont(font); 
+  letter.smooth();
+  letter.text(letters.charAt(c),0,0); 
+  letter.endDraw();
+  lettersquare.beginDraw(); 
+  lettersquare.background(255); 
+  lettersquare.image(letter,0,0);
+  lettersquare.filter(ERODE);
+  lettersquare.filter(ERODE);
+  lettersquare.endDraw();
+  for(int i=0;i<iterations;i++){
+    int x = floor(random(width-fontsize));
+    int y = floor(random(height-fontsize));
+    boolean fits = true;
+    for(int dx=0;dx<fontsize&&fits;dx++){ 
+      for(int dy=0;dy<fontsize&&fits;dy++){
+        if(brightness(img.get(x+dx,y+dy))>127){
+          fits = false;
+          break;
+        }
+        if(brightness(lettersquare.get(dx,dy))<127){ 
+          if(brightness(drawing.get(x+dx,y+dy))<127){
+            fits = false;
+          }
+        }
+      }
+    }
+    if(fits){
+      drawing.beginDraw();
+      drawing.image(letter,x,y);
+      drawing.endDraw();
+      return true;
+    }
+  }
+  return false;
+}
+
+/*
+void mousePressed(){
+  save("mlk-"+hour()+""+minute()+""+second()+".tif");
+  exit();
+}
+*/

project/filters/index.html

+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
+        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
+	<head>
+	        <!-- charset must remain utf-8 to be handled properly by Processing -->
+		<meta http-equiv="content-type" content="text/html; charset=utf-8" />
+		
+		<title>filters : Built with Processing</title>
+		
+		<style type="text/css">
+		/* <![CDATA[ */
+	
+		body {
+  		  margin: 60px 0px 0px 55px;
+		  font-family: verdana, geneva, arial, helvetica, sans-serif; 
+		  font-size: 11px; 
+		  background-color: #ddddcc; 
+		  text-decoration: none; 
+		  font-weight: normal; 
+		  line-height: normal; 
+		}
+		 
+		a          { color: #3399cc; }
+		a:link     { color: #3399cc; text-decoration: underline; }
+		a:visited  { color: #3399cc; text-decoration: underline; }
+		a:active   { color: #3399cc; text-decoration: underline; }
+		a:hover    { color: #3399cc; text-decoration: underline; }
+	
+		/* ]]> */
+		</style>
+	 
+	</head>
+	<body>
+		<div id="content">
+			<div id="filters_container">
+			
+			<!--[if !IE]> -->
+				<object classid="java:filters.class" 
+            			type="application/x-java-applet"
+            			archive="filters.jar"
+            			width="438" height="600"
+            			standby="Loading Processing software..." >
+            			
+					<param name="archive" value="filters.jar" />
+				
+					<param name="mayscript" value="true" />
+					<param name="scriptable" value="true" />
+				
+					<param name="image" value="loading.gif" />
+					<param name="boxmessage" value="Loading Processing software..." />
+					<param name="boxbgcolor" value="#FFFFFF" />
+				
+					<param name="test_string" value="outer" />
+			<!--<![endif]-->
+				
+				<object classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93" 
+						codebase="http://java.sun.com/update/1.5.0/jinstall-1_5_0_15-windows-i586.cab"
+						width="438" height="600"
+						standby="Loading Processing software..."  >
+						
+					<param name="code" value="filters" />
+					<param name="archive" value="filters.jar" />
+					
+					<param name="mayscript" value="true" />
+					<param name="scriptable" value="true" />
+					
+					<param name="image" value="loading.gif" />
+					<param name="boxmessage" value="Loading Processing software..." />
+					<param name="boxbgcolor" value="#FFFFFF" />
+					
+					<param name="test_string" value="inner" />
+					
+					<p>
+						<strong>
+							This browser does not have a Java Plug-in.
+							<br />
+							<a href="http://java.sun.com/products/plugin/downloads/index.html" title="Download Java Plug-in">
+								Get the latest Java Plug-in here.
+							</a>
+						</strong>
+					</p>
+				
+				</object>
+				
+			<!--[if !IE]> -->
+				</object>
+			<!--<![endif]-->
+			
+			</div>
+			
+			<p>
+			
+			</p>
+			
+			<p>
+			Source code: <a href="filters.pde">filters</a> 
+			</p>
+			
+			<p>
+			Built with <a href="http://processing.org" title="Processing.org">Processing</a>
+			</p>
+		</div>
+	</body>
+</html>

project/filters/loading.gif

Added
New image

project/ipab/Node.pde

   float darkness;
 
 
-  public Node(Node parent, String folder, int level, int order) {
-    super(parent, folder, level, order);
-    String[] contents = new String[5];
-    ArrayList cities = new ArrayList();
-    cities.add("Bangalore");
-    cities.add("Mysore");
-    cities.add("Delhi");
-    cities.add("Bombay");
-    cities.add("Kolkatta");
+  public Node(Node parent, XMLElement content, int level, int order) {
+    super(parent,content, order);
+    int kids = content.getChildCount();
+
+    println("Now working for"+content.getString("name")+"  Totoal children="+kids);
     
-    ArrayList dept = new ArrayList();
-    dept.add("Police");
-    dept.add("Registration");
-    dept.add("Revenue");
-    dept.add("Income Tax");
-    dept.add("Health");
-    
-    if(level == 0){
-      dept.toArray(contents);
-    }else{
-       cities.toArray(contents);
-    }  
-
-    
-    if (contents != null) {
-      contents = sort(contents);
-      items = new Mappable[contents.length];
+    if (kids > 0) {
+      items = new Mappable[kids];
       int count = 0;
-      for (int i = 0; i < contents.length; i++) {
-        String NodeElement = contents[i];
-        NodeElement newItem = null;
-       if (dept.contains(NodeElement)) {
-          newItem = new Node(this, NodeElement, level+1, count);
-        } else {
-          newItem = new NodeElement(this, NodeElement, level+1, count);
-        }
+      for (int i = 0; i < kids; i++) {
+        String colorString =  "";
+        NodeElement newItem = new Node(this, content.getChild(i), content.getChild(i).getInt("level"), count);
         items[count++] = newItem;
         size += newItem.getSize();
       }

project/ipab/NodeElement.pde

   float boxRight, boxBottom;
 
 
-  NodeElement(Node parent, String file, int level, int order) {
+  NodeElement(Node parent, XMLElement content, int order) {
     this.parent = parent;
-    this.file = file;
+    this.file = content.getString("name");
     this.order = order;
-    this.level = level;
+    this.level = content.getInt("level");
+    String cString = content.getString("color");
+    String[] list = split(cString, ','); 
+    this.c = color(Integer.parseInt(list[0]),Integer.parseInt(list[1]),Integer.parseInt(list[2]));
+    println("color = "+c);
       
     name = file.toString();
     size =  random(1, 150);
 
     colorMode(HSB, 360, 100, 100);
     if (parent == zoomItem) {
-      //c = color(hue, 80, 80);
+     // c = color(hue, 80, 80);
         c = color(int(random(0,255)),int(random(0,255)),int(random(0,255)));
+       // c = this.c;
     } else if (parent != null) {
         c = color(int(random(0,255)),int(random(0,255)),int(random(0,255)));
-      //c = color(parent.hue, 80, brightness);
+     // c = color(parent.hue, 80, brightness);
+     //c = parent.c;
     }
     colorMode(RGB, 255);
   }

project/ipab/data/tree.xml

+<tree name="BribePatterns" level="0" color="100,200,300">
+<node level="1" name="Bangalore" value="100" color="100,200,300" >
+	<node level="2" name="Police" value="10" color="100,200,300">
+	</node>
+	<node level="2" name="Revenue" value="20" color="150,240,300">
+	</node>
+</node>
+<node level="1" name="Mysore" value="20" color="140,210,300" >
+	<node level="2" name="Police" value="10" color="100,200,300">
+	</node>
+	<node level="2" name="Revenue" value="20" color="200,200,100">
+	</node>
+</node>
+
+</tree>

project/ipab/ipab.pde

 RankedLongArray modTimes = new RankedLongArray();
 
 PFont font;
-
+XMLElement xml;
 
 void setup() {
     size(500, 500);
     noStroke();
   
    font = createFont("SansSerif", 13);
-   setRoot("Locations");
+   xml = new XMLElement(this, "tree.xml");
+   String title =  xml.getString("name");
+   print(title);
+   setRoot(xml);
 }
 
   
-void setRoot(String folder) {
-  Node tm = new Node(null, folder, 0, 0);
+void setRoot(XMLElement content) {
+  println("Root is set");
+  color c = #233456;
+  Node tm = new Node(null, content,  0, 0);
   tm.setBounds(0, 0, width, height);
   tm.contentsVisible = true;
     

project/tsp/data/CharterBT-Roman-48.vlw

Binary file added.

project/tsp/tsp.pde

+// Written by Torbjoern Haugen 17. april 2010
+// inspired by the source example from
+// "Artificial Intellgence A Systems Approach
+// by M. Tim Jones.
+// http://www.amazon.com/Artificial-Intelligence-Approach-Computer-Engineering/dp/0977858235
+ 
+ 
+/* bugs:
+-movment of individual ants isnt animated right. can either use current&next, req. mod to chooseNextCity
+-sometimes hangs in while(1) loop, cant find new city with p>rnd
+*/
+ 
+import controlP5.*;
+ 
+ControlP5 controlP5;
+ 
+int num_cities;
+int num_ants;
+ 
+class City
+{
+  float x,y;
+}
+int edgeLen = 200; // max edge length when creating city graph.
+ 
+class Ant
+{
+  int current_city;
+  int next_city;
+  int tabu[];
+  int tour_index;
+  int tour[];
+  double tour_length;
+ 
+  Ant(){
+    tabu = new int[num_cities];
+    tour = new int[num_cities];
+  }
+}
+ 
+// ACO-equation variables
+// keep alpha,beta and rho within [0,1]
+float alpha_value = 1.0; // higher value -> more scouting behaviour
+float beta_value = 1.0; // higher value -> higher importance of distance cost
+float rho = 0.9; // decay rate
+float qval = 500; // amount of pherom to spread on tour.
+ 
+City cities[];
+Ant ants[];
+float precomp_distance[][]; // edge length, store distances between cities
+float pherom[][]; // pherom levels on each edge
+float base_pherom; // minimum pherom level
+ 
+double best_tour; // length of best tour found
+int best_index = -1; // index of ants[] with best tour
+int best_tour_history[]; // save ant tour history here
+ 
+int iterations; // no of iterations used on ACO
+ 
+float iterationTimer = 0; // remember time
+float iterationTimeLength = 0.05; // how fast to iterate in seconds
+int grabbedNode = -1;
+ 
+void initACO()
+{
+  iterations = 0;
+  num_cities = 20;
+  num_ants = 20;
+ 
+  best_tour = 100000.0;
+  base_pherom = 1.0 / num_cities;
+ 
+  cities = new City[num_cities];
+  ants = new Ant[num_ants];
+  for(int i=0; i < num_ants; i++){
+     ants[i] = new Ant();
+  }
+   
+  precomp_distance = new float[num_cities][num_cities];
+  pherom = new float[num_cities][num_cities]; 
+  best_tour_history = new int[num_cities];
+   
+  initCities();
+  initAnts();
+}
+ 
+void setup()
+{
+  size(400,400);
+  frameRate(35);
+  controlP5 = new ControlP5(this);
+  // addSlider(java.lang.String theName, float theMin, float theMax,
+  //float theDefaultValue, int theX, int theY, int theW, int theH)
+  controlP5.addSlider("alphaValue",0,1,.95,
+                      5,20*1,100,15).setId(1);
+                       
+  controlP5.addSlider("betaValue",0,1,.8,
+                      5,20*2,100,15).setId(2);                         
+ 
+  controlP5.addSlider("rhoValue",0,1,.9,
+                      5,20*3,100,15).setId(3);
+ 
+  controlP5.addSlider("iterationIntervalPause",0.01,0.5,0.4,
+                      5,20*4,100,15).setId(4);                     
+  initACO();
+  PFont myfont;
+  myfont = loadFont("CharterBT-Roman-48.vlw");
+  textFont(myfont, 12);
+}
+ 
+void draw()
+{
+  background(127,127,127);
+   
+  float time = (float) millis() / 1000.0;
+  if(time > iterationTimer)
+  {
+    for(int i=0; i<num_cities; i++)
+      if( moveAnts() == 0) // are all ants finished moving?
+      {
+          evaporatePheromoneTrails();
+          intensifyPheromoneTrails();
+          findBestTour();
+          initAnts(); // reset ant position and tour
+      }
+    iterations+=num_cities;
+    iterationTimer = time + iterationTimeLength;  
+  }
+ 
+  if(best_index >= 0) // found a good tour?
+  {
+    drawBestTour();
+  }
+   
+  // draw city nodes
+  strokeWeight(1.0);
+  fill(255,255,255);
+  for(int i=0; i < num_cities; i++)
+  {
+    rect( cities[i].x-5, cities[i].y-5, 10, 10);
+  }
+    
+  //float t = 1-(iterationTimer-time)/iterationTimeLength;
+  if( iterationTimeLength > 0.001 )
+  {
+    //drawMovingAnts(t);
+  }
+   
+  colorMode(RGB, 256,256,256);
+   
+  text("iterations: "+iterations+", best tour: "+nf( (float)best_tour,5,1),5,15);
+  //text("t: "+t,15,15*3);
+  //text("alpha: "+nf( alpha_value, 1,2),15,15*4);
+  //text("beta: "+nf( beta_value, 1,2),15,15*5);
+  //text("rho: "+nf( rho, 1,2),15,15*6);
+  text("spacebar = reset, mouse = move nodes",50,height-5);
+  //delay(16);
+}
+ 
+public void alphaValue(float theValue) {
+  alpha_value = theValue;
+}
+public void betaValue(float theValue) {
+  beta_value = theValue;
+}
+public void rhoValue(float theValue) {
+  rho = theValue;
+}
+public void iterationIntervalPause(float theValue) {
+  iterationTimeLength = theValue;
+}
+ 
+void mouseDragged()
+{
+  if(grabbedNode > -1) // move node
+  {
+    cities[grabbedNode].x = mouseX;
+    cities[grabbedNode].y = mouseY;
+  }
+}
+ 
+void mousePressed() // mousePressed is called on an event! it isnt polled!
+{
+  if (mouseButton == LEFT && grabbedNode == -1) // not moving node, look for closest to mouse
+  {
+    float mindist = 10*10; // distance^2. look for node within radius.
+    for(int i=0; i<num_cities; i++){
+      float dx = abs(mouseX - cities[i].x);
+      float dy = abs(mouseY - cities[i].y);
+      float distance = dx*dx + dy*dy;
+      if(distance < mindist){
+        mindist = distance;
+        grabbedNode = i;
+      }
+    }
+  }
+ 
+}
+ 
+void mouseReleased()
+{
+  if(grabbedNode > -1)
+  {
+    cities[grabbedNode].x = mouseX;
+    cities[grabbedNode].y = mouseY;
+    grabbedNode = -1;
+     
+     
+    best_index = -1;
+    best_tour = 1e6;
+    iterations = 0;
+    resetPherom();
+    computeCityDistances();
+  }
+}
+ 
+void keyPressed()
+{
+  if (key == ' ') initACO();
+}
+ 
+void drawBestTour()
+{
+  int startCity = best_tour_history[0];
+  int nextCity = 0;
+  for(int i=0; i < num_cities; i++)
+  {
+    nextCity = best_tour_history[i];
+    strokeWeight( pherom[startCity][nextCity] );
+    stroke( color(0,0,0) );
+    line( cities[startCity].x, cities[startCity].y,
+    cities[nextCity].x, cities[nextCity].y );
+    startCity = nextCity;
+  }
+   
+  // close loop
+  startCity = best_tour_history[0];
+  nextCity = best_tour_history[num_cities-1];
+  strokeWeight( pherom[startCity][nextCity] );
+  line( cities[startCity].x, cities[startCity].y,
+  cities[nextCity].x, cities[nextCity].y );
+}
+ 
+void drawMovingAnts(float t)
+{
+    colorMode(HSB, num_ants, 1.0, 1.0);
+    ellipseMode(CENTER);
+    int j = int( 19.0*t );
+    float jsmooth = iterationTimeLength/(19.0*t);
+    for(int i=0; i < num_ants; i++){
+      //for(int j=0; j<num_cities; j++){
+         //Ant a = ants[i];
+        int now = ants[i].tour[ j ];
+        int next = ants[i].tour[ (j+1)%num_cities ];
+         
+        float xpos = lerp( cities[now].x, cities[next].x, jsmooth );
+        float ypos = lerp( cities[now].y, cities[next].y, jsmooth );
+        fill( i,1.0,1.0 );
+        ellipse(xpos, ypos,4,4);
+      //}
+ 
+    }
+}
+ 
+void initCities()
+{
+  // randomly place cities on the map
+  float angIncrement = (TWO_PI) / float(num_cities);
+  float ang = 0.0;
+  for(int i=0; i < num_cities; i++)
+  {
+    cities[i] = new City();
+    cities[i].x = width/2-edgeLen/2 + ( (1.0+cos(ang))/2.0*edgeLen ) + random(5,10);
+    cities[i].y = height/2-edgeLen/2 + ( (1.0+sin(ang))/2.0*edgeLen ) + random(5,10);
+    ang += angIncrement;
+     
+    if(random(0.0, 1.0) < 0.2)
+    {
+      cities[i].x = width/2-edgeLen/2 +(int)random(0,edgeLen);
+      cities[i].y =  height/2+(int)random(0,edgeLen);
+    }
+     
+  }
+  cities[0].x = 300;
+  cities[0].y = 100;
+   
+  resetPherom();
+ 
+  // precompute the distances between cities
+  computeCityDistances();
+}
+ 
+void computeCityDistances()
+{
+  for(int from=0; from < num_cities; from++){
+    for(int to=0; to < num_cities; to++){
+      float dx = abs( cities[from].x - cities[to].x );
+      float dy = abs( cities[from].y - cities[to].y );
+      float distance = sqrt( (dx*dx) + (dy*dy) );
+      precomp_distance[from][to] = distance;
+      precomp_distance[to][from] = distance;
+    }
+  }
+}
+ 
+void resetPherom()
+{
+  for(int from=0; from < num_cities; from++){
+    for(int to=0; to < num_cities; to++){
+      pherom[from][to] = base_pherom;
+      pherom[to][from] = base_pherom;
+    }
+  }
+}
+ 
+void findBestTour()
+{
+  for(int i=0; i < num_ants; i++){
+    if( ants[i].tour_length < best_tour){
+      best_tour = ants[i].tour_length;
+      best_index = i;
+       
+      for(int j=0; j < num_cities; j++) // remember tour
+      {
+        best_tour_history[j] = ants[i].tour[j];
+      }
+    }
+  }
+}
+ 
+void initAnts()
+{
+  int city = 0;
+  // place ants throughout the cities (evenly if possible)
+  for(int i=0; i< num_ants; i++){
+     
+    for(int j=0; j< num_cities; j++){
+      ants[i].tabu[j] = 0;
+      ants[i].tour[j] = 0;
+    }
+    // place this ant in a city, and reflect it in the tabu
+    ants[i].current_city = city; //(int)random(0,num_cities);//city;
+    //ants[i].next_city = city; // will be set on choosenext
+    city++;
+    city %= num_cities;
+    ants[i].tabu[ ants[i].current_city ] = 1;
+ 
+    // update the tour, and current tour length given the current path
+    ants[i].tour[0] = ants[i].current_city;
+    ants[i].tour_index = 1;
+    ants[i].tour_length = 0.0;
+  }
+}
+ 
+void chooseNextCity(Ant ant)
+{
+   
+  double d = 0.0;
+  double p = 0.0;
+   
+  int from = ant.current_city;
+   
+  //
+  int to=0;
+  for(to=0; to < num_cities; to++){ 
+    if( ant.tabu[to] == 0){ // if city not yet visited
+      d += pow(pherom[from][to], (float)alpha_value) *
+        pow( (1.0/precomp_distance[from][to]), (float)beta_value );
+    }
+  }
+ 
+  // Probabilistically select the next city
+  to = 0;
+  int stuck = 0;
+  while(true){
+    if( ant.tabu[to] == 0){ // if city not yet visited
+    // equation 14.1
+    p = pow(pherom[from][to], (float)alpha_value) *
+                  pow( (1.0/precomp_distance[from][to]), (float)beta_value ) / d;
+    if( random(0.0, 1.0) <= p ) break; // roll dice and see if we choose to go to city
+    }
+    to++;
+    to %= num_cities;
+    // shouldnt need this:
+    stuck++;
+    if(stuck > 200) break;
+  }
+ 
+  // we have our new destination, update for new city
+  ant.next_city = to;
+  ant.tabu[ant.next_city] = 1; // mark as visited
+  ant.tour[ant.tour_index] = ant.next_city; // update tour log
+  ant.tour_index++;
+  ant.tour_length += precomp_distance[ant.current_city][ant.next_city];
+ 
+  // visited all cities, add distance from start to end.
+  if(ant.tour_index == num_cities){
+    ant.tour_length +=
+      precomp_distance[ ant.tour[num_cities-1] ]  [ant.tour[0] ];
+  }
+  ant.current_city = ant.next_city; //!!!
+}
+ 
+int moveAnts()
+{
+  int moved = 0;
+  for(int i=0; i < num_ants; i++){
+    if( ants[i].tour_index < num_cities ){
+      chooseNextCity( ants[i] );
+      moved++;
+    }
+  }
+  return moved; // if we couldnt move, we have visited all. We need to re-init. Return 0
+}
+ 
+void evaporatePheromoneTrails()
+{
+  for(int from = 0; from < num_cities; from++){
+    for(int to=0; to < num_cities; to++){
+      // equation 14.4
+      pherom[from][to] *= (1.0 - rho);
+      if(pherom[from][to] < 0.0){
+        pherom[from][to] = base_pherom;
+      }
+    }
+  }
+}
+void intensifyPheromoneTrails()
+{
+  for(int i=0; i < num_ants; i++){
+    for(int city = 0; city < num_cities; city++){
+      int from = ants[i].tour[city];
+      int to = ants[i].tour[ ((city+1) % num_cities) ];
+ 
+      // eq 14.2 / 14.3
+      pherom[from][to] += (qval/ants[i].tour_length) * rho;
+      pherom[to][from] = pherom[from][to]; 
+    }
+  }
+}
+ 
+ 
+void drawArrowHead(float sx, float sy, float ex, float ey, float len)
+{
+   //line(sx,sy,ex,ey);
+   float angle = atan2(ey-sy,ex-sx);
+   float ofs=PI*1.2;
+    
+   line(ex, ey, ex+cos(angle+ofs)*len, ey+sin(angle+ofs)*len);
+   line(ex,ey,ex+cos(angle-ofs)*len, ey+sin(angle-ofs)*len);
+}
+
+