Paul N Jeffries

avatar

Mar 262014
 

Example 2B: Switching between two points, If statements

In the last session, we created our own version of the built-in line component.  Now let’s take that previous example and move it a bit beyond what we could have just done with the standard component.  Let’s make it so that the component is smart, and that if we give it a choice between two end points it will pick the one which is closest to the start.

Add a new point to the Rhino document and a new Point parameter in grasshopper that references it.  Now zoom in on the C# component until the tiny + and – symbols appear.  Click on a ‘+’ to add a new input parameter.

C#2_1

Name it ‘PtC’ and set its type hint to Point3d.  Connect our new point to it.

Change the code inside the script component to look like this:

Now lets look at what’s going on here, shall we?

Firstly, we calculate the distance between PtA and the other two points.  The ‘Point3d’ structure has a built-in function to find the distance between the given point and another one.  Functions are subroutines that give an output answer – more on those later.

Once we have these distance values stored we need to compare them and then choose which point to connect to PtA.  This is where if statements come in handy:

 

‘(distAB < distAC)’ is the conditional statement that is being evaluated.  If it is true (i.e. distAB is lower than distAC) then the first block of code will be executed and the code will then skip forwards to after the if statement.  If it isn’t true then the code skips the first block and goes down to ‘else’ and executes the second block of code.

Note that we declare myLine before we go into the if statement without actually assigning anything to it.  This is because variables are only valid inside the scope in which they are declared.  If we declared myLine inside the if statement we could not then use it outside it.

If we try this out by moving our points around you should find that the line now automatically jumps to the closest point.

 

This kind of thing can be very useful for getting your definitions to adapt to different circumstances in an intelligent manner.  We could achieve the same thing in native grasshopper by using a Dispatch or Pick ‘n’ Choose component in conjunction with a function component returning true or false and a bunch of other components computing the distance, but it can often be easier and neater to do it in code, especially when things get more complicated.

 

Example 3A: Creating a truss, Lists and Loops

For performing repetitive operations on a large number of inputs grasshopper has lists and trees, but it still cannot be used for many complex iterative operations that would be relatively easy to implement in code.

This next example takes in two lists of points and iterates through them to draw a zig-zag line between them, as you might want to do to create part of a truss structure.

Firstly we will create two lists of points by subdividing curves.  Draw two roughly parallel curves in Rhino and bring them into grasshopper via some Curve components.  Pass those curves into a pair of Divide Curve components to generate two lists of points.

Now we will bring those two lists into a C# component.  Create a new one and set the type hint for both x and y inputs to Point3d.  Since we are no longer bringing in single values we need to tell the component to treat x and y as lists of objects rather than individual objects.  To do this right click on each input and select the ‘List Access’ option.

If we take a look inside the script editor for that component now we will see that the type of x and y parameters have changed to List<Point3d>.  Lists are generic containers that can be used to hold any other type of object.  The type to be used is defined inside the angle brackets (‘<’ and ‘>’).  They function similarly to arrays but with extra functionality and with the bonus that they will automatically resize themselves when new items are added.  Get used to them because you are going to be using them a lot!

Plug the two lists of points into x and y and in the script editor add:

First of all I rename our inputs ptsX and ptsY by defining new Lists of Point3d variables and assigning x and y to them (the reason why I do this will become clear in example 3B).

Since we are going to create more than one line this time around we need to create a new list to hold them all in one place so that they can all be output to A as a group.  Lists are a type of object so to create one we need to use the new keyword.  We define the type it will contain inside the angle brackets after the type name (in this case, the list will hold lines).  Even though we are using the default constructor and aren’t entering any parameters to initialise the list with, we still have to include a pair of empty brackets when creating the new list.

Next we begin our loop – in this case a for loop, meaning that we are going to iterate a particular variable until a certain condition is met.  The brackets behind the ‘for’ are split into three sections separated by semicolons.

The first part tells the for loop what to iterate.  In this case we create a new integer variable called ‘i’ and set it to a starting value of 0.

Next we tell it when to iterate (and when to stop).  In this case we give it the condition to continue iterating while i is lower than the number of points in ptsX – which we retrieve by using the ‘Count’ property of that list.

