
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>daniel shiffman</title>
	<atom:link href="http://www.shiffman.net/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.shiffman.net</link>
	<description></description>
	<lastBuildDate>Thu, 14 Mar 2013 19:40:50 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=</generator>
		<item>
		<title>Box2D Blob Skeleton</title>
		<link>http://www.shiffman.net/2012/03/01/box2d-blob-skeleton/</link>
		<comments>http://www.shiffman.net/2012/03/01/box2d-blob-skeleton/#comments</comments>
		<pubDate>Thu, 01 Mar 2012 20:45:25 +0000</pubDate>
		<dc:creator>Daniel</dc:creator>
				<category><![CDATA[processing.org]]></category>
		<category><![CDATA[box2d]]></category>
		<category><![CDATA[nature of code]]></category>

		<guid isPermaLink="false">http://www.shiffman.net/?p=1095</guid>
		<description><![CDATA[This week in nature of code, we talked about using a physics engine to build a skeleton for an onscreen character. Two projects we referenced are: Karsten Schmidt&#8217;s Nokia Friends and Elie Zananiri&#8217;s Big Screams. Both of these projects involve &#8230; <a href="http://www.shiffman.net/2012/03/01/box2d-blob-skeleton/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>This week in nature of code, we talked about using a physics engine to build a skeleton for an onscreen character.   Two projects we referenced are:</p>
<p><iframe src="http://player.vimeo.com/video/1472427" width="250" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe> <iframe src="http://player.vimeo.com/video/8487873" width="250" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe></p>
<p>Karsten Schmidt&#8217;s <a href="http://postspectacular.com/work/nokia/friends/start">Nokia Friends</a> and Elie Zananiri&#8217;s <a href="http://www.bigscreams.com">Big Screams</a>.</p>
<p>Both of these projects involve an underlying skeleton (Nokia Friends uses toxiclibs verlet physics and Big Screams uses Box2D) that serves as the structure for a cute, cuddly, jiggly creature drawn on top.   In my efforts to expand the nature of code materials this semester, I&#8217;ve released a new example that demonstrates this technique.  It constructs a skeleton of out Box2D bodies and distance joints and draws a curvy polygon with eyes and mouth on top.</p>
<p><img src="http://www.shiffman.net/wp/wp-content/uploads/2012/03/blob11.png" alt="" title="blob1" width="240" height="143" class="alignnone size-full wp-image-1108" />  <img src="http://www.shiffman.net/wp/wp-content/uploads/2012/03/blob21.png" alt="" title="blob2" width="240" height="143" class="alignnone size-full wp-image-1108" /> </p>
<p>Source: <a href='http://www.shiffman.net/wp/wp-content/uploads/2012/03/BlobSkeleton.zip'>BlobSkeleton.zip</a><br />
(Requires pbox2d: <a href="https://github.com/shiffman/PBox2D">https://github.com/shiffman/PBox2D</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.shiffman.net/2012/03/01/box2d-blob-skeleton/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Night #8: Rendering an image sequence</title>
		<link>http://www.shiffman.net/2011/12/28/night-8-rendering-out-as-image-sequence/</link>
		<comments>http://www.shiffman.net/2011/12/28/night-8-rendering-out-as-image-sequence/#comments</comments>
		<pubDate>Wed, 28 Dec 2011 16:13:43 +0000</pubDate>
		<dc:creator>Daniel</dc:creator>
				<category><![CDATA[processing.org]]></category>
		<category><![CDATA[image sequence]]></category>
		<category><![CDATA[png]]></category>
		<category><![CDATA[render]]></category>
		<category><![CDATA[saveFrame]]></category>

		<guid isPermaLink="false">http://www.shiffman.net/?p=1073</guid>
		<description><![CDATA[How can one render a movie from a Processing sketch? In Processing 1.5.1, there is a class called MovieMaker which generates a Quicktime file directly. However, this class uses ye old Quicktime for Java and will be removed from Processing &#8230; <a href="http://www.shiffman.net/2011/12/28/night-8-rendering-out-as-image-sequence/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>How can one render a movie from a Processing sketch?  In Processing 1.5.1, there is a class called MovieMaker which generates a Quicktime file directly.  However, this class uses ye old Quicktime for Java and will be removed from Processing 2.0.  Instead, 2.0 is going to introduce a MovieMaker &#8220;tool&#8221; which will generate a movie file from a directory containing an image sequence.  So how do you get this image sequence?  Easy:</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">void</span> draw<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  saveFrame<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;output/frames####.png&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>This will create a folder called &#8220;output&#8221; in your sketch folder and for each frame of draw(), it will write a file &#8212; frames0001.png, frames0002.png, etc.  The &#8216;#&#8217; sign tells processing to auto-number the images.</p>
<p>There are a couple additional tricks included in this new example.  First, it uses a boolean variable to turn rendering on and off and cycles the boolean in keyPressed() allowing recording to be stopped and started by pressing &#8216;r&#8217;.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">void</span> draw<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #666666; font-style: italic;">// If we are recording call saveFrame!</span>
  <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>recording<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    saveFrame<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;output/frames####.png&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000066; font-weight: bold;">void</span> keyPressed<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>  
  <span style="color: #666666; font-style: italic;">// If we press r, start or stop recording!</span>
  <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>key <span style="color: #339933;">==</span> <span style="color: #0000ff;">'r'</span> <span style="color: #339933;">||</span> key <span style="color: #339933;">==</span> <span style="color: #0000ff;">'R'</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    recording <span style="color: #339933;">=</span> <span style="color: #339933;">!</span>recording<span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>In addition, if you draw anything after saveFrame() it won&#8217;t actually appear in the output, but will be seen on screen.  This is useful for debugging information that you don&#8217;t want included in the render.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">void</span> draw<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
  <span style="color: #666666; font-style: italic;">// Draw lots of stuff to be recorded!</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>recording<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    saveFrame<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;output/frames####.png&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #666666; font-style: italic;">// Draw our debugging stuff that won't be recorded!</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Until 2.0 is released, I recommend you use 3rd party software to take the image sequence and turn it into a movie.  The old Quicktime 7 will do the trick, as well as any number of video production applications like final cut, after effects, iMovie, etc.  The nice thing about using a PNG sequence is that the images are uncompressed, but aren&#8217;t as large as say TIFFs.  I don&#8217;t recommend saving JPGs because then you will likely be compressing twice (once when saving the image, once when exporting the movie file).</p>
<p><a href='http://www.shiffman.net/wp/wp-content/uploads/2011/12/SavingFrames.zip'><img src="http://www.shiffman.net/wp/wp-content/uploads/2011/12/frames.png" alt="" title="frames" width="590" height="352" class="alignnone size-full wp-image-1075" /></a></p>
<p>Source: <a href='http://www.shiffman.net/wp/wp-content/uploads/2011/12/SavingFrames.zip'>SavingFrames.zip</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.shiffman.net/2011/12/28/night-8-rendering-out-as-image-sequence/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Night #7: Nature of Code excerpts</title>
		<link>http://www.shiffman.net/2011/12/27/night-7-nature-of-code-excerpts/</link>
		<comments>http://www.shiffman.net/2011/12/27/night-7-nature-of-code-excerpts/#comments</comments>
		<pubDate>Tue, 27 Dec 2011 20:48:41 +0000</pubDate>
		<dc:creator>Daniel</dc:creator>
				<category><![CDATA[processing.org]]></category>
		<category><![CDATA[fractal]]></category>
		<category><![CDATA[genetic algorithm]]></category>
		<category><![CDATA[nature of code]]></category>
		<category><![CDATA[neural network]]></category>
		<category><![CDATA[tree]]></category>

		<guid isPermaLink="false">http://www.shiffman.net/?p=1052</guid>
		<description><![CDATA[For tonight&#8217;s post, I&#8217;m going to include three new examples from my upcoming Nature of Code book. I&#8217;ll also excerpt some of the text with these examples below. This first example expands on the existing Recursive Tree example that comes &#8230; <a href="http://www.shiffman.net/2011/12/27/night-7-nature-of-code-excerpts/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>For tonight&#8217;s post, I&#8217;m going to include three new examples from my upcoming Nature of Code book.  I&#8217;ll also excerpt some of the text with these examples below.</p>
<p>This first example expands on the existing <a href="http://processing.org/learning/topics/tree.html">Recursive Tree</a> example that comes with Processing.</p>
<p><strong>Chapter 8: Recursion and Fractals</strong></p>
<p>The recursive tree fractal is a nice example of a scenario in which adding a little bit of randomness can make the tree look more natural.  Take a look outside and you’ll notice that branch lengths and angles vary from branch to branch, not to mention the fact that branches don’t all have exactly the same number of smaller branches.   First, let’s see what happens when we simply vary the angle and length.  This is a pretty easy one, given that we can just ask Processing for a random number each time we draw the tree.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">void</span> branch<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">float</span> len<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>	
  <span style="color: #666666; font-style: italic;">// Start by picking a random angle for each branch</span>
  <span style="color: #000066; font-weight: bold;">float</span> theta <span style="color: #339933;">=</span> random<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">0</span>,PI<span style="color: #339933;">/</span><span style="color: #cc66cc;">3</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>  
&nbsp;
  line<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">0</span>, <span style="color: #cc66cc;">0</span>, <span style="color: #cc66cc;">0</span>, <span style="color: #339933;">-</span>len<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  translate<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">0</span>, <span style="color: #339933;">-</span>len<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  len <span style="color: #339933;">*=</span> <span style="color: #cc66cc;">0.66</span><span style="color: #339933;">;</span>
  <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>len <span style="color: #339933;">&gt;</span> <span style="color: #cc66cc;">2</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    pushMatrix<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>    
    rotate<span style="color: #009900;">&#40;</span>theta<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>   
    branch<span style="color: #009900;">&#40;</span>len<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    popMatrix<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>     
    pushMatrix<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    rotate<span style="color: #009900;">&#40;</span><span style="color: #339933;">-</span>theta<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    branch<span style="color: #009900;">&#40;</span>len<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    popMatrix<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>In the above function, we always call branch() twice.  But why not pick a random number of branches and call branch() that number of times?</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">void</span> branch<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">float</span> len<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>	
&nbsp;
  line<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">0</span>, <span style="color: #cc66cc;">0</span>, <span style="color: #cc66cc;">0</span>, <span style="color: #339933;">-</span>len<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  translate<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">0</span>, <span style="color: #339933;">-</span>len<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>len <span style="color: #339933;">&gt;</span> <span style="color: #cc66cc;">2</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// Call branch() a random number of times</span>
    <span style="color: #000066; font-weight: bold;">int</span> n <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">int</span><span style="color: #009900;">&#40;</span>random<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">1</span>,<span style="color: #cc66cc;">4</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>		 
    <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> i <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> n<span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>	
&nbsp;
      <span style="color: #666666; font-style: italic;">// Each branch gets its own random angle</span>
      <span style="color: #000066; font-weight: bold;">float</span> theta <span style="color: #339933;">=</span> random<span style="color: #009900;">&#40;</span><span style="color: #339933;">-</span>PI<span style="color: #339933;">/</span><span style="color: #cc66cc;">2</span>, PI<span style="color: #339933;">/</span><span style="color: #cc66cc;">2</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> 
      pushMatrix<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>     
      rotate<span style="color: #009900;">&#40;</span>theta<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      branch<span style="color: #009900;">&#40;</span>h<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      popMatrix<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>The example below takes the above a few steps further.  It uses Perlin noise to generate the angles, as well as animate them.  In addition, it draws each branch with a thickness according to its level and sometimes shrinks a branch by a factor of two to vary where the levels begin.</p>
<p><a href='http://www.shiffman.net/wp/wp-content/uploads/2011/12/TreeStochasticNoise.zip'><img src="http://www.shiffman.net/wp/wp-content/uploads/2011/12/tree1.png" alt="" title="tree" width="580" height="347" class="alignnone size-full wp-image-1058" /></a></p>
<p><a href='http://www.shiffman.net/wp/wp-content/uploads/2011/12/TreeStochasticNoise.zip'>TreeStochasticNoise.zip</a></p>
<p>Next up an excerpt from the Genetic Algorithm chapter.</p>
<p><strong>Chapter 9: Evolution and Code</strong></p>
<p>In 2009, <a href="http://blog.blprnt.com">Jer Thorp</a>  released a great genetic algorithms example on his blog entitled “<a href="http://blog.blprnt.com/blog/blprnt/project-smart-rockets">Smart Rockets</a>.”   Jer points out that NASA uses evolutionary computing techniques to solve all sorts of problems, from satellite antenna design to rocket firing patterns. This inspired him to create a Flash demonstration of evolving rockets.  Here is a description of the scenario:</p>
<p>A population of rockets launches from the bottom of the screen with the goal of hitting a target at the top of the screen (with obstacles blocking a straight line path).   </p>
<p><img src="http://www.shiffman.net/wp/wp-content/uploads/2011/12/rockets.png" alt="" title="rockets" width="300" height="187" class="alignnone size-full wp-image-1061" /></p>
<p>Each rocket is equipped with five thrusters of variable strength and direction.    The thrusters don’t fire all at once and continuously; rather, they fire one at a time in a custom sequence.  In this example, we’re going to evolve our own simplified Smart Rockets, inspired by Jer Thorp’s.   You can leave implementing some of Jer’s additional advanced features as an exercise.  </p>
<p>Our rockets will have only one thruster, and this thruster will be able to fire in any direction with any strength in every single frame of animation.  This isn&#8217;t particularly realistic, but it will make building out the framework a little easier. (We can always make the rocket and its thrusters more advanced and realistic later.)   </p>
<p><a href='http://www.shiffman.net/wp/wp-content/uploads/2011/12/SmartRockets.zip'><img src="http://www.shiffman.net/wp/wp-content/uploads/2011/12/rockets2.png" alt="" title="rockets2" width="590" height="352" class="alignnone size-full wp-image-1063" /></a></p>
<p>Source: <a href='http://www.shiffman.net/wp/wp-content/uploads/2011/12/SmartRockets.zip'>SmartRockets.zip</a></p>
<p>And here&#8217;s a short excerpt from the beginning of the chapter on neural networks, as well as the example that closes out the chapter demonstrating how to visualize the flow of information through a network.</p>
<p><strong>Chapter 10: The Brain</strong></p>
<p>Computer scientists have long been inspired by the human brain.   In 1943, Warren S. McCulloch, a neuroscientist, and Walter Pitts, a logician, developed the first conceptual model of an artificial neural network.  In their paper, &#8220;A logical calculus of the ideas imminent in nervous activity,” they describe the concept of a neuron, a single cell living in a network of cells that receives inputs, processes those inputs, and generates an output.</p>
<p>Their work, and the work of many scientists and researchers that followed, was not meant to accurately describe how the biological brain works.  Rather, an artificial neural network (which we will now simply refer to as a “neural network”) was designed as a computational model based on the brain that can solve certain kinds of problems.</p>
<p>It’s probably pretty obvious to you that there are certain problems that are incredibly simple for a computer to solve, but difficult for you.  Take the square root of 964,324, for example.  A quick line of code produces the value 982, a number Processing computed in less than a millisecond.   There are, on the other hand, problems that are incredibly simple for you or me to solve, but not so easy for a computer.   Show any toddler a picture of a kitten or puppy and they’ll be able to tell you very quickly which one is which.   Say hello and shake my hand one morning and you should be able to pick me out of a crowd of people the next day.  But need a machine to perform one of these tasks?  People have already spent careers researching and implementing complex solutions.</p>
<p>The most common application of neural networks in computing today is to perform one of these easy-for-a-human, difficult-for-a-machine” tasks, often referred to as pattern classification.   Applications range from optical character recognition (turning printed or handwritten scans into digital text) to facial recognition.  We don’t have the time or need to use some of these more elaborate artificial intelligence algorithms here, but if you are interested in researching neural networks, I’d recommend the books Artificial Intelligence: A Modern Approach by Stuart J. Russell and Peter Norvig and AI for Game Developers by David M. Bourg and Glenn Seemann.</p>
<p>In this chapter, we’ll instead begin with a conceptual overview of the properties and features of neural networks and build the simplest example possible of one (a network that consists of a singular neuron).  Afterwards, we’ll examine strategies for building a “Brain” object that can be inserted into our Vehicle class and used to determine steering.   Finally, we’ll also look at techniques for visualizing and animating a network of neurons.</p>
<p><script type="application/processing">

Network network;

void setup() {
  size(590, 360); 
  smooth();
  
  // Create the Network object
  network = new Network(width/2, height/2);

  // Create a bunch of Neurons
  Neuron a = new Neuron(-300, 0);
  Neuron b = new Neuron(-200, 0);
  Neuron c = new Neuron(0, 100);
  Neuron d = new Neuron(0, -100);
  Neuron e = new Neuron(200, 0);
  Neuron f = new Neuron(300, 0);

  // Connect them
  network.connect(a, b,1);
  network.connect(b, c,random(1));
  network.connect(b, d,random(1));
  network.connect(c, e,random(1));
  network.connect(d, e,random(1));
  network.connect(e, f,1);

  // Add them to the Network
  network.addNeuron(a);
  network.addNeuron(b);
  network.addNeuron(c);
  network.addNeuron(d);
  network.addNeuron(e);
  network.addNeuron(f);
}

void draw() {
  background(255);
  // Update and display the Network
  network.update();
  network.display();
  
  // Every 30 frames feed in an input
  if (frameCount % 30 == 0) {
    network.feedforward(random(1));
  }
}

class Connection {
  // Connection is from Neuron A to B
  Neuron a;
  Neuron b;
  
  // Connection has a weight
  float weight;

  // Variables to track the animation
  boolean sending = false;
  PVector sender;
  
  // Need to store the output for when its time to pass along
  float output = 0;

  Connection(Neuron from, Neuron to, float w) {
    weight = w;
    a = from;
    b = to;
  }
  
  
  // The Connection is active
  void feedforward(float val) {
    output = val*weight;        // Compute output
    sender = a.location.get();  // Start animation at Neuron A
    sending = true;             // Turn on sending
  }
  
  // Update traveling sender
  void update() {
    if (sending) {
      // Use a simple interpolation
      sender.x = lerp(sender.x, b.location.x, 0.1);
      sender.y = lerp(sender.y, b.location.y, 0.1);
      float d = PVector.dist(sender, b.location);
      // If we've reached the end
      if (d < 1) {
        // Pass along the output!
        b.feedforward(output);
        sending = false;
      }
    }
  }
  
  // Draw line and traveling circle
  void display() {
    stroke(0);
    strokeWeight(1+weight*4);
    line(a.location.x, a.location.y, b.location.x, b.location.y);

    if (sending) {
      fill(0);
      strokeWeight(1);
      ellipse(sender.x, sender.y, 16, 16);
    }
  }
}

class Network {

  // The Network has a list of neurons
  ArrayList neurons;

  // The Network now keeps a duplicate list of all Connection objects.
  // This makes it easier to draw everything in this class
  ArrayList connections;
  PVector location;

  Network(float x, float y) {
    location = new PVector(x, y);
    neurons = new ArrayList();
    connections = new ArrayList();
  }

  // We can add a Neuron
  void addNeuron(Neuron n) {
    neurons.add(n);
  }

  // We can connection two Neurons
  void connect(Neuron a, Neuron b, float weight) {
    Connection c = new Connection(a, b, weight);
    a.addConnection(c);
    // Also add the Connection here
    connections.add(c);
  } 

  // Sending an input to the first Neuron
  // We should do something better to track multiple inputs
  void feedforward(float input) {
    Neuron start = (Neuron) neurons.get(0);
    start.feedforward(input);
  }

  // Update the animation
  void update() {
    for (int i = 0; i < connections.size(); i++) {
      Connection c = (Connection) connections.get(i);
      c.update();
    }
  }

  // Draw everything
  void display() {
    pushMatrix();
    translate(location.x, location.y);
    for (int i = 0; i < neurons.size(); i++) {
      Neuron n = (Neuron) neurons.get(i);
      n.display();
    }

    for (int i = 0; i < connections.size(); i++) {
      Connection c = (Connection) connections.get(i);
      c.display();
    }
    popMatrix();
  }
}

// An animated drawing of a Neural Network
// Daniel Shiffman <http://www.shiffman.net>
// Nature of Code

class Neuron {
  // Neuron has a location
  PVector location;

  // Neuron has a list of connections
  ArrayList connections;

  // We now track the inputs and sum them
  float sum = 0;

  // The Neuron's size can be animated
  float r = 32;

  Neuron(float x, float y) {
    location = new PVector(x, y);
    connections = new ArrayList();
  }

  // Add a Connection
  void addConnection(Connection c) {
    connections.add(c);
  } 

  // Receive an input
  void feedforward(float input) {
    // Accumulate it
    sum += input;
    // Activate it?
    if (sum > 1) {
      fire();
      sum = 0;  // Reset the sum to 0 if it fires
    }
  }

  // The Neuron fires
  void fire() {
    r = 64;   // It suddenly is bigger

    // We send the output through all connections
    for (int i = 0; i < connections.size(); i++) {
      Connection c = (Connection) connections.get(i);

      c.feedforward(sum);
    }
  }

  // Draw it as a circle
  void display() {
    stroke(0);
    strokeWeight(1);
    // Brightness is mapped to sum
    float b = map(sum, 0, 1, 255, 0);
    fill(b);
    ellipse(location.x, location.y, r, r);

    // Size shrinks down back to original dimensions
    r = lerp(r, 32, 0.1);
  }
}

</script></p>
<p>Source: <a href='http://www.shiffman.net/wp/wp-content/uploads/2011/12/NetworkAnimation.zip'>NetworkAnimation.zip</a></script></pre>
]]></content:encoded>
			<wfw:commentRss>http://www.shiffman.net/2011/12/27/night-7-nature-of-code-excerpts/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Night #6: Image Sequence Object (with variable speed)</title>
		<link>http://www.shiffman.net/2011/12/26/night-6-image-sequence-object-with-variable-speed/</link>
		<comments>http://www.shiffman.net/2011/12/26/night-6-image-sequence-object-with-variable-speed/#comments</comments>
		<pubDate>Mon, 26 Dec 2011 16:00:19 +0000</pubDate>
		<dc:creator>Daniel</dc:creator>
				<category><![CDATA[processing.org]]></category>
		<category><![CDATA[animation]]></category>
		<category><![CDATA[image sequence]]></category>
		<category><![CDATA[PImage]]></category>

		<guid isPermaLink="false">http://www.shiffman.net/?p=1036</guid>
		<description><![CDATA[I have an example from Learning Processing which demonstrates how to package a &#8220;pre-made&#8221; animation (i.e. sequence of images) into an object in Processing so that it can be duplicated many times on screen. For tonight&#8217;s example, I&#8217;m going to &#8230; <a href="http://www.shiffman.net/2011/12/26/night-6-image-sequence-object-with-variable-speed/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>I have <a href="http://www.learningprocessing.com/exercises/chapter-15/exercise-15-5/">an example from Learning Processing</a> which demonstrates how to package a &#8220;pre-made&#8221; animation (i.e. sequence of images) into an object in Processing so that it can be duplicated many times on screen.   For tonight&#8217;s example, I&#8217;m going to make a new version that improves a few key points.</p>
<p>First, in the original example the the image files are loaded in the class itself.  This is problematic.  Sure, if you make one object then you are loading files from the hard drive once.  However, if you make many objects, then you are loading the same images over and over again which is totally unnecessary (and can cause problems like using too much memory, stuttering if objects are made during draw(), taking too long to start up, etc.).</p>
<p>We can fix this by loading an array of images in setup() and passing it to the object.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="java" style="font-family:monospace;">Animation a<span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000066; font-weight: bold;">void</span> setup<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #666666; font-style: italic;">// Load the image sequence first!</span>
  PImage<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> seq <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> PImage<span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">40</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
  <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> i <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> seq.<span style="color: #006633;">length</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    seq<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> loadImage<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;stick/stick&quot;</span><span style="color: #339933;">+</span>nf<span style="color: #009900;">&#40;</span>i<span style="color: #339933;">+</span><span style="color: #cc66cc;">1</span>,<span style="color: #cc66cc;">2</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">+</span><span style="color: #0000ff;">&quot;.png&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> 
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #666666; font-style: italic;">// Now when you make the animation object, you pass it the image array!</span>
  a <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Animation<span style="color: #009900;">&#40;</span>seq<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>  
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>The class then receives the array in the constructor and passes it to its own array.</p>
</pre>

<div class="wp_syntax"><table><tr><td class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> Animation <span style="color: #009900;">&#123;</span>
  <span style="color: #666666; font-style: italic;">// The array of images</span>
  PImage<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> images<span style="color: #339933;">;</span>
&nbsp;
  Animation<span style="color: #009900;">&#40;</span>PImage<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> images_<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    images <span style="color: #339933;">=</span> images_<span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>This way (as you'll see in the example) if we make an array of objects, each one uses the same array of images (which we loaded only once). Another feature of this improvement is that the Animation object is more generic, and can be created with any arbitrary array of images.</p>
<p>The original example demonstrated how to have the sequences start at different images so that they didn't all appear to be perfectly in sync.  However, the question I usually get is instead: "How can the sequences play back at variable speeds?"   </p>
<p>The original example used an integer to keep track of the current "frame" of the animation.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">int</span> index <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000066; font-weight: bold;">void</span> next<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  index <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>index <span style="color: #339933;">+</span> <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">%</span> images.<span style="color: #006633;">length</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Here, you see that we move one spot in the array each frame, and the animation is then shown at the frame rate of our sketch.  So in theory, you could change the above to "index = index + 2" to, say, double the speed.   A more flexible way to vary the rate of the animation, however, is to use a float for the index in the array, i.e.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">float</span> index <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span>
<span style="color: #000066; font-weight: bold;">float</span> speed <span style="color: #339933;">=</span> random<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">1</span>,<span style="color: #cc66cc;">5</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000066; font-weight: bold;">void</span> next<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #666666; font-style: italic;">// Move the index forward in the animation sequence</span>
  index <span style="color: #339933;">+=</span> speed<span style="color: #339933;">;</span>
  <span style="color: #666666; font-style: italic;">// If we are at the end, go back to the beginning</span>
  <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>index <span style="color: #339933;">&gt;=</span> images.<span style="color: #006633;">length</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">// We could just say index = 0</span>
    <span style="color: #666666; font-style: italic;">// but this is slightly more accurate</span>
    index <span style="color: #339933;">-=</span> images.<span style="color: #006633;">length</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span> 
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Of course, you can't actually use this float when you go to look up an image in the array -- indices must be integers!  So we simply convert it to an int when the time comes to draw the image.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">void</span> display<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #000066; font-weight: bold;">int</span> imageIndex <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">int</span><span style="color: #009900;">&#40;</span>index<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  image<span style="color: #009900;">&#40;</span>images<span style="color: #009900;">&#91;</span>imageIndex<span style="color: #009900;">&#93;</span>, x, y<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Here is the example.</p>
<p><script type="application/processing">
// An array of "Animation" objects
Animation[] animations = new Animation[6];

// The image sequence will be loaded outside of the object
// We don't want multiple instances of an object
// to load images again and again, just to point to an array
// of pre-loaded images

void setup() {
  size(640,360);
  
  // Load the image sequence
  PImage[] seq = new PImage[40];
  for (int i = 0; i < seq.length; i++) {
    seq[i] = loadImage("http://www.shiffman.net/p5/stick/stick"+nf(i+1,2)+".png"); 
  }
  
  // Make all the objects
  float y = 0;
  for (int i = 0; i < animations.length; i ++ ) {
    // Each object gets an image array and an x,y location
    animations[i] = new Animation(seq,0,y);
    y += 58;
  }
}

void draw() {

  background(255);
  
  // Display, cycle, and move all the animation objects
  for (int i = 0; i < animations.length; i ++ ) {
    animations[i].display();
    animations[i].next();
    animations[i].move();
  }
}


// Daniel Shiffman
// Hanukkah 2011
// 8 nights of Processing examples
// http://www.shiffman.net

// The animation object

class Animation {
  float x;  // location for Animation
  float y;  // location for Animation

  // The index into the array is a float!
  // This allows us to vary the speed of the animation
  // It will have to be converted to an int before the actual image is displayed
  float index = 0; 
  
  // Speed, this will control both the animations movement
  // as well as how fast it cycles through the images
  float speed;

  // The array of images
  PImage[] images;
  
  Animation(PImage[] images_, float x_, float y_) {
    images = images_;
    x = x_;
    y = y_;
    
    // A random speed
    speed = random(1,5);
    // Starting at the beginning
    index = 0;

  }

  void display() {
    // We must convert the float index to an int first!
    int imageIndex = int(index);
    image(images[imageIndex], x, y);
  }

  void move() {
    // Object only moves horizontally
    x += speed;
    if (x > width) {
      x = -images[0].width;
    }
  }

  void next() {
    // Move the index forward in the animation sequence
    index += speed;
    // If we are at the end, go back to the beginning
    if (index >= images.length) {
      // We could just say index = 0
      // but this is slightly more accurate
      index -= images.length;
    } 
  }
}
</script></p>
<p>Download source: <a href='http://www.shiffman.net/wp/wp-content/uploads/2011/12/AnimationExample.zip'>AnimationExample.zip</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.shiffman.net/2011/12/26/night-6-image-sequence-object-with-variable-speed/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Night #5: thread() in Processing</title>
		<link>http://www.shiffman.net/2011/12/25/night-5-thread-in-processing/</link>
		<comments>http://www.shiffman.net/2011/12/25/night-5-thread-in-processing/#comments</comments>
		<pubDate>Sun, 25 Dec 2011 14:52:54 +0000</pubDate>
		<dc:creator>Daniel</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[processing.org]]></category>
		<category><![CDATA[threads]]></category>

		<guid isPermaLink="false">http://www.shiffman.net/?p=1028</guid>
		<description><![CDATA[I just updated the Thread tutorial on the Processing wiki to include a little known function in Processing called thread(). It&#8217;s undocumented as of now, but will be a part of the 2.0 documentation. Here&#8217;s how it works. (This following &#8230; <a href="http://www.shiffman.net/2011/12/25/night-5-thread-in-processing/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>I just updated the <a href="http://wiki.processing.org/w/Threading">Thread tutorial</a> on the Processing wiki to include a little known function in Processing called thread().  It&#8217;s undocumented as of now, but will be a part of the 2.0 documentation.  Here&#8217;s how it works.</p>
<p>(This following is excerpted from the tutorial).</p>
<p>You are likely familiar with the idea of writing a program that follows a specific sequence of steps &#8212; setup() first then draw() over and over and over again! A Thread is also a series of steps with a beginning, a middle, and an end. A Processing sketch is a single thread, often referred to as the &#8220;Animation&#8221; thread. Other threads sequences, however, can run independently of the main &#8220;Processing&#8221; sketch. In fact, you can launch any number of threads at one time and they will all run concurrently.</p>
<p>Processing does this all the time, whenever you write an event callback, such as serialEvent(), or captureEvent(), etc. these functions are triggered by a different thread running behind the scenes, and they alert Processing whenever they have something to report. This is useful whenever you need to perform a task that takes too long and would slow down the main animation&#8217;s frame rate, such as grabbing data from the network (XML, database, etc.) If a separate thread gets stuck or has an error, the entire program won&#8217;t grind to a halt, since the error only stops that individual thread. To create independent, asynchronous threads, you can use the thread() function built into Processing.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">void</span> setup<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  size<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">200</span>,<span style="color: #cc66cc;">200</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #666666; font-style: italic;">// This will tell someFunction() to execute now as a separate thread</span>
  thread<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;someFunction&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000066; font-weight: bold;">void</span> draw<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000066; font-weight: bold;">void</span> someFunction<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #666666; font-style: italic;">// This function will run as a thread when called via</span>
  <span style="color: #666666; font-style: italic;">// thread(&quot;someFunction&quot;) as it was in setup!</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>The thread() function receives a String as an argument. The String should match the name of the function you want to run as a thread.   While using the thread() function is a very simple way of getting an independent thread, it is somewhat limited. Being able to make a thread object is a great deal more powerful, and this can be done by extending java&#8217;s <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Thread.html">Thread</a> class.</p>
<p>For more about how to do that, take a look at <a href="http://wiki.processing.org/w/Threading">the full tutorial</a>.</p>
<p>Following is an example draws a loading bar in the &#8220;animation&#8221; thread that reports progress on another thread().  This is a nice demonstration, however, it would not be necessary in a sketch where you wanted to load data in the background and hide this from the user, allowing the draw() loop to simply continue.</p>
<p><a href='http://www.shiffman.net/wp/wp-content/uploads/2011/12/Threads.zip'><img src="http://www.shiffman.net/wp/wp-content/uploads/2011/12/threads.png" alt="" title="threads" width="500" height="298" class="alignnone size-full wp-image-1029" /></a></p>
<p><a href='http://www.shiffman.net/wp/wp-content/uploads/2011/12/Threads.zip'>Threads.zip</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.shiffman.net/2011/12/25/night-5-thread-in-processing/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Night #4: Sorting the Vertices of a Polygon</title>
		<link>http://www.shiffman.net/2011/12/23/night-4-sorting-the-vertices-of-a-polygon/</link>
		<comments>http://www.shiffman.net/2011/12/23/night-4-sorting-the-vertices-of-a-polygon/#comments</comments>
		<pubDate>Sat, 24 Dec 2011 00:27:13 +0000</pubDate>
		<dc:creator>Daniel</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[arraylist]]></category>
		<category><![CDATA[polygon]]></category>
		<category><![CDATA[processing.org]]></category>
		<category><![CDATA[selection sort]]></category>

		<guid isPermaLink="false">http://www.shiffman.net/?p=1005</guid>
		<description><![CDATA[The following problem came up in my ICM course this year. A student was working on a sketch that involved tiling polygons arbitrarily drawn by a user. Allowing a user to set the vertices of a polygon should be easy &#8230; <a href="http://www.shiffman.net/2011/12/23/night-4-sorting-the-vertices-of-a-polygon/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>The following problem came up in my ICM course this year.  A student was working on a sketch that involved tiling polygons arbitrarily drawn by a user.  Allowing a user to set the vertices of a polygon should be easy enough, right?  But what if the user does not happen to draw them in a nice clock-wise (or counter clock-wise) order?</p>
<p>Imagine for a moment, you have an ArrayList of PVectors called &#8220;vertices.&#8221;  When the user clicks, the mouse you could add that mouse location to that ArrayList.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">void</span> mousePressed<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  vertices.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> PVector<span style="color: #009900;">&#40;</span>mouseX,mouseY<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>You could then draw that list as a polygon using beginShape() and endShape().</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">void</span> draw<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  beginShape<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span>PVector v <span style="color: #339933;">:</span> vertices<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    vertex<span style="color: #009900;">&#40;</span>v.<span style="color: #006633;">x</span>, v.<span style="color: #006633;">y</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span> 
  endShape<span style="color: #009900;">&#40;</span>CLOSE<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>But depending on how the user set the vertices, you might end up with:</p>
<p><img src="http://www.shiffman.net/wp/wp-content/uploads/2011/12/unsorted.png" alt="" title="unsorted" width="500" height="298" class="alignnone size-full wp-image-1006" /></p>
<p>when what you really want is the following:</p>
<p><img src="http://www.shiffman.net/wp/wp-content/uploads/2011/12/sorted.png" alt="" title="sorted" width="500" height="298" class="alignnone size-full wp-image-1007" /></p>
<p>One solution for solving this problem is to always sort all of the vertices according to their relative angle from the center.  Let&#8217;s say you calculate the center of the polygon as the average location of all vertices.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="java" style="font-family:monospace;">  PVector centroid <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> PVector<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span>PVector v <span style="color: #339933;">:</span> vertices<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    centroid.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span>v<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span> 
  centroid.<span style="color: #006633;">div</span><span style="color: #009900;">&#40;</span>vertices.<span style="color: #006633;">size</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>You can then make a vector that points from the center to each vertex and get its direction (using PVector&#8217;s heading2D() method).</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="java" style="font-family:monospace;">  <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span>PVector v <span style="color: #339933;">:</span> vertices<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    PVector dir <span style="color: #339933;">=</span> PVector.<span style="color: #006633;">sub</span><span style="color: #009900;">&#40;</span>v, centroid<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">float</span> a <span style="color: #339933;">=</span> dir.<span style="color: #006633;">heading2D</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> PI<span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Note how we add PI to the angle.  The heading2D() function will return an angle between -PI and PI and it&#8217;ll be easier to sort if we just have an angle between 0 and TWO_PI.  One way to sort an ArrayList is called a <a href="http://en.wikipedia.org/wiki/Selection_sort">Selection Sort</a>.  In the example below, you&#8217;ll find a variation of the selection sort.   The code iterates through the ArrayList, finds the element with the highest angle, removes that element and sticks it at the end of a new ArrayList.  It does this again and again until the original ArrayList is empty.  The result is a new ArrayList in sorted order.</p>
<p>Following is that example which implements all of the above into a class. If you are looking for an exercise, try allowing the user to move or delete existing vertices.   Also, how you would make a system of these polygons so that the user can draw more than one?</p>
<p><script type="application/processing">
// Daniel Shiffman
// Hanukkah 2011
// 8 nights of Processing examples
// http://www.shiffman.net


// A Polygon object
Poly p;

void setup() {
  size(586, 293);
  smooth();
  // An empty one
  p = new Poly();
}

void draw() {
  background(50);
  // Draw the polygon
  p.display();

  textAlign(CENTER);
  fill(255);
  text("click mouse to add vertices", width/2, height-16);
}

void keyPressed() {
  // Clear it when you press the mouse
  if (key == ' ') {
    p.clear();
  } 
  // If you want to see the polygon unsorted, comment
  // out the automatic sortVertices() in the class
  /*else if (key == 's') {
    p.sortVertices();
  }*/
}

// Add a vertex!
void mousePressed() {
  PVector mouse = new PVector(mouseX, mouseY);
  p.addVertex(mouse);
}

// Daniel Shiffman
// Hanukkah 2011
// 8 nights of Processing examples
// http://www.shiffman.net

// A class that generates a polygon sorted
// according to relative angle from center

class Poly {
  // A list of vertices
  ArrayList vertices;
  // The center
  PVector centroid;

  Poly() {
    // Empty at first
    vertices = new ArrayList();
    centroid = new PVector();
  }

  // We can clear the whole thing if necessary
  void clear() {
    vertices.clear();
  }


  // Add a new vertex
  void addVertex(PVector newVertex) {
    vertices.add(newVertex);
    // Whenever we have a new vertex
    // We have to recalculate the center
    // and re-sort the vertices
    updateCentroid();
    // Come out the sorting if you want to see it drawn incorrectly
    sortVertices();
  }

  // The center is the average location of all vertices
  void updateCentroid() {
    centroid = new PVector();
    for (int i = 0; i < vertices.size(); i++) {
      PVector v = (PVector) vertices.get(i);
      centroid.add(v);
    } 
    centroid.div(vertices.size());
  }


  // Sorting the ArrayList
  void sortVertices() {

    // This is something like a selection sort
    // Here, instead of sorting within the ArrayList
    // We'll just build a new one sorted
    ArrayList newVertices = new ArrayList();

    // As long as it's not empty
    while (!vertices.isEmpty ()) {
      // Let's find the one with the highest angle
      float biggestAngle = 0;
      PVector biggestVertex = null;
      // Look through all of them
    for (int i = 0; i < vertices.size(); i++) {
      PVector v = (PVector) vertices.get(i);
        // Make a vector that points from center
        PVector dir = PVector.sub(v, centroid);
        // What is it's heading
        // The heading function will give us values between -PI and PI
        // easier to sort if we have from 0 to TWO_PI
        float a = dir.heading2D() + PI;
        // Did we find it
        if (a > biggestAngle) {
          biggestAngle = a;
          biggestVertex = v;
        }
      }

      // Put the one we found in the new arraylist
      newVertices.add(biggestVertex);
      // Delete it so that the next biggest one 
      // will be found the next time
      vertices.remove(biggestVertex);
    }
    // We've got a new ArrayList
    vertices = newVertices;
  }

  // Draw everything!
  void display() {
    
    // First draw the polygon
    stroke(255);
    fill(255, 127);
    beginShape();
    for (int i = 0; i < vertices.size(); i++) {
      PVector v = (PVector) vertices.get(i);

      vertex(v.x, v.y);
    } 
    endShape(CLOSE);
    
    
    // Then we'll draw some addition information
    // at each vertex to show the sorting
    for (int i = 0; i < vertices.size(); i++) {
      
      // This is overkill, but we want the numbers to
      // appear outside the polygon so we extend a vector
      // from the center
      PVector v = (PVector) vertices.get(i);      
      PVector dir = PVector.sub(v, centroid);
      dir.normalize();
      dir.mult(12);
      
      // Number the vertices
      fill(255);
      stroke(255);
      ellipse(v.x, v.y, 4, 4);
      textAlign(CENTER);
      text(i, v.x+dir.x, v.y+dir.y+6);
    } 

   
    // Once we have two vertices draw the center
    if (vertices.size() > 1  ) {
      fill(255);
      ellipse(centroid.x, centroid.y, 8, 8);
      text("centroid", centroid.x, centroid.y+16);
    }
  }
}
</script></p>
<p>Source: <a href='http://www.shiffman.net/wp/wp-content/uploads/2011/12/PolygonVertexSorting.zip'>PolygonVertexSorting.zip</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.shiffman.net/2011/12/23/night-4-sorting-the-vertices-of-a-polygon/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Night #3: Regular Expressions in Processing</title>
		<link>http://www.shiffman.net/2011/12/22/night-3-regular-expressions-in-processing/</link>
		<comments>http://www.shiffman.net/2011/12/22/night-3-regular-expressions-in-processing/#comments</comments>
		<pubDate>Fri, 23 Dec 2011 02:25:34 +0000</pubDate>
		<dc:creator>Daniel</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[processing.org]]></category>
		<category><![CDATA[regex]]></category>

		<guid isPermaLink="false">http://www.shiffman.net/?p=989</guid>
		<description><![CDATA[Several years ago I became somewhat obsessed with regular expressions while reading Jeffrey Friedl&#8217;s Mastering Regular Expressions. At the time, I wrote a short tutorial about regular expressions for my course Programming from A to Z. The sad truth is &#8230; <a href="http://www.shiffman.net/2011/12/22/night-3-regular-expressions-in-processing/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Several years ago I became somewhat obsessed with regular expressions while reading Jeffrey Friedl&#8217;s <a href="http://regex.info">Mastering Regular Expressions</a>.  At the time, I wrote <a href="http://www.shiffman.net/teaching/a2z/regex/">a short tutorial about regular expressions</a> for my course Programming from A to Z.  The sad truth is that if you&#8217;ve ever done regular expressions in Java, it&#8217;s pretty darn awkward compared to, say, python or perl.  The good news is there are some nice regex helper functions in Processing that can make it a bit easier.  Before we get to that let&#8217;s start with the Java API: </p>
<ul>
<li><a href="http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html">Pattern</a> &#8212; a compiled representation of a regular expression.</li>
<li><a href="http://docs.oracle.com/javase/6/docs/api/java/util/regex/Matcher.html">Matcher</a> &#8212; an engine that performs match operations on a character sequence (or String) by interpreting a Pattern.</li>
</ul>
<p>An example of Pattern and Matcher in Java (which you can write directly into Processing) looks like the following:</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="java" style="font-family:monospace;"><span style="color: #003399;">String</span> inputtext <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;This is a test of regular expressions.&quot;</span><span style="color: #339933;">;</span>  <span style="color: #666666; font-style: italic;">// Input text</span>
<span style="color: #003399;">String</span> regex <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;test&quot;</span><span style="color: #339933;">;</span>              <span style="color: #666666; font-style: italic;">// The regular expression to match</span>
Pattern p <span style="color: #339933;">=</span> Pattern.<span style="color: #006633;">compile</span><span style="color: #009900;">&#40;</span>regex<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// Making a Pattern object with the regex </span>
Matcher m <span style="color: #339933;">=</span> p.<span style="color: #006633;">matcher</span><span style="color: #009900;">&#40;</span>inputtext<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>   <span style="color: #666666; font-style: italic;">// Matching that regex in the input string</span>
<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>m.<span style="color: #006633;">find</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>m.<span style="color: #006633;">group</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>     <span style="color: #666666; font-style: italic;">// Here's the match!</span>
<span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;No match!&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>   <span style="color: #666666; font-style: italic;">// No match!</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Of course, in most cases, you want to do something more sophisticated where you iterate over many matches.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="java" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// Regex that matches double words</span>
<span style="color: #666666; font-style: italic;">// Ugh, look at all these double back slashes!!</span>
<span style="color: #003399;">String</span> regex <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;<span style="color: #000099; font-weight: bold;">\\</span><span style="color: #000099; font-weight: bold;">\\</span>b(<span style="color: #000099; font-weight: bold;">\\</span><span style="color: #000099; font-weight: bold;">\\</span>w+)<span style="color: #000099; font-weight: bold;">\\</span><span style="color: #000099; font-weight: bold;">\\</span>b<span style="color: #000099; font-weight: bold;">\\</span><span style="color: #000099; font-weight: bold;">\\</span>W+<span style="color: #000099; font-weight: bold;">\\</span><span style="color: #000099; font-weight: bold;">\\</span>1&quot;</span><span style="color: #339933;">;</span>   
&nbsp;
Pattern p <span style="color: #339933;">=</span> Pattern.<span style="color: #006633;">compile</span><span style="color: #009900;">&#40;</span>regex<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>     <span style="color: #666666; font-style: italic;">// Compile Regex</span>
Matcher m <span style="color: #339933;">=</span> p.<span style="color: #006633;">matcher</span><span style="color: #009900;">&#40;</span>content<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>         <span style="color: #666666; font-style: italic;">// Create Matcher</span>
<span style="color: #000000; font-weight: bold;">while</span> <span style="color: #009900;">&#40;</span>m.<span style="color: #006633;">find</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>m.<span style="color: #006633;">group</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Processing provides some regex helper functions that wrap all of this Java Pattern/Matcher stuff.  They are <a href="http://processing.org/reference/match_.html">match()</a> and <a href="http://processing.org/reference/matchAll_.html">matchAll()</a>.  </p>
<p>The match() function is used to apply a regular expression to a piece of text, and return matching groups (elements found inside parentheses) as a String array. If there is no match, the function will return null. If no groups are specified in the regular expression, but the sequence matches, an array of length one (with the matched text as the first element of the array) will be returned. </p>
<p>Here&#8217;s an example (this is straight from the reference page).</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="java" style="font-family:monospace;"><span style="color: #003399;">String</span> s <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;Inside a tag, you will find &lt;tag&gt;content&lt;/tag&gt;.&quot;</span><span style="color: #339933;">;</span>
<span style="color: #003399;">String</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> m <span style="color: #339933;">=</span> match<span style="color: #009900;">&#40;</span>s, <span style="color: #0000ff;">&quot;&lt;tag&gt;(.*?)&lt;/tag&gt;&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
println<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Found '&quot;</span> <span style="color: #339933;">+</span> m<span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;' inside the tag.&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #666666; font-style: italic;">// Prints to the console:</span>
<span style="color: #666666; font-style: italic;">// &quot;Found 'content' inside the tag.&quot;</span></pre></td></tr></table></div>

<p>The matchAll() function is at first a bit confusing because it returns a two dimensional array.  But if you look right back to how match() works, it&#8217;s pretty simple.  match() assumes you want just one match, and gives you an array, a list of all the groups for that single match.  matchAll() assumes you want all the matches, so it gives you a bunch of those arrays, one for every match.   What&#8217;s an array of an array?  A two dimensional array!  The first dimension is the match itself, and the second dimension is the group for that match, i.e.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="java" style="font-family:monospace;"><span style="color: #003399;">String</span> s <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;Some tags! &lt;tag&gt;one&lt;/tag&gt; &lt;tag&gt;two&lt;/tag&gt; &lt;tag&gt;three&lt;/tag&gt;.&quot;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// Match this regular expression</span>
<span style="color: #003399;">String</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> m <span style="color: #339933;">=</span> matchAll<span style="color: #009900;">&#40;</span>s, <span style="color: #0000ff;">&quot;&lt;tag&gt;(.*?)&lt;/tag&gt;&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #666666; font-style: italic;">// Loop through all the matches     </span>
<span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> i <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> m.<span style="color: #006633;">length</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #666666; font-style: italic;">// Print out group 1 for each match                </span>
  println<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Found '&quot;</span> <span style="color: #339933;">+</span> m<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;' inside a tag.&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> 
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>This new example uses a regex that matches anything inside an HTML href tag and draws it the screen.</p>
<p><a href='http://www.shiffman.net/wp/wp-content/uploads/2011/12/Regex.zip'><img src="http://www.shiffman.net/wp/wp-content/uploads/2011/12/regex.png" alt="" title="regex" width="500" height="298" class="alignnone size-full wp-image-994" /></a></p>
<p><a href='http://www.shiffman.net/wp/wp-content/uploads/2011/12/Regex.zip'>Regex.zip</a></pre>
]]></content:encoded>
			<wfw:commentRss>http://www.shiffman.net/2011/12/22/night-3-regular-expressions-in-processing/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Night #2: Fade Sound In and Out Using Minim</title>
		<link>http://www.shiffman.net/2011/12/21/night-2-fade-sound-in-and-out-using-minim/</link>
		<comments>http://www.shiffman.net/2011/12/21/night-2-fade-sound-in-and-out-using-minim/#comments</comments>
		<pubDate>Thu, 22 Dec 2011 03:37:36 +0000</pubDate>
		<dc:creator>Daniel</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[minim]]></category>
		<category><![CDATA[pcomp]]></category>
		<category><![CDATA[processing.org]]></category>
		<category><![CDATA[sound]]></category>

		<guid isPermaLink="false">http://www.shiffman.net/?p=978</guid>
		<description><![CDATA[I made this example earlier in the semester after seeing countless projects with the following functionality: turning a sound on when a sensor reading reaches a given level, turning the sound off when a sensor reading falls below a certain &#8230; <a href="http://www.shiffman.net/2011/12/21/night-2-fade-sound-in-and-out-using-minim/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>I made this example earlier in the semester after seeing countless projects with the following functionality: turning a sound on when a sensor reading reaches a given level, turning the sound off when a sensor reading falls below a certain level.  Most the projects used Minim for sound playback and pause() and play() to start and stop a sound, along with rewind() to send the sound back to the beginning.  While this does work, I find a more effective strategy is to fade a sound in and out using shiftGain().</p>
<p>Now this is a fairly simple problem if you can pinpoint the moment a sound should fade in.  For example, let&#8217;s say you want it to happen when the mouse is clicked.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">void</span> mousePressed<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  player.<span style="color: #006633;">shiftGain</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">-</span><span style="color: #cc66cc;">80</span>, <span style="color: #cc66cc;">13</span>, <span style="color: #cc66cc;">1000</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> 
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>The above line of code will fade the sound over 1,000 milliseconds (i.e. 1 second) from a decibel level of -80 (inaudible) to 13 (some vaguely loud level.)</p>
<p>If you put this code in draw(), however, you&#8217;ve got a problem.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">void</span> draw<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>sensorVal <span style="color: #339933;">&gt;</span> threshold<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    player.<span style="color: #006633;">shiftGain</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">-</span><span style="color: #cc66cc;">80</span>, <span style="color: #cc66cc;">13</span>, <span style="color: #cc66cc;">1000</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> 
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>You can&#8217;t call shiftGain() over and over again!  You want this to happen just once, the moment the sensor value reaches that threshold.  Introducing a boolean is a quick way to solve this problem.  If you set the boolean to true when the sound is fading and only call shiftGain() when the boolean is set to false, you&#8217;ve now got only one call to the function.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">boolean</span> fade <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">false</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000066; font-weight: bold;">void</span> draw<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>sensorVal <span style="color: #339933;">&gt;</span> threshold <span style="color: #339933;">&amp;&amp;</span> <span style="color: #339933;">!</span>fade<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    player.<span style="color: #006633;">shiftGain</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">-</span><span style="color: #cc66cc;">80</span>, <span style="color: #cc66cc;">13</span>, <span style="color: #cc66cc;">1000</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> 
    fade <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">true</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>The question remains: when does fade get set back to false?  One likely solution is to reset the boolean when the sensor value falls below the threshold, i.e.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="java" style="font-family:monospace;">  <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>sensorVal <span style="color: #339933;">&gt;</span> threshold <span style="color: #339933;">&amp;&amp;</span> <span style="color: #339933;">!</span>fade<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    player.<span style="color: #006633;">shiftGain</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">-</span><span style="color: #cc66cc;">80</span>, <span style="color: #cc66cc;">13</span>, <span style="color: #cc66cc;">1000</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> 
    fade <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">true</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">else</span> <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>sensorVal <span style="color: #339933;">&lt;</span> threshold<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    fade <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">false</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Following is an example that does this with a double threshold (fading up above a value and fading down below a value).  In addition, it offers some other improvements (such as having the sound fade from its current gain level). The mouseX location is the stand-in for a sensor value.</p>
<p><a href="http://www.shiffman.net/wp/wp-content/uploads/2011/12/SoundFade.zip"><img src="http://www.shiffman.net/wp/wp-content/uploads/2011/12/soundfade.png" alt="" title="soundfade" width="400" height="239" class="alignnone size-full wp-image-979" /></a></p>
<p>Source: <a href="http://www.shiffman.net/wp/wp-content/uploads/2011/12/SoundFade.zip">SoundFade.zip</a></p>
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.shiffman.net/2011/12/21/night-2-fade-sound-in-and-out-using-minim/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Night #1: Zoom and Pan in 2D</title>
		<link>http://www.shiffman.net/2011/12/20/night-1-zoom-and-pan-in-2d/</link>
		<comments>http://www.shiffman.net/2011/12/20/night-1-zoom-and-pan-in-2d/#comments</comments>
		<pubDate>Wed, 21 Dec 2011 03:19:31 +0000</pubDate>
		<dc:creator>Daniel</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[2D]]></category>
		<category><![CDATA[pan]]></category>
		<category><![CDATA[processing.org]]></category>
		<category><![CDATA[zoom]]></category>

		<guid isPermaLink="false">http://www.shiffman.net/?p=970</guid>
		<description><![CDATA[This came up in my course &#8220;Introduction to Computational Media&#8221; this year. How does one pan and/or zoom in a 2D Processing world? We could certainly introduce P3D into the mix, but there is a nice, elegant way we can &#8230; <a href="http://www.shiffman.net/2011/12/20/night-1-zoom-and-pan-in-2d/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>This came up in my course &#8220;Introduction to Computational Media&#8221; this year.  How does one pan and/or zoom in a 2D Processing world?  We could certainly introduce P3D into the mix, but there is a nice, elegant way we can create the effect of panning and zooming and still live in 2D.  Here&#8217;s how it works.</p>
<p>First, you need to make sure you translate to the center of your window.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="java" style="font-family:monospace;">  translate<span style="color: #009900;">&#40;</span>width<span style="color: #339933;">/</span><span style="color: #cc66cc;">2</span>, height<span style="color: #339933;">/</span><span style="color: #cc66cc;">2</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Then you can use the <a href="http://processing.org/learning/basics/scale.html">scale()</a> function to scale the world according to a percentage (i.e. 2.0 is 200%, 0.5 is 50%).  We&#8217;ll use a variable called zoom.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="java" style="font-family:monospace;">  <span style="color: #000066; font-weight: bold;">float</span> zoom <span style="color: #339933;">=</span> <span style="color: #cc66cc;">1.5</span><span style="color: #339933;">;</span>  <span style="color: #666666; font-style: italic;">// 150%</span>
  scale<span style="color: #009900;">&#40;</span>zoom<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Then we can translate additionally to pan according to some offset.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="java" style="font-family:monospace;">  <span style="color: #000066; font-weight: bold;">float</span> offsetX <span style="color: #339933;">=</span> <span style="color: #cc66cc;">100</span><span style="color: #339933;">;</span>  <span style="color: #666666; font-style: italic;">// Some arbitrary offset</span>
  <span style="color: #000066; font-weight: bold;">float</span> offsetY <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span>
  translate<span style="color: #009900;">&#40;</span>offsetX,offsetY<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Here is an example (running in processing.js) that allows the user to pan around a design by dragging the mouse, and zoom in and out using key presses.</p>
<p><script type="application/processing">
// The scale of our world
float zoom;
// A vector to store the offset from the center
PVector offset;
// The previous offset
PVector poffset;
// A vector for the mouse position
PVector mouse;

void setup() {
  size(586, 293);
  zoom = 1.0;
  offset = new PVector(0, 0);
  poffset = new PVector(0, 0);

  smooth();
}

void draw() {
  background(50);
  pushMatrix();
  // Everything must be drawn relative to center
  translate(width/2, height/2);
  
  // Use scale for 2D "zoom"
  scale(zoom);
  // The offset (note how we scale according to the zoom)
  translate(offset.x, offset.y);
  
  // An arbitrary design so that we have something to see!
  randomSeed(1);
  for (int i = 0; i < 500; i++) {
    stroke(255);
    fill(255,50);
    rectMode(CENTER);
    float h = 100;
    if (random(1) < 0.5) {
      rect(random(-h,h),random(-h,h),12,12);
    } else {
      ellipse(random(-h,h),random(-h,h),12,12);
    } 
  }
  popMatrix();
  
  // Draw some text (not panned or zoomed!)
  fill(255);
  text("a: zoom in\nz: zoom out\ndrag mouse to pan",10,32);
  
  
}

// Zoom in and out when the key is pressed
void keyPressed() {
  if (key == 'a') {
    zoom += 0.1;
  } 
  else if (key == 'z') {
    zoom -= 0.1;
  }
  zoom = constrain(zoom,0,100);
}

// Store the mouse and the previous offset
void mousePressed() {
  mouse = new PVector(mouseX, mouseY);
  poffset.set(offset);
}

// Calculate the new offset based on change in mouse vs. previous offsey
void mouseDragged() {
  offset.x = (mouseX - mouse.x)/zoom + poffset.x;
  offset.y = (mouseY - mouse.y)/zoom + poffset.y;
}

</script></p>
<p>Source: <a href='http://www.shiffman.net/wp/wp-content/uploads/2011/02/PanZoom2D.zip'>PanZoom2D.zip</a></p>
<p></script></p>
]]></content:encoded>
			<wfw:commentRss>http://www.shiffman.net/2011/12/20/night-1-zoom-and-pan-in-2d/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Hanukkah: 8 Nights of Processing</title>
		<link>http://www.shiffman.net/2011/12/20/hanukkah-8-nights-of-processing/</link>
		<comments>http://www.shiffman.net/2011/12/20/hanukkah-8-nights-of-processing/#comments</comments>
		<pubDate>Tue, 20 Dec 2011 19:31:05 +0000</pubDate>
		<dc:creator>Daniel</dc:creator>
				<category><![CDATA[General]]></category>

		<guid isPermaLink="false">http://www.shiffman.net/?p=951</guid>
		<description><![CDATA[Hello world. I have completely failed to remember I have a blog. Well, I suppose it wasn&#8217;t a failure of memory, rather it just fell out of my routine to keep things up-to-date. When you have one of these jobs &#8230; <a href="http://www.shiffman.net/2011/12/20/hanukkah-8-nights-of-processing/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Hello world.</p>
<p>I have completely failed to remember I have a blog.  Well, I suppose it wasn&#8217;t a failure of memory, rather it just fell out of my routine to keep things up-to-date.  When you have one of these jobs at an academic institution, one thing they require you to do every so often is put together a big pile of paper that provides evidence you are contributing member of society.  The way I&#8217;ve always managed to do that in the past is by scanning through all my old posts to find out if I have in fact done anything.  According to this blog, I have not existed since April 2011.  I&#8217;m going to try to remedy that.  The first thing I&#8217;m going to do is post a list of things I&#8217;ve been up to in the last seven or eight months (this is for me and anyone reading should really just stop reading).  The second thing I&#8217;m going to do (starting tonight) is simultaneously attempt to revive this blog and celebrate the festival of lights by posting eight nights of Processing examples.  I&#8217;ve made a few new ones for the upcoming Processing 2.0 release as well as helped out students on a number of different problems over the course of the fall semester.  So hopefully this can be a place where I can document and share some of these examples in the hopes that they will help others.</p>
<p>So first, the part everyone should feel free to ignore. . .</p>
<ul>
<li>April 2011. I visited my good friend <a href="http://www.talespin.com/">Chris Ault</a> at The College of New Jersey and gave a presentation about the Nature of Code and Most Pixels Ever and saw several demos of student work.</li>
<li>June 2011. I attended Seb Lee-Delisle&#8217;s <a href="http://sebleedelisle.com/training/">Creative JS</a> course in NYC.  I made this: <a href="http://www.shiffman.net/creativejs/particles.html">fibonacci particles</a></li>
<li>June 17-20 2011. I participated in the Processing 2.0 summit. Ben Fry, Casey Reas, Andres Colubri, Jer Thorp, Patrick Hebron, and I worked together to define the 2.0 release.  (Thanks to Casey for the photos below.)</li>
<p><img src="http://reas.com/blog/wp-content/uploads/2011/07/itp2.jpg" alt="Processing 2.0" /><br />
<img alt="Processing 2.0" src="http://reas.com/blog/wp-content/uploads/2011/07/itp1.jpg" /></p>
<li>Summer 2011. I participated in Google Summer of Code as a mentor for Processing.</li>
<li>September 2011. Launched the &#8220;Magic Book&#8221; project with Rune Madsen and Miguel Bermudez at ITP (stay tuned for more about this).</li>
<li>October 2011. I attended IndieCade in Los Angeles and participated in a panel discussion with Zach Gage, Robert Hodgin, and Casey Reas, and Daniel Shiffman.  We discussed projects which use code as a generator of form, and explore the various ways in which procedurally generated elements can contribute to the mechanics, dynamics, and/or aesthetics of video games. (<a href="http://www.youtube.com/watch?v=edor4shC-pY">video of the panel</a>).</li>
<li>October 2011. Attended Art &#038;&#038; Code 3D and was proud to be Greg Borenstein&#8217;s helper for his workshop <a href="http://artandcode.com/3d/workshops/1a-using-the-kinect-with-processing">Using the Kinect with Processing</a>.  Also really enjoyed Stephen Howell&#8217;s Scratch + Kinect workshop.</li>
<li>November 2011. Began development on a <a href="http://www.itpcakemix.com/">CakeMix</a> Processing library. Source on <a href="https://github.com/shiffman/CakeMix-Processing">github</a>.
</li>
<li>Fall 2011. Technical edited Greg Borenstein&#8217;s upcoming book: <a href="http://shop.oreilly.com/product/0636920020684.do">Making Things See</a>.</li>
<li>December 2011. Gave a presentation at the Neuberger Museum of Art as part of the <a href="https://drupalsites.purchase.edu/newmedia/index.php?q=node/150">New Media Lecture Series</a></li>
<li>December 2011.  Completing work on Processing 2.0.  New examples, new tutorials. Stay tuned for further updates</li>
<p>.
</ul>
<p>Next up, 8 Processing examples!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.shiffman.net/2011/12/20/hanukkah-8-nights-of-processing/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
