<?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>toxiclibs &#187; simutils</title>
	<atom:link href="http://toxiclibs.org/category/simutils/feed/" rel="self" type="application/rss+xml" />
	<link>http://toxiclibs.org</link>
	<description>Building blocks for computational design</description>
	<lastBuildDate>Fri, 27 Aug 2010 10:01:54 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>simutils-0001: Gray-Scott reaction diffusion</title>
		<link>http://toxiclibs.org/2010/02/simutils-grayscott/</link>
		<comments>http://toxiclibs.org/2010/02/simutils-grayscott/#comments</comments>
		<pubDate>Wed, 24 Feb 2010 08:05:39 +0000</pubDate>
		<dc:creator>toxi</dc:creator>
				<category><![CDATA[Featured]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Usage]]></category>
		<category><![CDATA[colorutils]]></category>
		<category><![CDATA[simutils]]></category>
		<category><![CDATA[volumeutils]]></category>

		<guid isPermaLink="false">http://toxiclibs.org/?p=217</guid>
		<description><![CDATA[This is part 2 of the discussion of the classes &#38; processes provided by the recently released simutils package. The first part of this series dealt with Diffusion-limited Aggregation (DLA) and this next process too is related to the simulated diffusion of particles. However, whereas the DLA process dealt with individual particles, this next one [...]]]></description>
			<content:encoded><![CDATA[<p>This is part 2 of the discussion of the classes &amp; processes provided by the recently released <a href="http://toxiclibs.org/category/simutils/">simutils</a> package. <a href="http://toxiclibs.org/2010/02/new-package-simutils/">The first part of this series dealt with Diffusion-limited Aggregation</a> (DLA) and this next process too is related to the simulated diffusion of particles. However, whereas the DLA process dealt with individual particles, this next one is only looking at the concentrations of particles of different &#8220;substances&#8221; in a two-dimensional simulation space.</p>
<p>The Gray-Scott reaction diffusion model is a member of a whole variety of <a href="http://en.wikipedia.org/wiki/Reaction-diffusion_system" onclick="pageTracker._trackPageview('/outgoing/en.wikipedia.org/wiki/Reaction-diffusion_system?referer=');">RD systems</a>, popular largely due to its ability to produce a very varied number of biological looking (and behaving) patterns, both static and constantly changing. Some patterns are reminiscent of cell devision, gastrulation or the formation of spots &amp; stripes on furry animals. As with all RD models, these patterns are the result of an iterative process evaluating each cell of the simulation space based on the concentrations of the two main parameters (for Gray-Scott usually named <strong>f</strong> and <strong>K</strong>) of the reaction equation as well as taking into account the concentrations of these 2 substances in neighboring cells. So conceptually the reaction diffusion system lies somewhere between the isolated DLA process working with individual particles and the entirely rulebased evaluation of a cell&#8217;s neighborhood in traditional cellular automatas, which we will deal with in the next post.</p>
<p>The image below, by <a href="http://mrob.com/pub/comp/xmorphia/" onclick="pageTracker._trackPageview('/outgoing/mrob.com/pub/comp/xmorphia/?referer=');">Robert Munafo</a>, is a fantastically helpful map of possible patterns resulting from various combinations of the <strong>f</strong> and <strong>K</strong> coefficients. Click the image to go to his website and explore the parameters in more detail (there&#8217;re close-ups and videos of all interesting combinations).</p>
<p><a href="http://mrob.com/pub/comp/xmorphia/" onclick="pageTracker._trackPageview('/outgoing/mrob.com/pub/comp/xmorphia/?referer=');"><img class="alignnone size-large wp-image-245" title="gs-parameter-map" src="http://toxiclibs.org/wp-content/uploads/2010/02/gs-parameter-map-680x680.jpg" alt="GS parameter map" width="680" height="680" /></a></p>
<p>As with the other classes of the <a href="http://toxiclibs.org/category/simutils/">simutils</a> package, the GrayScott implementation comes with several small demos to help you get started. The most basic use case (<a href="http://code.google.com/p/toxiclibs/source/browse/trunk/toxiclibs/examples/sim/HelloGrayScott/HelloGrayScott.pde" onclick="pageTracker._trackPageview('/outgoing/code.google.com/p/toxiclibs/source/browse/trunk/toxiclibs/examples/sim/HelloGrayScott/HelloGrayScott.pde?referer=');">HelloGrayScott</a>) is just setting up a simulation with default parameters and then allows you to draw in the simulation space with the mouse. Each frame, the reaction is updated, its new state translated into grayscale pixels and then rendered to the screen. The important thing to know here is that there&#8217;re 2 separate results states available, normally called the <strong>u</strong> and <strong>v</strong> buffers.</p>
<pre class="brush:java">
GrayScott gs;

// create a new simulation instance
// the "false" refers to a non-tiled space with walls
// set to true to create tiling patterns
gs=new GrayScott(width,height,false);

// configure the simulation params to:
// f=0.023, K=0.074
// diffusion speed for u buffer = 0.095
// diffusion speed for u buffer = 0.03
gs.setCoefficients(0.023,0.074,0.095,0.03);
</pre>
<p>The main <code>draw()</code> loop then just does this:</p>
<pre class="brush:java">
void draw() {
  if (mousePressed) {
    // set cells around mouse pos to max saturation
    gs.setRect(mouseX, mouseY,20,20);
  }
  loadPixels();
  // update simulation by 10 time steps per frame
  for(int i=0; i&lt;10; i++) gs.update(1);
  // read out the v buffer and translate into grayscale colors
  for(int i=0; i&lt;gs.v.length; i++) {
    float cellValue=gs.v[i];
    // the cell values in v are usually in the range 0.0 .. 0.33
    int col=255-(int)(min(255,cellValue*768));
    // use the col value for red, green and blue and set alpha to full opacity
    pixels[i]=col&lt;&lt;16|col&lt;&lt;8|col|0xff000000;
  }
  updatePixels();
}
</pre>
<p>To avoid this manual pixel pushing and enable us to make some of the subtle changes of densities more obvious, we can also use the handy (and also new) <a href="http://code.google.com/p/toxiclibs/source/browse/trunk/toxiclibs/src.color/toxi/color/ToneMap.java" onclick="pageTracker._trackPageview('/outgoing/code.google.com/p/toxiclibs/source/browse/trunk/toxiclibs/src.color/toxi/color/ToneMap.java?referer=');"><code>ToneMap</code></a> class of the <a href="http://toxiclibs.org/category/colorutils/">colorutils</a> package. This allows us to map a number range to different positions (colors) on a multi-color gradient and so potentially better visualize the different densities. The basic usage of this class is shown below:</p>
<pre class="brush:java">
import toxi.color.*;

ToneMap toneMap;

// define a color gradient by adding colors at certain key points
// a gradient is like a 1D array with target colors at certain points
// all inbetween values are automatically interpolated (customizable too)
// this gradient here will contain 256 values
ColorGradient gradient=new ColorGradient();
gradient.addColorAt(0, NamedColor.BLACK);
gradient.addColorAt(128, NamedColor.RED);
gradient.addColorAt(192, NamedColor.YELLOW);
gradient.addColorAt(255, NamedColor.WHITE);

// now create a ToneMap instance using this gradient
// this maps the value range 0.0 .. 0.33 across the entire gradient width
// a 0.0 input value will be black, 0.33 white
toneMap=new ToneMap(0, 0.33, gradient);
</pre>
<p>Now we can refactor our Gray-Scott rendering code into something even simpler:</p>
<pre class="brush:java">
for(int i=0; i&lt;gs.v.length; i++) {
    // take a GS v value and turn it into a packed integer ARGB color value
    pixels[i]=toneMap.getARGBToneFor(gs.v[i]);
}
</pre>
<p>Btw. The <code>ToneMap</code> class is a nice example of the whole reusable &#8220;building block philosophy&#8221; of toxiclibs (and the object oriented approach in general). The class is simply a <a href="http://en.wikipedia.org/wiki/Object_composition" onclick="pageTracker._trackPageview('/outgoing/en.wikipedia.org/wiki/Object_composition?referer=');">composition</a> of other library classes and under the hood delegates everything to these elements:</p>
<p><img src="http://toxiclibs.org/wp-content/uploads/2010/02/tonemap.png" alt="ToneMap composition" title="ToneMap composition" width="379" height="266" class="aligncenter size-full wp-image-275" /></p>
<p>All other GrayScott demos, as well as all Cellular Automata examples, make use of this ToneMap class, so do have a look at those for more reference&#8230; </p>
<p>Since a homogeneous configuration of the entire sim grid will always just provide one particular character/patterning, the <code>GrayScott</code> class has been designed with extension in mind. The <a href="http://code.google.com/p/toxiclibs/source/browse/trunk/toxiclibs/examples/sim/CustomGrayScott/CustomGrayScott.pde" onclick="pageTracker._trackPageview('/outgoing/code.google.com/p/toxiclibs/source/browse/trunk/toxiclibs/examples/sim/CustomGrayScott/CustomGrayScott.pde?referer=');">CustomGrayScott</a> demo shows how to impose a pattern on the actual simulation parameters themselves, so that cells at different positions are evaluated using different parameters:</p>
<pre class="brush:java">
class PatternedGrayScott extends GrayScott {

  // our constructor just passes things on to the parent class
  PatternedGrayScott(int w, int h, boolean tiling) {
    super(w,h,tiling);
  }

  // this function is called for each cell
  // to retrieve its f coefficient
  public float getFCoeffAt(int x, int y) {
    // here we only take the x coordinate
    // and choose one of 2 options (even &#038; odd)
    x/=32;
    return 0==x%2 ? f : f-0.005;
  }

  // this function is called for each cell
  // to retrieve its K coefficient
  public float getKCoeffAt(int x, int y) {
    // here we only use the y coordinate
    // and create a gradient falloff for this param
    return k-y*0.00004;
  }
}
</pre>
<p>Instead of using the default GrayScott class, we only need to change one line in the setup() method to use our extended version instead:</p>
<pre class="brush:java">
GrayScott gs;

void setup() {
	size(200,200);
	gs=new PatternedGrayScott(width,height,false);
	...
}
</pre>
<p>The result of this is shown below&#8230; Easy, huh? :)</p>
<p><img class="alignnone size-full wp-image-193" title="CustomGrayScott001" src="http://toxiclibs.org/wp-content/uploads/2010/02/CustomGrayScott001.png" alt="" width="680" height="362" /></p>
<p>Having this mechanism in place, it can be also used to create more interesting types of masking. For a commission to produce a <a href="http://postspectacular.com/work/printmag/" onclick="pageTracker._trackPageview('/outgoing/postspectacular.com/work/printmag/?referer=');">cover design for Print Magazine</a> in 2008, I generated a type face from simple line &#038; arc segments and used it as mask to manipulate the concentrations of the f &#038; K parameters to achieve two different types of patterning: one for the inside of the letter shapes, the other for the outside&#8230;</p>
<p><object width="680" height="383"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id=1272071&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=00ADEF&amp;fullscreen=1" /><embed src="http://vimeo.com/moogaloop.swf?clip_id=1272071&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=00ADEF&amp;fullscreen=1" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="680" height="383"></embed></object><br /></p>
<p>The frames of that animation were then stacked up along the Z axis in 3D space and with the help of the <a href="http://toxiclibs.org/category/volumeutils/">volumeutils</a> classes turned into 3D mesh, <a href="http://code.google.com/p/toxiclibs/source/browse/trunk/toxiclibs/src.core/toxi/geom/util/STLWriter.java" onclick="pageTracker._trackPageview('/outgoing/code.google.com/p/toxiclibs/source/browse/trunk/toxiclibs/src.core/toxi/geom/util/STLWriter.java?referer=');">exported as STL format</a> (also see <a href="http://toxiclibs.org/docs/core/toxi/geom/util/TriangleMesh.html#saveAsSTL%28java.lang.String%29">TriangleMesh.saveAsSTL()</a>) and finally fabricated into the physical, 3D printed sculpture shown below. In a way, the sculpture can be seen as a map of its entire creation process&#8230;</p>
<p><img class="size-full wp-image-237" title="typeform_square_680" src="http://toxiclibs.org/wp-content/uploads/2010/02/typeform_square_680.jpg" alt="Type &amp; Form sculpture" width="680" height="680" /></p>
<p>Here&#8217;re some more rendered detail shots of the sculpture. <a href="http://postspectacular.com/work/printmag/" onclick="pageTracker._trackPageview('/outgoing/postspectacular.com/work/printmag/?referer=');">More information about this project is here</a> and the <a href="http://www.flickr.com/photos/toxi/sets/72157604724789091/" onclick="pageTracker._trackPageview('/outgoing/www.flickr.com/photos/toxi/sets/72157604724789091/?referer=');">related flickr set</a>.</p>
<p><img class="aligncenter size-full wp-image-265" title="typeform_detail1" src="http://toxiclibs.org/wp-content/uploads/2010/02/typeform_detail1.jpg" alt="" width="680" height="382" /></p>
<p><img src="http://toxiclibs.org/wp-content/uploads/2010/02/typeform_detail2.jpg" alt="" title="typeform_detail2" width="680" height="382" class="aligncenter size-full wp-image-266" /></p>
<p>Finally, the <a href="http://code.google.com/p/toxiclibs/source/browse/trunk/toxiclibs/examples/sim/GrayScottImage/GrayScottImage.pde" onclick="pageTracker._trackPageview('/outgoing/code.google.com/p/toxiclibs/source/browse/trunk/toxiclibs/examples/sim/GrayScottImage/GrayScottImage.pde?referer=');"><code>GrayScottImage</code></a> demo shows another supported technique of using the library: the seeding of the simulation using a bitmap image.</p>
<p><img class="alignnone size-full wp-image-194" title="GrayScottImage002" src="http://toxiclibs.org/wp-content/uploads/2010/02/GrayScottImage002.png" alt="" width="680" height="362" /></p>
]]></content:encoded>
			<wfw:commentRss>http://toxiclibs.org/2010/02/simutils-grayscott/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>simutils-0001: Diffusion limited aggregation</title>
		<link>http://toxiclibs.org/2010/02/new-package-simutils/</link>
		<comments>http://toxiclibs.org/2010/02/new-package-simutils/#comments</comments>
		<pubDate>Sat, 20 Feb 2010 11:44:16 +0000</pubDate>
		<dc:creator>toxi</dc:creator>
				<category><![CDATA[simutils]]></category>
		<category><![CDATA[3d]]></category>
		<category><![CDATA[diffusion]]></category>
		<category><![CDATA[dla]]></category>
		<category><![CDATA[generative]]></category>
		<category><![CDATA[octree]]></category>
		<category><![CDATA[particles]]></category>
		<category><![CDATA[rulebased]]></category>

		<guid isPermaLink="false">http://toxiclibs.org/?p=190</guid>
		<description><![CDATA[A few days ago I published some updates to all five existing main packages and also bundled up some other classes from existing projects into a new package, called simutils. As the name indicates, these new classes deal with the simulation of some fairly basic processes inspired by nature, but each of them exhibits some [...]]]></description>
			<content:encoded><![CDATA[<p>A few days ago I published some updates to all five existing main packages and also bundled up some other classes from existing projects into a new package, called <strong>simutils</strong>. As the name indicates, these new classes deal with the simulation of some fairly basic processes inspired by nature, but each of them exhibits some emergent behaviours which can be (and have been) used for a wide variety of design tasks from 3D printed sculptures to generative music. To help you get started, the package also contains two or three Processing demos for each process showing basic usage patterns. The three processes implemented so far are explained in more detail in this &amp; <a href="http://toxiclibs.org/2010/02/simutils-grayscott/">the next</a> few upcoming posts. Let&#8217;s start with&#8230;</p>
<p><img class="alignnone size-full wp-image-220" title="brownian_sunflow" src="http://toxiclibs.org/wp-content/uploads/2010/02/brownian_sunflow.jpg" alt="brownian motion" width="680" height="382" /></p>
<h2>Diffusion limited aggregation</h2>
<p><a href="http://en.wikipedia.org/wiki/Diffusion-limited_aggregation" onclick="pageTracker._trackPageview('/outgoing/en.wikipedia.org/wiki/Diffusion-limited_aggregation?referer=');">Diffusion limited aggregation</a>, DLA in short, is a theoretical process describing the clustering of particles through a process of diffusion, like a random walk/<a href="http://en.wikipedia.org/wiki/Brownian_motion" onclick="pageTracker._trackPageview('/outgoing/en.wikipedia.org/wiki/Brownian_motion?referer=');">Brownian motion</a>. Inspired by the work of <a href="http://www.andylomas.com" onclick="pageTracker._trackPageview('/outgoing/www.andylomas.com?referer=');">Andy Lomas</a> with this process, in 2006 I set out to implement DLA myself from scratch, in order to apply it to structures and literally grow objects not made out of triangles/polygons. At the same time I&#8217;d also just discovered the possibilities of <a href="http://toxi.co.uk/blog/2006_12_01_archive.htm" onclick="pageTracker._trackPageview('/outgoing/toxi.co.uk/blog/2006_12_01_archive.htm?referer=');">rendering huge point clouds with Sunflow</a>, which seemed the perfect combination to explore this all further. By March &#8217;07 I had a system in place which allowed me to grow type and have used it for a commission to produce the &#8220;New Shoots&#8221; title sequence for Channel4.</p>
<p><img class="alignnone size-large wp-image-207" title="New Shoots (still)" src="http://toxiclibs.org/wp-content/uploads/2010/02/456471284_95dc1b9b45_o-680x382.png" alt="" width="680" height="382" /></p>
<p>The basic premise of a DLA simulation is the slow formation of complex structures through the (random) movement of single particles. Once a particle comes close to an existing one, it attaches itself and a new particle is spawned in a sphere around a previous particle. The process then repeats, slowly filling up the simulation space. If the random walk ever takes a particle passed a certain escape radius, the search is restarted with a different initial direction until another particle is hit. Because particles are usually very tiny, a large number of them and even more iterations are required for even very simple structures to emerge. For example, <a href="http://www.flickr.com/photos/toxi/456487319/in/set-72157600200636464/" onclick="pageTracker._trackPageview('/outgoing/www.flickr.com/photos/toxi/456487319/in/set-72157600200636464/?referer=');">the final frame of the New Shoots sequence</a> consisted of 4.5 million particles, whereas the structure for the image below has a &#8220;mere&#8221; 645,000&#8230;</p>
<p><img class="alignnone size-large wp-image-196" title="dlatest_spiral2" src="http://toxiclibs.org/wp-content/uploads/2010/02/dlatest_spiral2-680x382.png" alt="" width="680" height="382" /></p>
<h3>Finding the needle in the haystack</h3>
<p>Searching for particle collisions in sets of such size linearly is super slow &amp; cumbersome, so to make the process more efficient, my version of DLA is using the <a href="http://toxiclibs.org/docs/core/toxi/geom/PointOctree.html">PointOctree</a> class from the core package. This class is recursively (and on-demand) subdividing the simulation space into smaller, nested cubes, which are stored as <a href="http://en.wikipedia.org/wiki/Octree" onclick="pageTracker._trackPageview('/outgoing/en.wikipedia.org/wiki/Octree?referer=');">tree structure</a>. When new particles are added by the DLA process they&#8217;re also being attached to the leaf nodes of the octree. When the next particle is searching for collisions with existing particles, these can then be found very quickly by querying the octree based on local search criteria using these 2 methods:</p>
<pre class="brush:java">PointOctree octree = new PointOctree(new Vec3D(-50,-50,50),100);
List&lt;Vec3D&gt; points; // in Java
java.util.List points; // in Processing, no support for generics!

// search within a sphere (i.e. all points within a certain distance)
Sphere boundingSphere = new Sphere(new Vec3D(),1);
points = octree.getPointsWithinSphere(boundingSphere); // or
points = octree.getPointsWithinSphere(origin, radius);

// search within an axis-aligned bounding box
AABB boundingBox = AABB.fromMinMax(new Vec3D(-1, -1, -1), new Vec3D(1, 1, 1));
points = octree.getPointsWithinBox(boundingBox);</pre>
<p>For more usage information about the octree also see the <a href="http://code.google.com/p/toxiclibs/source/browse/trunk/toxiclibs/examples/sim/DLASpiral/DLASpiral.pde" onclick="pageTracker._trackPageview('/outgoing/code.google.com/p/toxiclibs/source/browse/trunk/toxiclibs/examples/sim/DLASpiral/DLASpiral.pde?referer=');">DLASpiral</a> demo (the screenshot below also shows the adaptive structure of the octree) and the <a href="http://code.google.com/p/toxiclibs/source/browse/#svn/trunk/toxiclibs/examples/core/OctreeDemo" onclick="pageTracker._trackPageview('/outgoing/code.google.com/p/toxiclibs/source/browse/_svn/trunk/toxiclibs/examples/core/OctreeDemo?referer=');">OctreeDemo</a> of the core package&#8230;</p>
<p>In the future I&#8217;ll probably refactor this current dependency on the <code>PointOctree</code> class and have the <code>DLA</code> merely depend on a more generic <code>SpatialTree</code> interface, which then can also be implemented by other tree types, e.g. a <a href="http://en.wikipedia.org/wiki/Kd-tree" onclick="pageTracker._trackPageview('/outgoing/en.wikipedia.org/wiki/Kd-tree?referer=');">kD tree</a>. To compensate, the DLA class so far has an extension point of sorts to allow custom <code>PointOctree</code> sub-classes to be used. In this case you&#8217;ll simply have to also sub-class <code>DLA</code> and overwrite the <code>createOctree</code> method to return an instance of your custom <code>PointOctree</code>.</p>
<p><img class="alignnone size-full wp-image-192" title="DLASpiral004" src="http://toxiclibs.org/wp-content/uploads/2010/02/DLASpiral004.png" alt="" width="680" height="362" /></p>
<h3>Guided growth</h3>
<p>In the above screenshot you can also see the blue spiral shape guideline directing the growth of the particles. These guidelines can either be individual line segments or points lists, e.g. sourced from a <a href="http://toxiclibs.org/docs/core/toxi/geom/Spline3D.html">Spline3D</a> instance or computed otherwise. When passing in a list of points, they&#8217;re connected into successive line segments internally. At least one line segment is required for the DLA process to function and you&#8217;d combine the 2 classes like this:</p>
<pre class="brush:java">// define a spline
Spline3D spline = new Spline3D();
spline.add(new Vec3D()).add(new Vec3D(0,-50,0)).add(new Vec3D(50,0,50)).add(new Vec3D(0,50,0));
DLAGuideLines guides = new DLAGuideLines();
guides.addCurveStrip(spline.computeVertices(8));

// setup DLA in a cubic space of 100 units edge length (always centred around (0,0,0))
DLA dla = new DLA(100);
// assign guideline(s)
dla.setGuideLines(guides);
</pre>
<p>The moment the guidelines are attached, each line segment is sampled at a high resolution and the computed points added to a second octree kept by the <code>DLA</code> class. It&#8217;s these points which are shown in the above screenshot (although only 10% of them are displayed)&#8230;</p>
<p><object width="680" height="382"><param name="movie" value="http://www.youtube.com/v/yDIh3PVq3RE&#038;fs=1" /><param name="allowFullScreen" value="true" /><param name="allowscriptaccess" value="always" /><embed src="http://www.youtube.com/v/yDIh3PVq3RE&#038;fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="680" height="382"></embed></object></p>
<h3>Order of growth</h3>
<p>By default the growth of the entire particle system will be in the same order as the guideline segments have been added, however you&#8217;re free to change this by means of custom <a href="http://java.sun.com/javase/6/docs/api/java/util/Comparator.html" onclick="pageTracker._trackPageview('/outgoing/java.sun.com/javase/6/docs/api/java/util/Comparator.html?referer=');">Compatators</a>. The <a href="http://code.google.com/p/toxiclibs/source/browse/trunk/toxiclibs/src.sim/toxi/sim/dla/DLAGuideLines.java" onclick="pageTracker._trackPageview('/outgoing/code.google.com/p/toxiclibs/source/browse/trunk/toxiclibs/src.sim/toxi/sim/dla/DLAGuideLines.java?referer=');">DLAGuideLines</a> class is storing <a href="http://code.google.com/p/toxiclibs/source/browse/trunk/toxiclibs/src.sim/toxi/sim/dla/DLASegment.java" onclick="pageTracker._trackPageview('/outgoing/code.google.com/p/toxiclibs/source/browse/trunk/toxiclibs/src.sim/toxi/sim/dla/DLASegment.java?referer=');">DLASegment</a> instances in a sorted <a href="http://java.sun.com/javase/6/docs/api/java/util/TreeSet.html" onclick="pageTracker._trackPageview('/outgoing/java.sun.com/javase/6/docs/api/java/util/TreeSet.html?referer=');">TreeSet</a>. The order of this set can be defined by defining a custom comparator implementation when creating the guidelines and so any possible growth order can be designed/defined. The example below defines one which enforces a bottom-up growth (assuming positive Y is up):</p>
<pre class="brush:java">// define comparator
// (this how to do in Processing, which doesn't support generics...
// in plain Java you'd compare Line3D instance directly
// without the need for casting from Object)
class BottomUpOrder implements Comparator {
  public int compare(Object a, Object b) {
    float ya=((Line3D)a).getMidPoint().y;
    float yb=((Line3D)b).getMidPoint().y;
    if (ya&lt;yb) return -1;
    if (ya&gt;yb) return 1;
    return 0;
  }
}

// now use the comparator for the guidelines
DLAGuideLines guides = new DLAGuideLines(new BottomUpOrder());
</pre>
<p>The next release of this package will contain a few more of those&#8230;</p>
<h3>Parameters of growth</h3>
<p>The final requirement for the whole process to start is a set of configuration parameters. Of these there are many and so they&#8217;re encapsulated in their own class. To use them they&#8217;re simply passed to the DLA like:</p>
<pre class="brush:java">// use default configuration
dla.setConfig(new DLAConfiguration());
</pre>
<p>The default configuration has the following values, also briefly described below:</p>
<pre class="brush:java">// threshold distance below which a particle attaches itself to an older one
float snapDistance = 1.8f;
// threshold distance to attach to a curve/guideline particle
float curveAttachDistance = 2;

// max. radius of the sphere in which a new particle is spawned around a previous one
float spawnRadius = 12;
// max. radius of the sphere when the particle's random walk is interrupted/restarted
float escapeRadius = 36;
// actual size of the particles (currently assumed to be uniform for entire system)
float particleRadius = 0.25f;
// stickiness factor, only 10% of all attachments will be successful
float stickiness = 0.1f;
// using guidelines the growth can be forced into a certain direction
// this parameter defines the impact strength of this direction
// if 0.0 particles grow in all directions, 1.0 = actual segment direction is used
float curveAlign = 0.74f;

// percentage amount to progress along segments after each new particle
float curveSpeed = 0.00045f;
// velocity of the random particle walk
float searchSpeed = snapDistance * 0.66f;
// turn speed when particle changes direction
float particleSpeed = 0.001f;

// progress speed when scanning guidelines to build octree
float guideLineDensity = 0.1;

// chance for existing/already processed segments to continue growing
// evaluated before spawning each new particle
float continousGrowthRatio = 0.1f;
</pre>
<h3>Why a library?</h3>
<p>Whereas this is setup creates very interesting structures (especially when rendered in Sunflow), my idea for this library was not necessarily to have everyone replicate this specific look over &amp; over again, but provide the means to focus more on exploring the actual growth process, to customize it and use it as driver for creating new structures in which the actual particles are only present indirectly/secondary. One key feature for that matter are events emitted by the DLA class at key moments of the process. The <a href="http://code.google.com/p/toxiclibs/source/browse/trunk/toxiclibs/src.sim/toxi/sim/dla/DLAEventListener.java" onclick="pageTracker._trackPageview('/outgoing/code.google.com/p/toxiclibs/source/browse/trunk/toxiclibs/src.sim/toxi/sim/dla/DLAEventListener.java?referer=');">DLAEventListener</a> interface defines the following 3 event hooks:</p>
<pre class="brush:java">public interface DLAEventListener {

    void dlaAllSegmentsProcessed(DLA dla);

    void dlaNewParticleAdded(DLA dla, Vec3D p);

    void dlaSegmentSwitched(DLA dla, DLASegment s);
}
</pre>
<p>You can subscribe to these events by either creating your own class implementing this interface or sub-classing the also supplied <a href="http://code.google.com/p/toxiclibs/source/browse/trunk/toxiclibs/src.sim/toxi/sim/dla/DLAEventAdapter.java" onclick="pageTracker._trackPageview('/outgoing/code.google.com/p/toxiclibs/source/browse/trunk/toxiclibs/src.sim/toxi/sim/dla/DLAEventAdapter.java?referer=');">DLAEventAdapter</a> (in case you don&#8217;t want to react to all of them):</p>
<pre class="brush:java">class MyDLAListener extends DLAEventAdapter {

  // only get notified when growth is complete
  public  void dlaAllSegmentsProcessed(DLA dla) {
     System.out.println("done");
  }
}

DLA dla=new DLA(100);
// attach listener
dla.addListener(new MyDLAListener());
</pre>
<p>Alternatively, listening to &#8220;new particle&#8221; events allows you to construct elaborate structures not just from particles, but use particle positions to deposit small meshes or use <a href="http://toxiclibs.org/category/volumeutils/">volumeutils</a> to draw with a <code>VolumetricBrush</code> at these positions&#8230; There&#8217;re endless possibilities for further exploration and I hope some of you are excited enough to explore them! If so have fun &amp; share it!</p>
<p><a href="http://www.flickr.com/photos/toxi/tags/dla/" onclick="pageTracker._trackPageview('/outgoing/www.flickr.com/photos/toxi/tags/dla/?referer=');">Some more of my own earlier explorations into this field are on flickr.</a></p>
<p><img class="alignnone size-large wp-image-210" title="dlatest_spiral" src="http://toxiclibs.org/wp-content/uploads/2010/02/dlatest_spiral-680x382.png" alt="" width="680" height="382" /></p>
]]></content:encoded>
			<wfw:commentRss>http://toxiclibs.org/2010/02/new-package-simutils/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>