This means that when i is larger than or equal to the number of points the loop will exit and continue with whatever is next in the script.  We do this so that the loop will execute once for each item in the list.

Finally, we tell the loop how to iterate.  In this case we use the ++ operator, which in C-like languages means ‘add one to’.  We could also have written this as i += 1 and gotten the same result – each time the loop has executed it will add 1 to the current value of i and start again (provided the condition we just gave it in the middle part is still true).

The next part inside the curly brackets is the block of code that will be repeated by the loop.

We start by picking the points from the list that we want to use.  You can access a particular item from a list by enclosing its index (its position in the list, starting from 0) in square brackets after the name of the list.  In this instance, we are picking the points from ptsX and ptsY that are at position i – meaning that as the loop iterates and i increases we will retrieve every pair of points in the two lists.  We store the points in new variables called ptA and ptB and then draw a line between them the same way as we have done previously.

Once we have created our line we use the Add() subroutine to append that line to the back of our output list.

Finally, outside of the loop, we assign our output list to our output object A.

This example so far will create a ‘ladder’ between the two initial curves by joining equivalently numbered points.  Essentially we have replicated in code Grasshopper’s default data-matching option, where the first item in each list will be processed together, the second in each list also matched and so on.

The next step in creating the ‘zig-zag’ is to also join up the first list of points with an offset of the second list of points.  To do this with grasshopper components we could use the Shift List component to create an offset copy of the initial list.  However, in code we can do this in a more direct (and efficient) fashion.

Add the following to the end of the block of code inside the for loop:

This section of code finds the next (the ‘i+1th’) point in the list ptsY and then creates a line between it and our original ptA, then adds that line to our output.  This will create the diagonals of our zig-zag truss bracing.

However, if we now press ‘OK’ to close the script editor, we will see that something has gone wrong.  The script component has gone red and is no longer outputting any geometry at all!

To find out what has gone wrong hover your mouse either over the ‘out’ output or the small red error speech bubble that will have appeared in the top right of the component.  Doing so, you should get something like this:

Why are we getting this error?  Well, let’s imagine we have eleven points in each of our input lists, stored in locations 0-10.  When i = 10 in our code, ptA will be ptsX(10), ptB will be ptsY(10) and ptC will be ptsY(11), which will be something of a problem because there is no ptsY(11) – our index is outside the bounds of the list.

For our script to run successfully we will need to stop this from happening.  We can do this by placing an if statement around the piece of code we just added to make sure it is not trying to add a diagonal when i is already the last item in the list.

So, our complete script should now look like this:

Which should produce our zig-zag lines:

You can download the example grasshopper files for this session here:

C# Examples 2B & 3A.zip

Mar 192014
 

I’ve made some minor post-challenge tweaks and bugfixes to 7DArrrL, thus making the name even less accurate.  This new version fixes a couple of mistakes I made in my sleep deprived state and polishes off a couple of minor features that I didn’t have time to quite finish.  There are no major new content additions however and it’s basically the same as the same as the 7-day version with a little bit more love and care lavished on it.  Stay tuned, however, to possibly see it morph into a proper game one day.

download
(7DArrrL.zip – 7.85Mb – Requires Java)

Changes:

- Fixed bug where AI ships south of you will mistakenly head away from you rather than towards you (remember kids; always use Atan2 rather than Atan)
- Force generated by sails now uses relative rather than absolute wind speed.  Wind strength, drag factors etc. adjusted to compensate.
- Sails independantly rotate depending on wind direction
- Wind now starts in random direction
- AI ships now slightly more agressive and less stand-offish in combat
- Ships now sink faster and cannot steer while doing so.
- Game now restarts on death

 Day8(3)Day8

Mar 162014
 

(Note: I’ve since released a post-challenge bug-fix version of the game, which you can download here.  I’ve left the download below active for people who are particularly interested in seeing the 7-day version.)

