Grasshopper VB Scripting 2
Grasshopper VB Scripting 2
Grasshopper VB Scripting 2
Introduction
This booklet was written for students of the Generative Techniques in Design
elective at the Department of Architecture, National University of Singapore. Most
of the students had no prior experience with programming, so I have attempted
to introduce Grasshopper VB Scripting in a way that is as simple and easy to
understand as possible. Note that this is a very broad introduction that
necessarily glosses over many of the details. This is just a primer.
This is version 2 of this document, and it may continue to evolve. To download
the latest version, please go to http://community.nus.edu.sg/ddm . I fact, in this
current version, there are still a number of sections labelled as [under
construction] – these will be updated soon.
The document is based on Rhino3d Version 4 and Grasshopper Version
0.5.0099.
Page 1
Grasshopper VB Scripting Primer, Version 2
Table of Contents
Page 2
Grasshopper VB Scripting Primer, Version 2
Page 3
Grasshopper VB Scripting Primer, Version 2
Page 4
Grasshopper VB Scripting Primer, Version 2
Page 5
Grasshopper VB Scripting Primer, Version 2
1.1 VB.NET
The Microsoft .NET Framework is a software framework for developing programs
and applications for the Microsoft Windows operating system. The framework
supports a number of different languages, including Visual Basic .NET and C#
.NET.
Visual Basic .NET is a full-blown object-oriented programming language. Visual
Basic is often referred to using just the initials, VB. The difference between VB
and C# is mostly stylistic - the only real difference today is programmer
preference. The basis of VB is an earlier programming language called BASIC
that was invented by Dartmouth College professors John Kemeny and Thomas
Kurtz. VB is easily the most widely used computer programming system in the
history of software.
VB is not the same as VB for Applications (VBA) or VB Script. VBA is both a
language and an integrated programming environment (IDE), which is embedded
into many applications. VB Script is a subset of VBA and is a more rudimentary
scripting language to allow users to write simple scripts.
Page 6
Grasshopper VB Scripting Primer, Version 2
different from writing VB.NET scripts in Grasshopper. (The reason that you
cannot use RhinoScript in Grasshopper is because RhinoScript can only operate
on objects that are actually inside the document, whereas Grasshopper only
draws its geometry into the viewports.)
To summarise:
1) Rhino is written in C++ and it exposes a C++ SDK which allows other (i.e.
McNeel ) people and companies to write plugins for Rhino.
2) Using this C++ SDK, someone at McNeel wrote a RhinoScript plugin,
which in turn allows people to write scripts for Rhino.
3) Using this C++ SDK, someone else at McNeel wrote a .NET Wrapper
plugin, which in turn allows people to write Plugins for Rhino using any
.NET language.
4) Using this .NET wrapper SDK, another person at McNeel (David Rutten)
wrote a plugin called Grasshopper.
5) Grasshopper allows people to create custom components by writing
scripts in either the VB.NET language or the C#.NET language.
For writing a VB script in Grasshopper you use a simple script editor built into
Grasshopper. This creates some confusion at first since the documentation on
the Internet for VB tends to start with an introduction to the Visual Studio Express
IDE.
Page 7
Grasshopper VB Scripting Primer, Version 2
If you wish to write a .NET script inside Grasshopper, all you have to do
(assuming you already have Grasshopper installed and running) is:
• Open the Logic panel
• Drag a VB Component onto the canvas
• Double click the VB Component
• Start typing in the white space under where is says ’’’ <your code>.
The areas in the script window that are greyed out cannot be edited. (Try it –
click in the greyed out area and try typing.) When you have finished entering your
code and you click OK, Grasshopper will compile your code and (assuming there
were no errors during compilation) run it.
If you are writing a VB application, you would use a piece of software for
programming called an Integrated Development Environment (IDE). For
example, for VB there is an IDE called Visual Studio Express that is free of
charge.
However, for writing a VB script in Grasshopper you do not use this IDE. (You
should only use the IDE if you intend to write your own components. This is much
more difficult.) Instead you use the simple built-in script editor in Grasshopper as
described above.
The text in this document is littered with code snippets that are inline with the
text. In order to distinguish code from normal text, the code uses a different
font.
The text is also littered with links. Most of these links point to web pages on the
Microsoft Software Developer Network website (MSDN) where you can get more
information on the topic being discussed.
The code samples in the text below are extracts from a longer piece of code.
Only those sections with the title ‘a complete example’ will run if you copy them
directly into a script.
Page 8
Grasshopper VB Scripting Primer, Version 2
With the other bits of code, it takes up too much space to keep repeating the full
set of code, so only the parts of the code being discussed in the text is shown.
But the careful reader should easily be able to fill in the missing bits since they
will have been discussed earlier on in that particular chapter.
Page 9
Grasshopper VB Scripting Primer, Version 2
2 Writing code
Programming in VB involves writing two types of things: comments and code.
Here is the same example with some comments and some code.
2.1 Comments
Comments are lines of text preceded by an apostrophe. These comments are
just for you to remind yourself (and maybe others) of what your code is doing.
Comments become essential when code gets complex.
The your code lines are just comments and can be deleted if you want:
The reason that there are three apostrophes rather than just one is because
there is also a more advanced way of adding comments, called XML
Documentation Comments. However for the moment don’t worry about this.
2.2 Code
Code is everything that is not a comment. Code consists of a series of
statements that tell the computer what to do.
In the example above, there is one statement: Print(“Hello”). This is an
execution statement that uses the Print function.
The print function is a very useful function that displays some text somewhere on
your screen. (It does not send anything to you printer – when writing computer
programs, print means ‘display this text’.) In the case of Grasshopper scripts, the
Page 10
Grasshopper VB Scripting Primer, Version 2
text from the print function will always be sent to the out parameter of the VB
component.
Code conventions focus on the stylistic aspects of naming and coding. For
example, should you start a variable with an upper or lower case letter? (The
answer is lowercase). For those new to programming, this type of thing may
seem unimportant. But as you do more programming, you realise that it is very
important for legibility of code. If you come back to some code a few months
later, it is much easier to understand if you have followed some kind of consistent
coding conventions. As far as possible, this document follows the standard code
conventions.
One particular point to note is the use of the line-continuation character, which is
an underscore (_). This is used when a long line of code needs to be broken
down into smaller lines. Due to the formatting of this document, this has been
used in a number of places to fit the code onto the page.
2.2.2 Statements
The three main types of statements that you can write are declaration
statements, assignment statements, and execution statements. (Assignment
statements are actually a special type of execution statement.)
Declaration and assignment statements are mainly to do with telling the
computer to create and set variables, where a variable is a name that can be
associated with some value.
Execution statements are mainly to do with telling the computer to actually do
something. An important type of execution statement are things like functions,
loops, and if statements, which are referred to as control flow statements.
Page 11
Grasshopper VB Scripting Primer, Version 2
Variables may be associated with simple types of things like numbers, and more
complex types of things like points and lines. These are referred to as Value
Types and Reference Types respectively.
• Chapter 3 will introduce Value Types
• Chapter 4 will introduce Class Types, which are the most common
Reference Types.
In the absence of any control flow statements, a computer will step through the
statements that it finds in the program file in a sequential manner, from beginning
to end, executing each statement in turn.
Control flow statements allow you to regulate the flow of your program's
execution. For example, you might want to repeat an action ten times. Rather
than repeating the code ten times you can insert a loop structure into your code
that will tell the computer to repeat a particular piece of code a certain number of
times.
• Chapter 6 will introduce Control Structures
In general, the two main types of control structures are decision structures and
loop structures. One of each will be introduced: for decisions, If...Then...Else
construction will be introduced; for loops the For… Next construction will be
introduced.
Once you have grasped how to work with variables and control flow structures
like loops, it will then be time to delve into the ugly world of class libraries. This is
where things get a little messier. The reason is that these class libraries tend to
be very big, and it becomes difficult to find your way round. In order to get you
started, some of the most important class libraries for Grasshopper VB Scripting
will be introduced.
Page 12
Grasshopper VB Scripting Primer, Version 2
Class libraries are groups of useful classes written by other people. In your code,
you use these classes to construct your program. We will find out in chapter 4
that these libraries of classes are actually organised into a hierarchy of groups
and sub-groups that you can think of like the folders but that are referred to as
Namespaces. In the case of Grasshopper VB Scripting, there are generally two
types:
• .NET class libraries written by people at Microsoft. These are all in a
namespace that starts with System.
• Rhino class libraries written by people at McNeel. These are all in a
namespace that starts with RMA.
First we will review some useful class in the .NET libraries:
• Chapter 7 will focus on the .NET System namespace, which includes the
Array class, the String class, and some other useful classes.
Page 13
Grasshopper VB Scripting Primer, Version 2
If you are new to programming, then the concept of the variable data type is
probably the hardest to grasp. Assigning a data type to a variable allows the
computer to various things like assign the right amount of space in memory
somewhere to store the values of the variable. It also makes it easier for the
computer to figure out how the variable can—or can't—be used.
Page 14
Grasshopper VB Scripting Primer, Version 2
3.1.1 Declaration
A declaration statement is used to declare the data type of the variable, using a
Dim statement. For example:
Dim p As Integer
This statement declares that the variable named p can store an Integer value.
Some of the most important value data types are the following:
Boolean True A value that is either true or false
Integer 20 Whole numbers less than 2 billion
Long 2e9 Whole numbers larger than two billion
Double 20.5 Numbers with a fractional part
Char A A single character
So when you see the word Double in a script, then this is not some function to
double some number, it is actually just a type.
3.1.2 Assignment
Once you have declared the type of variable, you can then assign a value to it.
For example:
p = 20
If you try and assign a value to the variable that does not match the data type,
then you will get an error.
In order to save space, you can put declaration and assignment on a single line.
However, it is still important to conceptually think of these as two separate steps.
Combined declaration and assignment looks like this:
Dim p As Integer = 20
From now on, the variable with name x stores the value 20. For example:
Print(p)
This Print function would print 20. Another more complex example is this one:
Page 15
Grasshopper VB Scripting Primer, Version 2
p = p + 10
Print(p)
This time, the value of the variable x would be increase by 10. The Print
function would print 30. This example uses two operators, and addition operator
and an assignment operator. There are many operators that can be used with
Value Types.
In this case, the function has one input and one output. The inputs are always
specified on the right of the function name in parenthesis. When the computer
tries to run a line of code like this, it evaluates the code one step at the time, from
right to left. So for example, someText = CStr(p) would become someText =
CStr(20) , which would then (after executing the actual function) become
someText = “20” , which would finally result in the text “20” being assigned to
the variable someText.
Dim p As Double
Dim q As Double
Dim r As Double
p = 20
q = p + 10
r = p / q
Print(“The value of r is ” & CStr(r))
Page 16
Grasshopper VB Scripting Primer, Version 2
When talking about classes and objects, you generally say the object A is of type
B (where B is a class), or alternatively A is an instance of class B.
4.1.1 Classes
When you are writing VB .NET scripts in Grasshopper, you will not be creating
any of your own classes. However, you need to have a good basic understanding
of classes and objects so that you can use the existing libraries in the .NET
framework and in Rhino. In fact, one of the hardest things in programming is
learning how to use these existing class libraries since there are thousands of
these classes.
Class libraries consist of large numbers of compiled classes that are packaged
up into files such as .exe files or .dll files. These packages are referred to as
Assemblies. Inside these assemblies, there may be hundreds of classes, so
there has to be a way of organising all these classes. Not surprisingly, they are
organised into a hierarchy of groups and sub-groups that you can think of like the
folders where you store files on your computer. These folders are referred to as
Namespaces. For example, On3dPoint and OnLine are both in the Assembly
xxx.dll and in the Namespace RMA.OpenNURBS (where RMA is one Namespace,
and OpenNURBS is a sub Namespace).
Note that the reason that the classes in these examples start with the letters ‘On’
is because they are part of the OpenNURBS library. Resist the temptation of
thinking that the class OnLine has something to do with being on a line. Think of
it as ‘Open NURBS line’.
4.1.2 Objects
Page 17
Grasshopper VB Scripting Primer, Version 2
The properties and methods that an object has are defined by its class.
The properties are like variables that are inside the object. For example, an
object of type On3dPoint has x, y and z properties that hold data for the co-
ordinates of the point. In this case these variables are simple types of type
Double.
Another example is an object of type OnLine. In this case it has two properties,
from and to, which are the start point and the end point of the line. However, in
this case these variables are themselves class types of type On3dPoint.
The methods are like procedures that are inside the object. Such procedures are
similar to the VB run-time member functions discussed earlier. For example,
objects of type On3dPoint have a Function Procedure method called
DistanceTo that calculates the distance to another point. Another example is
objects of type Online have a Function Procedure method called Length that
calculates the length of the line.
Methods are described below in more detail.
Often procedures need some data as an input. This input is described in terms of
parameters and arguments.
A parameter represents a value that the procedure expects you to supply when
you call it. The procedure's declaration defines its parameters. An argument
represents the value you supply to a procedure parameter when you call the
procedure. The calling code supplies the arguments when it calls the procedure.
The one thing that is a little complex to understand for beginners when dealing
with parameters and arguments is the passing mechanism. This actually
specifies how the arguments are passed to the procedure. There are two options:
they can be passed either by reference (specified by the ByRef keyword) or by
value (specified by the ByVal keyword). For the moment, we will ignore what this
means exactly and return to it later.
Page 18
Grasshopper VB Scripting Primer, Version 2
Function Procedure are the same as the previously described functions: they
have one or more parameters and a single return value.
For example, let’s consider the class On3dPoint, which is used for representing
a 3d point in Rhino. This class has a Function Method called DistanceTo that
returns the distance to another point. The implementation might look something
like this:
The input is one parameter called arg1, of type On3dPoint. The output is of type
Double (and for the output, there is no need to specify a name). Inside the
function, the Return statement returns the result of calculating the distance. Note
that, the actual body of the code is omitted here in order not to distract from the
main point here.
One common error is to expect there to be two points as input parameters. (After
all, the function is calculating the distance between two points...). However,
remember that one point is the object itself. This point object has a method to
calculate the distance to another point, so only one input point is required.
Sub Procedures are almost the same as Function Procedures, except that they
don’t return anything.
For example, let’s consider the same class On3dPoint. This class has a Sub
Procedure Method called Set that can be used to set the values of the x, y and z
properties. The implementation might look something like this:
The input consists of three parameters called x, y, and z, all of type Float, and
there is no output. Again, note that the body of the implementation has been
omitted here.
Page 19
Grasshopper VB Scripting Primer, Version 2
4.2.4 Constructors
A class must also specify one or more special Sub Procedure methods called
Constructors that are used to create an object instances. These Sub Procedures
are different from other Sub Procedures in that the Sub Procedure name is
always the word New, and they are only executed when the object is first created.
We will come back to these later.
However, when working with complex types, a variable only stores a reference to
an object, but does not store the object itself. (You may have noticed that with
objects, I wrote that the variable ‘points to’ the object.) You can think of the
reference as an address – the variable stores the address of the object. So if pt1
and pt2 are On3dPoint objects and you write pt2 = pt1, the computer will take
the object reference stored in pt1 and copy it into pt2.
4.3.1 Declaration
As with value types, the same Dim statement can be used to declare class types.
For example:
This statement declares that the variable named pt1 can point to an object of
type On3dPoint. This is actually the same as for value types.
4.3.2 Instantiation
For value types, there is not a separate instantiation step since value types hold
the data directly inside the variable name. However, for reference types, the data
is created somewhere else, and the variable only holds a reference to that data.
This means that the data first has to be created, which is called instantiation, and
is done using the class’s constructor method.
To instantiate a new object, you have to use the New keyword. When the
computer sees this keyword, it will then know to look for one of the constructor
methods to instantiate a new object from the class. For example, let’s say you
want to create a new point with coordinates (20,30,40):
Page 20
Grasshopper VB Scripting Primer, Version 2
In this case, the New keyword is used to indicate that you want to create a new
object using one of the constructor methods of the class On3dPoint.
Most classes have more than one constructor, each with a different set of
parameters. For example, in the case of the class On3dPoint, we can actually
create a point at (0,0,0) by calling the constructor with no arguments:
Although this is possible, it can create confusion, especially when you are just
starting to learn the language. It is therefore recommended that you always add
the empty parenthesis to highlight that you are calling a constructor with no
arguments.
4.3.3 Assignment
Assignment looks exactly the same as for value types but remember that in the
background something very different is going on.
For example, you could do the following:
pt2 = pt1
There is a subtle trap that new programmers will tend to fall into when dealing
with complex variables. Since the actual object is not copied, if you change a
property of pt1, then the property of pt2 will also change.
The Print function will print 22.5. This is because both pt1 and pt2 contain the
same reference and are pointing to the same point object. So when you ‘change’
pt1 you will also ‘change’ pt2. This is not the case with simple variable.
p = 20
q = p
p = 22.5
Print(q)
Page 21
Grasshopper VB Scripting Primer, Version 2
As with Value Types, with Reference Types you can put both declaration and
assignment on a single line. For example:
For Reference Types, you can also create a single line that includes three
separate steps: declaration, instantiation and assignment.
This code first declares a new variable of type Double and then sets the value of
this variable to the same as the x property of the point pt1 (which in this case is
20).
Page 22
Grasshopper VB Scripting Primer, Version 2
The dot operator is used in the same way to access the methods inside the
object. So for example, to measure the distance between two points you can use
the DistanceTo method which exists inside any object of type On3dPoint:
The dot operator can also be used to chain together a series of objects. For
example, consider a line object. The line object will contain (as properties) two
point objects, and each point object will contain (as properties) x, y, and z Double
values. In the example below the x co-ordinate of the start of the line is accessed
using ln.from.x:
Page 23
Grasshopper VB Scripting Primer, Version 2
Page 24
Grasshopper VB Scripting Primer, Version 2
At the top of the template, you will see a set of lines all starting with the word
Imports.
As mentioned previously, class libraries are packaged into Assemblies, and the
classes inside these Assemblies are organised into hierarchical Namespaces. In
order to use a particular class in some Assembly, you first need to set up your
development environment so that the compiler knows about that Assembly. You
can then use any class in the Assembly as long as you state the Namespaces in-
front of the class name. This is referred to as qualification. For example, to
declare a new point, you can write:
In theory this works fine. In practice, it is a real pain to have to write so much text.
The Imports statement tells the computer where to look for classes that have no
Namespace. This means that the classes in the imported Namespaces can be
named in the code without qualification. So, for example:
Page 25
Grasshopper VB Scripting Primer, Version 2
Imports RMA.OpenNURBS
‘ Skip over some code here
‘ ...
‘ ...
Dim pt1 As On3dPoint
Page 26
Grasshopper VB Scripting Primer, Version 2
After the Imports statements, the next line in the template is the Class
declaration. This declaration simply tells the computer that there is a class called
Grasshopper_Custom_Script.
After the class declaration, the next section of code is enclosed between two
lines: #Region "members" and #End Region. This is a Region Directive which
actually has nothing to do with the script. It is purely a visual thing, in that it
allows bits of the code to be hidden and shown using the + and – links.
5.1.4 Properties
Inside the region called members, a set of class properties are declared. By
default, there are three properties:
Page 27
Grasshopper VB Scripting Primer, Version 2
always be of type System.Object, which in turn means that the property called A
in the template can be set to anything.
After the properties declared within the members region, the next lines of code
declare the main Sub Procedure inside which you can write your script, called
RunScript. By default, the Sub Procedure declaration in the template is as
follows:
The main thing to note about this Sub Procedure is the relationship between the
parameters in the Sub Procedure declaration, and the inputs to the VB Script
component in Grasshopper. Although this Sub Procedure declaration is not
editable here in the script editor, we will see below how the parameters can be
edited using the Grasshopper interface.
After the end of the RunScript Sub Procedure, there is a second region with the
description Additional methods and Type declarations. Apart from the
area inside the RunScript Sub Procedure, this is the only other area of the
template that is editable.
This second region is where you can write your own additional Sub Procedures
and Function Procedures. In most cases, it only really makes sense to create
Function Procedures, and not Sub Procedures. More advanced users may also
create type your own user-defined data types here.
Function procedures can be used to capture some code that gets repeated
numerous times in your script. For example, you might be writing a script that
requires various random points of type On3dPoint. In this case, you could write
two functions: one that returns a random number (where the value is between
some lowerbound and upperbound) and another that returns a random point
(where the x, y and z co-ordinates are between some lowerbound and
upperbound ).
Page 28
Grasshopper VB Scripting Primer, Version 2
(Note the use of the line continuation character. The code is too wide for the
page, so the first line of both functions has been broken into two lines.)
The input parameters specify the inputs into the component. By default, there are
two parameters, x and y. Looking at the image below, you will notice that there is
a relationship between these two inputs and the two arguments to the RunScript
Sub Procedure.
Page 29
Grasshopper VB Scripting Primer, Version 2
the drop down menu. Any changes that you make here will be reflected in the
RunScript method declaration. For example, if you rename the two input
parameters from x and y to pt1 and pt2, then the methods declaration will be
automatically updated to the following:
Sub RunScript(ByVal pt1 As Object, ByVal pt2 As Object)
''' <your code>
If you are certain that a specific input parameter always provides data of the
same type (say, On3dPoint), then you can specify a type-hint for that parameter.
Type-hints improve error checking and performance. To specify a type hint, right
click the component, select the input you want to change from the first drop down
menu, then select Type hint from the second drop down menu, and finally select
the type from the third drop down menu. Any changes that you make will be
reflected in the RunScript method declaration. For example, if you change the
types for pt1 and pt2 to On3dPoint, then the methods declaration will be
automatically updated to the following:
Sub RunScript(ByVal pt1 As On3dPoint, ByVal pt2 As On3dPoint)
''' <your code>
If the data coming into a certain input is going to consist of more than one
element, then you can specify that the parameter is a List. To specify a List,
right click the component, select the input that you want to change from the first
drop down menu, and then select List from the second drop down menu. For
example, if you change pt1 to be a List, then the methods declaration will be
automatically updated to the following:
Sub RunScript(ByVal pt1 As List(Of On3dPoint), _
ByVal pt2 As On3dPoint)
''' <your code>
(Note the use of the line continuation character. The code is too wide for the
page, so the first line has been broken into two lines.)
Output parameters can be added, deleted and renamed in the same way as input
parameters, through the VB Component menu. Any changes that you make will
be reflected in the declaration of the class properties. For example, if you rename
Page 30
Grasshopper VB Scripting Primer, Version 2
the output parameter from A to line, then property declarations will be updated
to the following:
#Region "members"
Private app As MRhinoApp
Private doc As MRhinoDoc
[under construction]
5.3.2 Debugging
[under construction]
5.3.3 Exporting
[under construction]
Page 31
Grasshopper VB Scripting Primer, Version 2
6 Control Flow
[under construction]
6.2 If...Then...Else
[under construction]
Page 32
Grasshopper VB Scripting Primer, Version 2
ReDim intArray2(8)
Page 33
Grasshopper VB Scripting Primer, Version 2
Page 34
Grasshopper VB Scripting Primer, Version 2
the array. However, with collections such as lists, you can add and remove
elements without worrying about the size of the collection. The size of the
collection will be changed automatically to match the number of elements in the
collection.
The methods to add elements to the List are Add, AddRange and Insert, while
the methods to remove elements from the List are Remove and RemoveAll. To
retrieve an element from a list, an index can be specified in parenthesis after the
variable name in the same way as with arrays. In addition to these basic
methods, there are also various other methods to do things like reverse the list,
sort the list, and concert the list to an array.
Another key difference is that arrays can be multidimensional, while lists can only
be one dimensional. However, this difference is a little less dramatic that it first
seems since you can simulate a multidimensional array by creating lists of lists.
This will be discussed in more detail later.
Declaration and assignment of Generic Classes differs slightly from other classes
due to the fact that you have to include the type parameter. For example, the
declaration of a variable of type List containing elements of type On3dPoint
would be as follows:
Dim ptList As List(Of On3dPoint)
The Of Integer part is the type parameter. It is this that tells the generic List
class that the elements in the list will all be of type Integer. So far, the list1
variable has only been declared, but does not exist yet since instantiation and
assignment have not yet been done. This is done as follows:
Now a new object of type List is actually created and assigned to the variable
ptList. Since the New keyword is used, we know that the constructor of the
List class is being called to instantiate the new object. However, instead of one
set of parenthesis, we now have two sets of parenthesis: in the first set of
parenthesis we pass in the type parameter, while in the second set of
parenthesis, we pass in the arguments to the constructor.
In the example above, there are no arguments for the constructor, so the second
sets of parentheses are empty. As described previously in chapter 4, in such a
case, you can actually omit the empty parentheses as follows:
Although this is possible, it can create confusion, especially when using Generic
Classes, since the type parameter then starts to look like an argument to the
Page 35
Grasshopper VB Scripting Primer, Version 2
The List class has many useful methods for manipulating lists. Probably the
most useful is the ability to add elements using the Add() method:
When using the Add() method, there is no need to worry about if the list has
enough space for these new elements (as is the case with arrays). the list will
automatically be resized.
Some other useful methods are Remove() which removes elements from the list,
Count() which returns the number of elements in the list, and Reverse() which
reverses the direction of the list.
ptList.Remove(3)
Dim ptListLength As Integer = ptList.Count()
ptList.Reverse()
When working with collections, you often find that you have to convert from one
data-structure to another. With lists, one common scenario is converting from an
Array to a List, and from a List to an Array. For these conversions to work,
the arrays must always be one-dimensional.
To convert a 1d array into a list, there are two approaches. You can either 1) add
the array to the end of an existing list using the AddRange() method of the List
class, or 2) create a new instance of the List class and pass in the array as an
argument to the constructor.
First let’s create an array to work with as an example:
And here is the second option, where the array is added to the end of an existing
list. In this case, the existing list is actually empty.
ptList.AddRange(ptArray)
Here is an example of creating a new instance of the List class and passing in
the array as an argument to the constructor:
Page 36
Grasshopper VB Scripting Primer, Version 2
You can then do things like insert new elements into the middle of the list. This
would not be very easy to do with arrays. For example:
To convert a list back into a 1d array, you simply call the ToArray() method.
This will return an array containing the same elements as in a list.
ptArray = ptList.ToArray()
There are also some collections that differ more significantly from the List class.
For example, there are some collections that contain pairs of elements referred
to as key / value pairs. The key is similar to the Integer index used with Lists and
Page 37
Grasshopper VB Scripting Primer, Version 2
Arrays, except that a key can be of any type. Two of these key / value collection
classes are:
• Dictionary: a collection of key / value pairs, where values can be retrieved
using a key. The methods to add key / value pairs to the SortedList are
Add. The methods to remove key / value pairs from the SortedList are
Remove and RemoveAt.
• SortedList: a collection that is similar to a Dictionary, but where key / value
pairs are automatically sorted as key / value pairs are added and
removed. The methods to add and remove key / value pairs are the same
as the Dictionary class.
Page 38
Grasshopper VB Scripting Primer, Version 2
9.1 Documentation
For the Rhino libraries, there is no equivalent website to the MSDN website.
However, you can download the Rhino 4.0 .NET Framework SDK, and inside the
zip file, you will find a file called RhinoDotNETDocs.chm that is a windows help
file that contains the documentation for RMA classes.
If you use Windows Vista and cannot see the contents of the help file when you
try to use it, then you need to unblock the content. To do this, go to Windows
Explorer, then right-click on the Rhino.NETDocs.chm file and go to Properties.
On the bottom of the General tab, click on the Unblock button.
Page 39
Grasshopper VB Scripting Primer, Version 2
The first thing that you will notice when you click on the OpenNURBS
Namespace is that it contains two set of things: Classes and Interfaces.
So far, Interfaces have not been mentions. For the most part, you can ignore
interfaces, and certainly in this help file, you only need to look at the
documentation under classes. However, interfaces will pop up every now and
then, so it is worth briefly explaining what they are.
[under construction]
Once you have found the class you are interested in, clicking the + to the left of
the class name will expand that section and show the different sub-sections for
the class.
For example, if we expand the On3dPoint class, we will see one file and four
sub-sections:
• On3dPoint Members lists all the members of the class in a compact form,
consisting in this case of the Methods, Operators, and Properties. Note
that the constructors are not listed here.
• On3dPoint Constructors lists the various constructors for the class, which
are used together with the New keyword to create new instances of this
class. In this case there are five different constructors. The last one, where
a new point is instantiated using three Double values, is the most
commonly used.
• On3dPoint Methods lists all the methods for this class. For some methods
there is just a single entry. For example, the DistanceTo Method
calculates the distance to another point. For other methods, there is a sub-
section that lists more than version of the method. For example, have a
look at the Rotate Method with rotates a point in 3d space. In this case
there are actually two methods with the same name, but with different
parameters. (This is referred to as overloading the method.)
• On3dPoint Operators lists all the operators for this class. These are
operators such as +, -, *, etc that can be used with objects of this class.
(Many classes do not have any operators since it often makes no sense.
Page 40
Grasshopper VB Scripting Primer, Version 2
9.2.1 Points
This class should already be quite familiar, since most of the examples up to now
have used On3dPoint classes and object. Here are some points that we can use
in our examples below:
‘Some points
Dim pt1 As New On3dPoint(0, 0, 0)
Dim pt2 As New On3dPoint(20, 0, 0)
Dim pt3 As New On3dPoint(30, 30, 0)
Dim pt4 As New On3dPoint(50, 50, 50)
Note that the 3d is short for 3 Double values rather than 3-dimensional. You will
notice that there are also various other types of points, such as 2d, 2f, 3d, 3f, 4d,
4f. The number indicates the number of properties (and is equivalent to the
number of dimensions), and the letter indicates the type, Double or Float. When
you are working with three-dimensional points, you would usually use
On3dPoint.
Page 41
Grasshopper VB Scripting Primer, Version 2
9.2.2 Vectors
9.2.3 Planes
9.3 Curves
There are many different kinds of curves classes. The basic classes for creating
things like lines and circles etc include the following:
• OnLine
• OnCircle
• OnArc
• OnEllipse
• OnPolyLine
There is another set of classes that are all parameterised curves. These are
curves that are defined in a specific way so that they have a direction (with a
curve start point and a curve end point), domain (for example 0 to 1), and a t
parameter (that can be used a position along the curve). For example, if the
domain of the curve is from 0 to 1, then the position on the curve at t = 0 will be
the start point, t = 0.5 will be half way along the curve, and t = 1 will be the
end point. You can also get other information like a tangent or curvature for a
given t parameter
These parameterised curves all inherit some of the behaviour from an abstract
class called OnCurve. Since this is an abstract class, you cannot instantiate
objects based on this class. You can only instantiate objects based on one of the
classes that inherit from the OnCurve class. These classes are as follows:
• OnLineCurve
• OnArcCurve
• OnNurbsCurve
• OnPolylineCurve
• OnPolyCurve
Page 42
Grasshopper VB Scripting Primer, Version 2
Finally, for Bezier curves and Polynomial curves, there are specific classes:
• OnBezierCurve
• OnPolynomialCurve
9.3.2 Curves
For creating NURBS curves with control points, you can use the OnNurbsCurve
class. The method of defining the geometry is a bit different from the previous
examples. In general, you first create the class using the constructor with no
parameters, and then in a second step you create the geometry by calling one of
the CreateXXX methods. In addition, when you call one of these methods, you
need to pass in an array of points, so you will first need to create this array.
Page 43
Grasshopper VB Scripting Primer, Version 2
9.3.3 Polys
9.4 Surfaces
[under construction]
9.5 Meshes
[under construction]
9.6 Solids
[under construction]
Page 44
Grasshopper VB Scripting Primer, Version 2
Page 45
Grasshopper VB Scripting Primer, Version 2
Acknowledgments
Parts of this document have been extracted from posts by David Rutten (McNeel)
to the Grasshopper user group.
Page 46