7DArrrL is this year’s attempt at the 7DRL challenge.  It’s a semi-success; I didn’t have time to put in everything I wanted to (my initial plans were massively over-ambitious, I realised about half-way in) but it’s still a playable game, even if only as a high-score challenge/demo of the combat system.  Unfortunately the bits I didn’t get around to doing are mostly the bits that would have made it more of an actual Roguelike.  I quite like what I’ve got so far, though, so I will probably carry on working on it and turn it into a full game once I’ve had a bit of a rest (and come up with a new name).

7DArrrL is a naval combat sim in which you play a pirate captain.  Sail the high seas and destroy your enemies!  You can download it here:

download(7DArrrL.zip – 7.85Mb – Requires Java)

 Day 6 - Dawn battle

Since the control system is fairly unique, it could probably do with a bit of explanation.  Here’s what the interface looks like and what it does:

InterfaceAnnotation

  1. The 3D view of your ship.  Click and drag or use the arrow keys to rotate the view.  Use the mouse wheel to zoom.
  2. The ship’s wheel.  Used to set your course, relative to your current direction.  Click on a point on the wheel to change your heading.  You can also use the Q and E keys to steer left and right respectively.
  3. Your hull button.  The % number displayed here is your current hull integrity.  If this reaches 0%, you’re sunk!  Crew not assigned other duties will remain in the hull and work on repairing the ship.
  4. Sails button.  Click on this to see the sails orders menu.  The more crew you have assigned to the sails the faster you will be able to change sail.  You can also press W and S to increase or decrease the amount of sail respectively.
  5. The port and starboard cannon batteries.  Click on these buttons to see the cannon order menus.  The more crew you have assigned to each battery the faster you can reload.
  6. The number of crew assigned to each part of the ship.
  7. Time controls.  Use this to stop or speed up the flow of time.  You can also right-click or press the space bar to pause/resume.  You can adjust your heading and issue orders even when time is stopped.
  8. The compass.  Shows the direction of the current view.
  9. The wind direction.  Pay attention to this.
  10. The amount of gold you have plundered.  Try to get as much as possible!

How to sail:

  • You have two kinds of sails; square-rigged and fore-and-aft.  Square-rigged sails are most efficient when travelling with the wind, but will slow you down if going into the wind.  Fore-and-aft sails are less efficient but allow you to sail closer to the wind.
  • When trying to move upwind, set your sails to ‘Fore & Aft only’ to avoid drag.  Note that it is still not possible to sail directly into the wind.
  • The faster you are moving, the faster you will turn.  The faster you can turn, the easier it will be to bring your cannons to bear.
  • You can order your cannon batteries to fire a broadside manually using the “Fire!” command.  Unless your aim is very good, however, it’s probably better to order them to fire at will.
  • Cannonballs do much more damage at close range.
  • Crew are likely to die from enemy fire, but should you defeat a ship, you will be able to replace your losses by ‘persuading’ some of their crew to join yours.

The enemy ships are perfectly matched with your own, so if you actually manage to take one down you’re doing very well.  If you manage to get two or more then you are a king of all the pirates!

Day 7 - New Dawn

Feb 272014
 

Grasshopper in its natural state is a very powerful tool capable of many impressive feats.  However, due to the way in which it operates there are some kinds of algorithms than are not possible to fully reproduce using its component-based system that would be trivial to implement in a traditional programming language.  Although it contains a vast array of components there are still some areas in which it is lacking in functionality and it can therefore be necessary to extend it by writing new components yourself.  Also, there are often things which, while possible, require long strings of components to achieve what might be more simply implemented as just a few lines of code.

 

C#

In the examples given here we will be using C# as our scripting language.  This has been chosen because its syntax should be familiar to people who have used any other of the ‘C’ family of programming languages (C, C++, Objective-C) or those based on it (Java, JavaScript, Processing, D, PHP etc.) and also because it can be used for some of the more powerful forms of programming within Rhino, such as writing custom Grasshopper components and even whole other Rhino plugins, which Python currently cannot.  However, none of the parts of these examples which interact with Grasshopper/Rhino are language specific and should be the same whether you are using C#, Visual Basic or Python – only the language syntax will be different, so you should be able to apply the following to whichever language you prefer to use.

C# is a version of C designed around the .NET framework, meaning that it can be used with all of the standard .NET libraries and is compatible with code written in other .NET languages (such as VB.NET).  It is a managed language, meaning that you do not need to manually delete objects to free up memory – the language cleans up after itself automatically.

For the following, no prior knowledge of C# itself is assumed, however we focus on those parts of the language which are specifically useful for grasshopper without dwelling too much on syntax or programming theory except for where it is particularly relevant – for a more comprehensive overview of the language you should look elsewhere.

To ease the transition into C# for those familiar with scripting in a different language it can be useful to know how it relates to other coding languages:

C#1_25

C# is most obviously influenced by C and the languages based on it and so shares similar syntax with C++ and Java (and hence Processing).  However it is also built on top of the .NET Framework which allows it to use and interact with code written in other .NET languages such as Visual Basic.NET (in which Grasshopper itself is -currently- written) and IronPython.

RhinoCommon

RhinoCommon is the library that we use for interacting with Rhino and geometry objects such as points, curves and surfaces.

Here’s where things could get confusing if you’re looking for examples on the web, however: RhinoCommon is a relatively recent development – before that there was another library that was used for the same thing called RhinoDotNet, which was a lot harder to use (trust me on this, I know whereof I speak).  Some people still use RhinoDotNet, however, and there are a lot of examples of it around on the internet, so be aware of this if you’re copying an example and it seems not to be working – if there are a lot of types starting with ‘On’ and ‘MRhino’ then you’re probably looking at a RhinoDotNet example rather than a RhinoCommon one.  Just a word of warning.

 

Example 1: A simple C# scripting component

 

First, open grasshopper with a new (blank) file.

All the scripting components can be found on the Math tab, under the heading ‘Script’.  Click on the ‘C# Script’ component and drop it onto the canvas.

 C#1_1

If you zoom in enough, the component should look something like this:

C#1_2

By default, it has inputs called ‘x’ and ‘y’ and outputs called ‘out’ and ‘A’.  You can customize this, however.  The little ‘+’ and ‘-‘ signs next to each of these lets you add and remove inputs.  Click on the ‘-‘ next to ‘y’ to remove that input.

C#1_3

C#1_4

For our first component, we’re going to do something super simple – we are just going to take in a number (‘x’) and divide it by 2.

But, before we start coding, let’s tell the component that x is supposed to be a number.  To do this, right click on the ‘x’ input.  In the drop-down menu, click on ‘Type hint’ and then ‘double’.  ‘double’ is just programmer-speak for a number (more specifically, it is short for double-precision floating point number).  Above that is ‘int’, which is for storing integer (i.e. whole) numbers only.

C#1_5

Now create a slider and plug its output into ‘x’:

C#1_6

Now we’re ready to rock!  Double click on the centre of the C# component and the following sight should greet you:

C#1_7

Whenever the component gets updated, the subroutine RunScript gets called and the inputs and outputs of the component get passed in as parameters – in this case our input ‘x’ and our output ‘A’ so that we can use them and modify them.  But hang on, you might say, don’t we have two outputs on this component?  What about ‘out’?

‘Out’ is there on every scripting component and is used to send messages to the outside world.  To demo this, let’s do the traditional ‘hello world’ example.  In between the curly brackets below RunScript, type this:

C#1_8

Scripting components have a built-in subroutine called ‘Print’ which is used to output stuff to the ‘out’ output.  If you press the OK button on the script window and plug a panel component into ‘out’.  If all has gone well, the words “Hello World!” should appear therein.

C#1_9

This is useful mainly for debugging purposes – you can output little messages that tell the user how the script is doing.  Any exceptions which occur when the script is running will also be reported here.

Let’s just break down what this little snippet is doing.  The first line is just a comment – the ‘//’ denotes it as such and tells the interpreter to completely ignore the rest of the line when running the script – it’s there just for the benefit of the programmer and doesn’t actually do anything.  ‘Print’ is the name of the subroutine we are calling.  The brackets contain the parameters we are passing – in this case ‘Hello World’ which is enclosed in speech marks which denote it as a string literal (i.e. tell the interpreter that it is a bit of text and not a variable name or anything else).  The ‘;’ just tells the interpreter that this is the end of the statement.

OK, let’s now make the script do something useful.  Back to the script editor and below what we’ve just written put:

C#1_10

Here, we’ve declared a variable of type double called ‘denominator’ and assigned a value of 2 to it.  In C# you declare a variable by putting its type name and then it’s own name.  You can optionally then assign a value to it on the same line if you wish.  Don’t forget the ‘;’.

Below this, write:

C#1_11

This declares a new variable called ‘answer’ and assigns to it the result of a calculation whereby our input variable x gets divided by the variable ‘denominator’ we just defined.

Now add:

C#1_12

This assigns the answer  we just calculated to our output parameter ‘A’.  And we’re done!

C#1_13

Press ‘OK’ and then plug another panel into ‘A’.  You should find that whatever value you put into x, you get half of it out of A.

C#1_14

Obviously, you could modify this code to use any mathematical formula that you liked.

 

Example 2A: Drawing a line between two points.  Objects, Value and Reference types.

 

The previous example is all very well but of course it isn’t anything that couldn’t be done with a function component.  Let’s move on to how to manipulate geometry.  For starters we’re going to duplicate the functionality of the standard ‘Line’ component to draw a line between two points.

In Rhino, create two points and reference them in grasshopper with two point components.

C#1_15

Now add a new C# component.  Right click on the x and y inputs and change their names to ‘PtA’ and ‘PtB’ respectively.  Set both of their type hints to ‘Point3d’.  Change the name of output A to ‘Ln’.

C#1_16

Plug the two points into PtA and PtB.  Now double click to open up the script window.  Note that the parameters of RunScript are different now to reflect the changes we have just made to the inputs and outputs (make sure that in particular PtA and PtB are now Point3ds, otherwise this next bit won’t work).

C#1_17

Add in:

C#1_18

Here we create a new line object called ‘myLine’ that runs between PtA and PtB.  We are using one of lines built in constructor subroutines that takes in the two points that the line runs between.  As you’re typing the intellisense helper should pop and show the types of parameters you can put in to create the line:

 C#1_19

There are a couple of other ways of constructing lines – for example by putting in a start point and a vector to follow instead.

To finish up just output myLine to Ln:

C#1_23

Click ‘OK’ and you should now have your very own line component.

C#1_24

The example files for this session can be downloaded here:

C# Examples 1 & 2A

Feb 122014
 

In this session we will be looking at some more advanced components and methods of using grasshopper, principally focussing on Galapagos, Grasshopper’s built-in genetic algrithm solver.  Along the way, we’ll also be examining Grasshopper’s metaball component and means of flow control – the Grasshopper equivalent of ‘if statements’ in coding.

Example 7: Galapagos

Galapagos is best used to solve problems to which the optimal solution is not immediately obvious. In this example the problem which we are going to try and solve is to examine a field of points and attempt to enclose as many of those points as possible within a closed curve of a fixed maximum length. If you want a physical analog – imagine that each point is a pin and we have a loop of string that we want to fit around as many as we can.

The first step is to obtain our set of points – you can either use the one in the example file provided or create your own using the Points command and clicking lots.

In Grasshopper we will reference in these points in the usual way – add a Point parameter component, right click and select ‘Set multiple points’.

Ex7_1

Now we want some way of drawing a closed cuve through those points.  A quick way (albeit probably not an ideal one) of generating an organic-looking closed curve in Grasshopper is through the Metaball components.

Metaballs

Metaballs are a form of geometry known as Implicit Surfaces, so-called because rather than rather than being explicitly defined by a particular mathematical equation, they are instead implicitly defined as isosurfaces (i.e. contours) through some scalar energy field.

The centre of each metaball might be considered an energy source with a falloff in the level of energy with distance from the point.  The surfaces of the metaballs then represent all of the points within that energy field with a particular energy value.

impl

Metaballs can be found in a variety of other modelling packages, where they are most commonly used to generate ‘gooey blobby things’ as the combination of energy fields tends to result in metaballs in close proximity bleeding into one another.

Gaussian_2a Gaussian_2b Gaussian_2c

If you are familiar with metaballs from elsewhere, or even if you’re not, the Grasshopper implementation of them might seem a little weird.  Firstly, metaballs in Grasshopper are not actually balls at all, or even 3d, or even (despite being found on the Mesh tab) meshes.  Instead, Grasshoppper currently only provides components to generate curves which represent flat 2d slices through a set of metaballs.  If you did want to create 3d metaballs from these you would need to generate a number of these on different planes and then construct the 3d form yourself.

Nonetheless, for what we want right now only a flat curve is required, so the components provided should be adequate.

Firstly, we want to be able to control the source point of each metaball.  More to the point, we want Galapagos to be able to control the source point of each metaball, and that means that we need to set up sliders to control the x and y coordinates of each point, since Galapagos can only exert control over slider (and, as we’ll see in a second, slider-like) components.

We could just use our old friend Number Slider for this, but as we will be creating multiple source points with multiple x and y coordinates, instead we will use the Gene Pool component.  Grab one from Params/Util box and add it to the canvas.

Ex7_2

A Gene Pool is basically a bunch of Number Sliders all bolted together into one component.  Rather than giving us a single number, they will give us a list of numbers with each number being controlled by a different slider in the pool.  We could use multiple Number Sliders for exactly the same purpose, but Gene Pools have the advantage of being slightly easier to set up.

Double-click on the Gene Pool to open the editor.  The Minimum and Maximum fields work the same way as with Number Sliders, only they affect all of the sliders in the pool.  We want our range of positions to encompass all of our points, so enter some suitable values based on the maximum and mimimum extents of your point field on the x and y axes.  The ‘Gene Count’ is the number of sliders to be contained within the pool.  Set this to 3.

Ex7_3

 

This first Gene Pool will represent the x-coordinates of our, source points.  Create a copy of it to represent the y-coordinates and then plug them both into the relevent inputs of a Construct Point component (Vector/Point).  Adjust the minimum and maximum extents of the Gene Pools if necessary so that the source points can move anywhere within our point field.

Ex7_4

Now add a Metaball(t) Custom component from Mesh/Triangulation to the canvas.  Plug the output of our Construct Point component into P.  Add another Gene Pool with a Gene Count of 3 and plug it into C – this will control the charge of each point source.  Try moving the source points around and changing the charge values to see how the metaballs join together and come apart.

Ex7_5

This now generates the curve(s) which we are going to try to fit around as many points as possible – this is as complicated as our actual geometry is going to get this time around.  However, before we can use Galapagos we need to get some kind of numeric feedback about the current arrangement.  Specifically, we need to know the number of points inside the curve and also the length of the curve.

To determine the number of points inside the curve we will use the Point In Curves component from Curve/Analysis.  Note the s – we could conceivably have multiple curves coming out of our Metaball component, so the alternative, Point In Curve component will not give us what we want.  Plug our inital point field into P and our Metaball curve into C.  The R output will return an integer which depends on whether each point is outside the curves (0), inside the curves (2) or directly on one of the curve (1 – rather unlikely in this setup!).  Using this, we want to count all of the points which are inside, i.e. all of the ones which give us an output of 2.

Ex7_6

If we were scripting rather than using Grasshopper, we could use an ‘if statement’ to check whether a particular condition was met and then take action accordingly.  For example, in C#:

if (R == 2)
{
//R is 2, do something
}
else
{
//R is not 2, do something else
}

Grasshopper doesn’t have if statements, but we can do something very similar by combining two different components – one which tests a particular conditional (i.e. is R equal to 2) to give us either a true or false and another which directs the flow of data accordingly.

Feed the R output into a new Equality component (Maths/Operators) and set the other input to the number 2.  This will perform our conditional check and then return either true or false, depending on whether the condition is satisfied.  In turn, feed that output from = into the P input of a Dispatch component.  Plug our original point field into L.  The Dispatch component will take in a a list of objects into L and a list of boolean values (i.e. true or false) into P.  If the value in P is true, then the matched item from L will be sent to the A output, else if it is false it will instead be sent to the B output.  This makes this a very useful component for sorting out objects into two lists given particular requirements.  If you plug a new Point parameter component into A and select it then you should see that it is giving us all of the points in our field which lie inside the curve (while B is all of the points that lie on or outside the curve).

Ex7_7

For our purposes, all we really care about is how many of them there are – use a List Length component from Sets/List to count them.

Next, add a Galapagos component to the canvas from Params/Util.  The Galapagos component looks a little weird, which is fitting considering it works in a very different way to most Grasshopper components.  It has a nodule on the left hand side called ‘Genome’.  The ‘Genome’ is the inputs which we will allow Galapagos to control.  Drag a wire out from this nodule and connect it to the first of our Gene Pools.  Hold down the shift key (exactly as if we were plugging multiple outputs to the same input) and also connect the remaining Gene Pools.  This lets Galapagos know that it has free reign to modify those inputs.  Any other input components which we do not connect in this way will remain constant at their current value when Galapagos is run.

On the bottom of Galapagos is another nodule marked ‘Fitness’.  This is where we connect a single, numeric value which tells Galapagos how good (or not) the current solution is.  Add a new Number parameter component (Params/Primitive) and drag a connector from the fitness nodule to this new component.  Whatever we plug into this Number component will now be taken as Galapagos’s fitness score.

Ex7_9

We now have all that we need to run Galapagos – if you like you can jump ahead to the Galapagos section below and run Galapagos using just the number of points as our fitness value.  However, we are unlikely to get very good results out at this stage – Galapagos will simply try to enclose as many points as it possibly can (and may struggle to do that, since the problem is fairly underconstrained at this point).

This one number alone however does not give us the full picture – we also care about how long the curve is.  To be specific; we want to tell Galapagos not to let the curve go longer than a certain length.  To do this we need to check what the cumulative curve length is, check it against some limit and if it is exceeded, apply a penalty to the fitness score to let galapagos know that this is not an evolutionary path it wants to go down.

Plug a Length component (Curve/Analysis) into the back of the metaball component, then add a Mass Addition component (Maths/Operators) to the back of that.  This will take care of the cases where we have more than one curve coming out of the metaball component and will give us the total length of all curves.

Ex7_10

Now add a Number Slider to control the length limit and use a Larger Than component (Maths/Operators) to compare it to the actual length.  This will return true if the length exceeds the limit.  In this case we want to subtract a penalty score from our fitness, or alternatively if it is false we do not want to subtract anything.  Add a Pick ‘n’ Choose component from Sets/List.  This component is a close cousin of the Dispatch component we used earlier but works in the opposite way – rather than taking in one input and splitting it between two outputs based on a pattern, the Pick ‘n’ Choose component takes in two inputs and returns one of them based on a pattern.  Plug the Larger Than output into P (this asks for an integer which defines the input number to take, but plugging in a boolean will work as well, as false will convert to 0 and true will convert to 1).  Plug the number o into the 0 input (here typed into a Panel).  Into 1 we need to plug our penalty value – we will use the cumulative curve length itself so that the penalty will increase the greater the amount by which this exceeds the limit.

Ex7_11

Finally, use a Subtraction component (Maths/Operators) to subtract the result of the Pick ‘n’ Choose component from the fitness score.  By manually playing around with the Gene Pool sliders, you should see that so long as the curve length is lower than the limit the fitness score will be the number of points contained within.  If the curve length exceeds the limit then the score will be significantly decreased.  The maximum score possible will be for a situation that encloses as many points as possible but which does not exceed the specified limit and it is this situation that we have thus instructed Galapagos to find.  The key to using Galapagos effectively is to contrive some kind of ‘scoring system’ such as this where our ideal outcome will score highest (and other options will score progressively worse the further away from this ideal they are).

Ex7_12

 

 Galapagos

Galapagos is a ‘genetic’ or ‘evolutionary’ solver, so called because it mimics the process of natural selection and evolution in order to produce increasingly ‘fit’ solutions to a problem.  In this analogy, we might think of each particular arrangement option as an individual animal in a population, with the input parameters used to generate it being equivalent to that animal’s genes.

Initially, a completely random set of these options will be generated and assessed for fitness.  Of this initial group, a certain percentage of the best options (i.e. those with the highest fitness scores) will be retained and the rest discarded, to be replaced by new options created by randomly combining the input par