grasshopper vb scripting 2

46
Grasshopper VB Scripting Primer, Version 2 Grasshopper VB Scripting Primer Dr Patrick Janssen [email protected] 23 rd March 2009 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

Upload: dparty28

Post on 08-Apr-2015

713 views

Category:

Documents


17 download

TRANSCRIPT

Page 1: Grasshopper VB Scripting 2

Grasshopper VB Scripting Primer, Version 2

Grasshopper VB Scripting Primer Dr Patrick Janssen

[email protected]

23rd March 2009

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

Page 2: Grasshopper VB Scripting 2

Grasshopper VB Scripting Primer, Version 2

Table of Contents

1  What’s it all about ..........................................................................................6 

1.1  VB.NET....................................................................................................6 

1.2  Grasshopper Scripting .............................................................................6 

1.2.1  Where do I write my script?...............................................................7 

1.2.2  What about Visual Studio Express? ..................................................8 

1.2.3  About the code samples....................................................................8 

2  Writing code.................................................................................................10 

2.1  Comments .............................................................................................10 

2.2  Code ......................................................................................................10 

2.2.1  Coding conventions.........................................................................11 

2.2.2  Statements ......................................................................................11 

2.3  What next...............................................................................................11 

2.3.1  Variables and Types........................................................................12 

2.3.2  The VB Component.........................................................................12 

2.3.3  Control Flow ....................................................................................12 

2.3.4  Class Libraries ................................................................................12 

3  Working with Value Types ...........................................................................14 

3.1  Some common Value Types.................... Error! Bookmark not defined. 

3.2  Variables and Value Types ....................................................................14 

3.2.1  Declaration ......................................................................................15 

3.2.2  Assignment .....................................................................................15 

3.2.3  Combined declaration and assignment ...........................................15 

3.2.4  Variable use ....................................................................................15 

3.3  Some Useful Functions..........................................................................16 

3.4  A complete example ..............................................................................16 

4  Working with Class Types............................................................................17 

4.1  Classes and Objects..............................................................................17 

4.1.1  Classes ...........................................................................................17 

Page 2

Page 3: Grasshopper VB Scripting 2

Grasshopper VB Scripting Primer, Version 2

4.1.2  Objects ............................................................................................17 

4.1.3  Properties and Methods ..................................................................18 

4.2  Methods in More Detail ..........................................................................18 

4.2.1  Parameters and Arguments ............................................................18 

4.2.2  Function Procedures .......................................................................19 

4.2.3  Sub Procedures ..............................................................................19 

4.2.4  Constructors....................................................................................20 

4.3  Variables and Class Types ....................................................................20 

4.3.1  Declaration ......................................................................................20 

4.3.2  Instantiation.....................................................................................20 

4.3.3  Assignment .....................................................................................21 

4.3.4  Combined declaration, instantiation and assignment ......................22 

4.3.5  Parameters and arguments revisited...............................................22 

4.3.6  Variable Use....................................................................................22 

4.3.7  The dot operator..............................................................................22 

4.4  A complete example ..............................................................................23 

5  The VB Script Component ...........................................................................24 

5.1  The Grasshopper_Custom_Script class ................................................24 

5.1.1  Imports Statements .........................................................................25 

5.1.2  Class declaration.............................................................................27 

5.1.3  The first region ................................................................................27 

5.1.4  Properties........................................................................................27 

5.1.5  Sub Procedures ..............................................................................28 

5.1.6  The second region ..........................................................................28 

5.2  VB Component Inputs and Outputs .......................................................29 

5.2.1  Inputs parameters ...........................................................................29 

5.2.2  Outputs parameters.........................................................................30 

5.3  Creating your own components .............................................................31 

5.3.1  Design issues..................................................................................31 

5.3.2  Debugging.......................................................................................31 

Page 3

Page 4: Grasshopper VB Scripting 2

Grasshopper VB Scripting Primer, Version 2

5.3.3  Exporting .........................................................................................31 

6  Control Flow.................................................................................................32 

6.1  For… Next .............................................................................................32 

6.2  If...Then...Else........................................................................................32 

7  The .NET System Namespace ....................................................................33 

7.1  Array Class ............................................................................................33 

7.1.1  Declaration ......................................................................................33 

7.1.2  Assignment ....................................... Error! Bookmark not defined. 

7.1.3  Combined declaration, instantiation, and assignment .....................33 

7.2  String Class ...........................................................................................33 

7.3  Math Class.............................................................................................33 

7.4  Random Class .......................................................................................33 

7.5  A complete example ..............................................................................33 

8  The .NET System.Collections.Generic Namespace ....................................34 

8.1  Generic Types and Classes...................................................................34 

8.2  The List Class ........................................................................................34 

8.2.1  Declaration, Instantiation and Assignment ......................................35 

8.2.2  Some useful methods......................................................................36 

8.2.3  Lists and Arrays ..............................................................................36 

8.3  Other generic collection classes ............................................................37 

8.3.1  Collections similar to lists ................................................................37 

8.3.2  Other types of collections ................................................................37 

8.4  A complete example ..............................................................................38 

9  The Rhino RMA.OpenNURBS Namespace.................................................39 

9.1  Documentation.......................................................................................39 

9.1.1  Classes and Interfaces....................................................................40 

9.1.2  Looking at a class............................................................................40 

9.2  Points, Vectors and Planes....................................................................41 

9.2.1  Points ..............................................................................................41 

9.2.2  Vectors ............................................................................................42 

Page 4

Page 5: Grasshopper VB Scripting 2

Grasshopper VB Scripting Primer, Version 2

9.2.3  Planes .............................................................................................42 

9.3  Curves ...................................................................................................42 

9.3.1  Lines, Circles and Arcs....................................................................43 

9.3.2  Curves.............................................................................................43 

9.3.3  Polys ...............................................................................................44 

9.3.4  Translating, Rotating and Scaling ...................................................44 

9.4  Surfaces.................................................................................................44 

9.5  Meshes ..................................................................................................44 

9.6  Solids .....................................................................................................44 

10  The Rhino RMA.Rhino Namespace ..........................................................45 

Page 5

Page 6: Grasshopper VB Scripting 2

Grasshopper VB Scripting Primer, Version 2

1 What’s it all about Rhino3d is a popular 3d NURBS based modelling program developed by McNeel.

Grasshopper is a free plugin for Rhino3d developed by David Rutten at McNeel, which allows you to do dataflow modelling. With the Grasshopper approach to dataflow modelling, you can create complex parametric models by defining relationships between entities in your model. These relationships are defined using the 'boxes and arrows' approach. The boxes – called components – specify procedures that do something like draw a line. The arrows connect the output from one procedure to the input of another procedure.

Grasshopper provides a two components that allow you to create your own custom procedures using scripting. These are the C# Component and the VB Component. In this document, we will be focusing on the VB Component, for which the user has to write a script in the VB.NET programming language.

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.

1.2 Grasshopper Scripting

Scripting in Grasshopper should not be confused with the other scripting options available in Rhino3d.

For a long time it has been possible to automate Rhino3d using the RhinoScript scripting language. RhinoScript is written by McNeel and it is based on the Microsoft VBScript language. Since Rhino3, it has also been possible to use VB.NET to write plugins for Rhino. Grasshopper for example is mostly written in VB.NET. However, Rhinoscript and VB.NET plugin development are very

Page 6

Page 7: Grasshopper VB Scripting 2

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.

1.2.1 Where do I write my script?

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

Page 8: Grasshopper VB Scripting 2

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.

1.2.2 What about Visual Studio Express?

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.

1.3 About this document

This document consists of lots of text, quite a bit of code, and a few screen captures. All screen captures were created by the author.

1.3.1 About the text

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.

1.3.2 About the code

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

Page 9: Grasshopper VB Scripting 2

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

Page 10: Grasshopper VB Scripting 2

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:

''' <your code> ''' </your code>

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

Page 11: Grasshopper VB Scripting 2

Grasshopper VB Scripting Primer, Version 2

text from the print function will always be sent to the out parameter of the VB component.

2.2.1 Coding conventions

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.

2.3 What next...

The remainder of this document will try to introduce the most important knowledge for getting started with actually writing useful scripts in Grasshopper.

Page 11

Page 12: Grasshopper VB Scripting 2

Grasshopper VB Scripting Primer, Version 2

2.3.1 Variables and Types

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.

2.3.2 The VB Component

The VB Component in Grasshopper allows users to enter code directly into a predefined script template that consists of a special class. After having covered the fundamentals of classes in chapter 4, it then becomes possible to get an understanding of how this template works.

• Chapter 5 will give an overview the VB Script Component, focusing in particular on the script template.

2.3.3 Control Flow

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.

2.3.4 Class Libraries

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

Page 13: Grasshopper VB Scripting 2

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.

• Chapter 8 will focus on the .NET System.Collections.Generic namespace, which includes the List class (which is the main data-structure used by Grasshopper).

Finally, we will review some useful class in the Rhino libraries:

• Chapter 9 will focus on the Rhino RMA.OpenNURBS namespace, which includes classes for all the standard entities found in Rhino such as points, curves and surfaces.

• Chapter 10 will focus on Rhino RMA.Rhino namespace, which includes one very useful class called RhUtil that has many useful methods for scripting Rhino modelling commands like lofting and intersecting.

Page 13

Page 14: Grasshopper VB Scripting 2

Grasshopper VB Scripting Primer, Version 2

3 Working with Value Types Variables are one of the core building blocks of any kind of programming. A variable is something that can be associated with some kind of value. For example, you can say that variable p should be associated with the value 20. A variable has three important attributes: a name, a value, and a data type.

• A variable is identified by its name – in this case the variable name is p. The name of a variable can be almost anything, like x, or myVar, or blabla. (It cannot be the same as one of the language keywords, which are reserved for other purposes.) By convention, variables use what is referred to as mixedCase: they start with a lowercase letter and each subsequent word starts with an uppercase letter.

• A variable has a value – in this case the variable value is 20. The value of the variable can be accessed by simply entering the variable name anywhere in your code. For example, wherever you write p, the computer will replace this with 20 when it actually runs the program. (This assumes that the value of x does not change, but your program may later change this value to something else, for example to 21.)

• A variable has a data type that specifies what types of values the variable is allowed to hold. In this case, we know that they type is a number, but there are actually various different type of numbers in programming. So we are not actually sure yet what the data type of p is. If we wanted to have a variable to hold round numbers (with no fractional part, i.e. not numbers like 20.5), then we would say that the data type of variable p is Integer.

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.

3.1 Variables and Value Type

If I want to use a variable in my script, then I always have to specify it’s name, it’s data type, and it’s value. This is done in two separate steps:

• Specifying the name and data type are done in one single step, and is called declaration.

• Specifying the value is done as a second step, and is called assignment.

(You will see later that you can combine declaration and assignment into a single line.)

Page 14

Page 15: Grasshopper VB Scripting 2

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.

p = 20.5 ‘this would result in a error

3.1.3 Combined declaration and assignment

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

3.1.4 Variable use

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

Page 16: Grasshopper VB Scripting 2

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.

3.2 Some Useful Functions

The Print function is one of the built in VB run-time member functions. There are many other useful VB functions.

A function has one or more inputs and a single output. The function will process the inputs and produce the output.

For example, there are a useful set of functions to convert one simple data type into another, known as type conversion functions. One of the functions is called CStr and converts things like Integer or Double to String.

Dim someText As String someText = CStr(p)

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.

3.3 A complete example

Here is a complete example that creates some Double values and converts one of them to a String to be printed:

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))

This script will print:

The value of r is 0.666666666666667

Page 16

Page 17: Grasshopper VB Scripting 2

Grasshopper VB Scripting Primer, Version 2

4 Working with Class Types As well as these simple data types, variable can also be associated with more complex types of entities called objects. For example, one common type of object in Grasshopper is an object of type On3dPoint, which is used for representing 3d points in Rhino. Another is OnLine, which is used for representing Lines in Rhino.

4.1 Classes and Objects

A class is a representation of a type of object. You can think of it as the object's blueprint. Just as a single blueprint can be used to build multiple buildings, a single class can be used to create multiple copies of an object. The names On3dPoint and OnLine are actually names of classes.

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

Objects are always instances of some type of class. Objects have

• properties that describe their attributes, and

• methods that define their actions.

Page 17

Page 18: Grasshopper VB Scripting 2

Grasshopper VB Scripting Primer, Version 2

The properties and methods that an object has are defined by its class.

4.1.3 Properties and Methods

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.

4.2 Methods in More Detail

There are two types of procedures: Function Procedures and Sub Procedures. Both of these types of procedures can accept input data, which is specified by the parameters for the procedure. Only Function Procedures can produce output data, which is specified as the return value of the Function Procedure.

4.2.1 Parameters and Arguments

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

Page 19: Grasshopper VB Scripting 2

Grasshopper VB Scripting Primer, Version 2

4.2.2 Function Procedures

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:

Function DistanceTo(ByRef arg1 As On3dPoint) As Double Dim dist As Double ‘ insert code that calculates the distance ‘ ... ‘ ... Return dist End Function

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.

4.2.3 Sub Procedures

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:

Sub Set(ByVal x As Float, ByVal y As Float, ByVal z As Float) ‘ insert code that sets properties here ‘ ... ‘ ... End Sub

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

Page 20: Grasshopper VB Scripting 2

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.

4.3 Variables and Class Types

Declaration and assignment of variables for class types would seem to be very similar to value types. However, there are actually some very fundamental differences, particularly when it comes to assignment.

When working with value types a variable will store the actual value. So if a and b are Doubles and you write b = a, then the computer will take the value stored in a and copy it into b.

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:

Dim pt1 As On3dPoint Dim pt2 As On3dPoint

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

Page 21: Grasshopper VB Scripting 2

Grasshopper VB Scripting Primer, Version 2

pt1 = New On3dPoint(20,30,40)

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:

pt1 = New On3dPoint()

In cases where there are no arguments (i.e. empty parentheses), VB supports a shortcut whereby you can omit the empty parentheses, as follows:

pt1 = New On3dPoint ‘do not do this

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.

pt1 = New On3dPoint(20,30,40) pt2 = pt1 pt1.x = 22.5 Print(pt2.x)

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)

The Print function will print 20.

Page 21

Page 22: Grasshopper VB Scripting 2

Grasshopper VB Scripting Primer, Version 2

4.3.4 Combined declaration, instantiation and assignment

As with Value Types, with Reference Types you can put both declaration and assignment on a single line. For example:

Dim pt2 As On3dPoint = pt1

For Reference Types, you can also create a single line that includes three separate steps: declaration, instantiation and assignment.

Dim pt2 As New On3dPoint(20,30,40)

4.3.5 Parameters and arguments revisited

[under construction – discuss ByRef and byVal]

4.3.6 Variable Use

A variable whose value is an object can be assigned in a similar way as a simple variable. (For example see pt2 = pt1 above.)

However, for other operators such as addition, this may not be so straight forward. In fact, this depends on the way the class has been implemented. Some classes provide special functionality so that instances of these classes can be used together with the standard operators.

For example, the On3dPoint class can be used with arithmetic operators such as addition, subtraction and division. For example, the mid-point half way between two other points can be found as follows:

Dim midPt As On3dPoint midPt = p1 + (pt2 – pt1 / 2.0)

4.3.7 The dot operator

With objects, it is possible to access the properties and methods inside these objects using a full stop between the name of the variable and the name of the property or method. This full stop is called the dot operator.

For example, the x property of a On3dPoint can be accessed like this:

Dim val As Double val = pt1.x

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

Page 23: Grasshopper VB Scripting 2

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:

Dim dist As Double dist = pt1.DistanceTo(pt2)

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:

pt1 = New On3dPoint(0,0,0) pt2 = New On3dPoint(20,30,40) Dim ln As OnLine ln = New OnLine(pt1, pt2) ln.from.x = 50

4.4 A complete example

Here is a complete example that creates a line between two points:

‘declare two points called pt1 and pt2 Dim pt1 As On3dPoint Dim pt2 As On3dPoint ‘assign pt1 by creating a new point pt1 = New On3dPoint(20, 30, 40) ‘assign pt2 by creating a copy of pt1 pt2 = New On3dPoint(pt1) ‘move pt2 by changing one of the co-ordinates pt2.x = 0 ‘declare a line called ln Dim ln As OnLine ‘assign ln by creating a new line ln = New OnLine(pt1, pt2)

Page 23

Page 24: Grasshopper VB Scripting 2

Grasshopper VB Scripting Primer, Version 2

5 The VB Script Component As described previously, the VB Component can be found in the Logic panel. The Help for this component states the following:

This component attempts to compile and run user specified VB.NET code. By default, the component contains no code. You can supply code by double-clicking the component or by picking the "Edit…" menu item.

Any errors that occur during compilation are sent to the 'out' output parameter and the component menu.

By default, there are two input parameters {x,y} and one output parameter {A}, all of which are of type System.Object. Input and output parameters can be added, deleted and renamed through the component menu.

In addition to this, there are also some other remarks at the bottom of the help text, some of which will be discussed below.

5.1 The Grasshopper_Custom_Script class

When a user enters code into the VB component, the code is placed inside a class template called Grasshopper_Custom_Script. When the user clicks OK on the script editor, the code is then compiled by Grasshopper and stored in memory. In this section this class template will be described. To see the full template, expand the hidden sections by clicking the + links.

The Grasshopper_Custom_Script is a typical VB class and consists of some Imports statements, some Properties, and one Sub Procedure. You also have the option of adding additional Sub Procedures or Function Procedures to the class.

Page 24

Page 25: Grasshopper VB Scripting 2

Grasshopper VB Scripting Primer, Version 2

5.1.1 Imports Statements

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:

Dim pt1 As RMA.OpenNURBS.On3dPoint

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

Page 26: Grasshopper VB Scripting 2

Grasshopper VB Scripting Primer, Version 2

Imports RMA.OpenNURBS ‘ Skip over some code here ‘ ... ‘ ... Dim pt1 As On3dPoint

Currently, there is no way of adding additional Assemblies and Imports statements to your script in the VB scripting component. However, by default, many of the most useful Namespaces from both the .NET libraries and from the Rhino libraries are already imported.

The .NET Namespaces that are imported are:

• System (see chapter 7)

• System.IO

• System.Drawing

• System.Drawing.Drawing2D

• System.Reflection

• System.Collections

• System.Collections.Generic (see chapter 8)

• Microsoft.VisualBasic

The MSDN website has a Class Library Reference that lists all the classes that are available in these Namespaces. (Grasshopper is compiled using VB 2008 Professional and the .NET 2.0). For each class, the class members are listed (such as class properties, class methods, and class constructors). The documentation is quite good.

The Rhino Namespaces that are imported are:

• RMA.OpenNURBS (see chapter 9)

• RMA.Rhino (see chapter 10)

• Grasshopper.Kernel.Types

For more information on some of these libraries, see chapters 7 to 10 of this document.

As a beginner, the best way to approach these class libraries is through examples. On the Grasshopper website, there is a page with scripted examples where you can see how various classes are used. You can then look up these classes in the documentation, and try and figure out why the classes are being used the way they are. The opposite approach, where you start with the class libraries, is very difficult due to the complexity of the classes and is only really feasible if you are an experienced programmer.

Page 26

Page 27: Grasshopper VB Scripting 2

Grasshopper VB Scripting Primer, Version 2

5.1.2 Class declaration

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.

5.1.3 The first region

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:

Private app As MRhinoApp Private doc As MRhinoDoc Public A As System.Object

As discussed previously, properties are simply variables that exist inside a particular object. So, for example On3dPoint has the properties x, y and z. In this case, the template has defined three properties:

• app gives you access to the Rhino application. For example, your script might want to check which viewports are visible.

• doc gives you access to the Rhino file that is currently open. For example, your script might want to read geometry directly from this file.

• A is linked to the output of the VB Script component. Inside your script, whatever you set A to will be the output of the A parameter.

The last one is the most important one since this is what lets you send some data out of your component. There is one issue that needs to be addressed regarding the type of this property. The template sets the type of System.Object, and later we will see that this type cannot be changed. At first this may seem odd, because what if you want to output a different type of object such as a On3dPoint, or even just a simple Integer. The reason this is not a problem is due to something called class inheritance. Up to now, the issue of class inheritance has been side-stepped, mainly because it is a little complex.

For now, the only thing that really needs to be understood is that classes are actually used to define a whole hierarchy of categories and sub-categories. Classes in the same category share certain types of information. Right at the top of the hierarchy is the class System.Object. This means that all classes must

Page 27

Page 28: Grasshopper VB Scripting 2

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.

5.1.5 Sub Procedures

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:

Sub RunScript(ByVal x As Object, ByVal y As Object) ''' <your code> ''' </your code> End Sub

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.

5.1.6 The second region

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 ).

‘Function that returns a random number of type Double Function rndNum(ByVal low As Double, ByVal upp As Double) _ As Double Return ((upp - low) * Rnd()) + low End Function

Page 28

Page 29: Grasshopper VB Scripting 2

Grasshopper VB Scripting Primer, Version 2

‘Function that returns a random point of type On3dPoint Function rndPt(ByVal low As Double, ByVal upp As Double) _ As On3dPoint Dim x As Integer = rndNum(low, upp) Dim y As Integer = rndNum(low, upp) Dim z As Integer = rndNum(low, upp) Dim pt As New On3dpoint(x, y, z) return pt End Function

(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.)

5.2 VB Component Inputs and Outputs

As will all components in Grasshopper, VB Components have input parameters and output parameters. These can be used for connecting the scripted component to other components. These other components may be either built-in Grasshopper components or scripted components.

5.2.1 Inputs parameters

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.

Input parameters can be added, deleted and renamed through the VB Component menu. Right click the component, and select Input parameters from

Page 29

Page 30: Grasshopper VB Scripting 2

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> ''' </your code> End Sub

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> ''' </your code> End Sub

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> ''' </your code> End Sub

(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.)

5.2.2 Outputs parameters

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

Page 31: Grasshopper VB Scripting 2

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 Public line As System.Object #End Region

Output parameters do not support type-hints at this point.

5.3 Creating your own components

[under construction]

5.3.1 Design issues

[under construction]

5.3.2 Debugging

[under construction]

5.3.3 Exporting

[under construction]

Page 31

Page 32: Grasshopper VB Scripting 2

Grasshopper VB Scripting Primer, Version 2

6 Control Flow [under construction]

6.1 For… Next

[under construction]

6.2 If...Then...Else

[under construction]

Page 32

Page 33: Grasshopper VB Scripting 2

Grasshopper VB Scripting Primer, Version 2

7 The .NET System Namespace [under construction]

7.1 Array Class

[under construction]

7.1.1 Declaration, Instantiation and Assignment

Dim intArray1() As Integer

Dim intArray2() As Integer

intArray1 = New Integer() {1, 2, 3, 4}

intArray2 = New Integer() {}

ReDim intArray2(8)

7.1.2 Combined declaration, instantiation, and assignment

Dim intArray3() As Integer = New Integer() {5,6,7,8}

Dim intArray4() As Integer = {5,6,7,8}

7.2 String Class

[under construction]

7.3 Math Class

[under construction]

7.4 Random Class

[under construction]

7.5 A complete example

[under construction]

Page 33

Page 34: Grasshopper VB Scripting 2

Grasshopper VB Scripting Primer, Version 2

8 The .NET System.Collections.Generic Namespace A collection is a convenient way of grouping a set of elements into a single object. Collections include things like objects of type List that we have already come across a number of times.

For creating a collection object, you can use one of the classes in the System.Collections.Generic namespace. The collections in this namespace all follow the rule that the elements in a collection must all be of the same type, which is referred to as being strongly typed.

(There is another type of collection class, which is the Visual Basic Collection Class. This collection is not strongly typed, which means that you can add any type of element to it. When you retrieve an element from the collection, you will have to convert it to the right type, which on practice can lead to more errors. So it is recommended that you use of the classes in the System.Collections.Generic Namespace.)

8.1 Generic Types and Classes

Strongly typed collections are a good thing because it means that when you retrieve an element from the collection, you will not have to convert it to the right type. (This is the same for arrays.)

However, this could potentially mean that there would have to be a different version of the collection for each type it was supposed to hold. For example, a ListOfIntegers class, a ListOfDoubles class, a ListOfStrings class, etc. Luckily, this is not the case – instead there is a special mechanism that can be used to tell a generic List class what type of elements it should contain. This mechanism is called Generic Types, and the classes are referred to as Generic Classes. The reason for the name System.Collections.Generic is that the classes in this namespace are all Generic Classes.

A Generic Class is a class that adapts to perform the same functionality for a variety of data types. When you define a Generic Class, you parameterize it with one or more data types. This allows you to declare several different objects all based on the same Generic Class, but each one acting on different data types.

There are a number of Generic Classes in the System.Collections.Generic Namespace. For Grasshopper Scripting, the most important one is the List Class, since this is the data-structure that Grasshopper uses for sending lists of data between components.

8.2 The List Class

The List class is a collection of elements in a specific order that can be accessed by index. Initially this class may sound very similar to an array of one dimension. The key difference is that, with arrays, you have to specify in advance the size of

Page 34

Page 35: Grasshopper VB Scripting 2

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.

8.2.1 Declaration, Instantiation and Assignment

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:

ptList = New List(Of On3dPoint)()

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:

ptList = New List(Of On3dPoint) ‘do not do this

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

Page 36: Grasshopper VB Scripting 2

Grasshopper VB Scripting Primer, Version 2

constructor. So it is recommended that you always add the empty parenthesis to highlight that you are calling a constructor with no arguments.

8.2.2 Some useful methods

The List class has many useful methods for manipulating lists. Probably the most useful is the ability to add elements using the Add() method:

Dim pt1 As On3dPoint = New On3dPoint(0,1,2) ptList.Add(pt1)

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()

8.2.3 Lists and Arrays

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:

Dim ptArray() As On3dPoint = { New On3dPoint(1, 2, 3), New On3dPoint(4, 5, 6), New On3dPoint(7, 8, 9) }

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

Page 37: Grasshopper VB Scripting 2

Grasshopper VB Scripting Primer, Version 2

Dim anotherPtList As New List(Of On3dPoint)(ptArray)

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:

Dim pt2 As On3dPoint = New On3dPoint(2,3,4) ptList.Insert(1, pt2)

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()

8.3 Other generic collection classes

In this chapter, the focus has been on the List class. However, there are many other classes in the System.Collections.Generic namespace that may also be useful.

8.3.1 Collections similar to lists

Some of the classes in the System.Collections.Generic namespace are in fact very similar to the List class, but have methods that behave slightly differently. These differences may initially seem rather minor, but in certain circumstances they can be very useful. Three of these list-like collection classes are LinkedList, Queue and Stack:

• LinkedList: a collection that is similar to a List, but that has methods for adding and removing elements before and after other elements. The methods to add elements to the LinkedList are AddBefore, AddAfter, AddFirst, and AddLast. The methods to remove elements from the LinkedList are Remove, RemoveFirst and RemoveLast.

• Queue: a collection that is similar to a List, but where elements are automatically adding at one end and removed at the other end. The methods to add and remove elements from the queue are Enqueue and Dequeue respectively.

• Stack: a collection that is similar to a List, but where elements are automatically adding at one end and removed at the same end. The methods to add and remove elements from the stack are Push and Pop respectively.

8.3.2 Other types of collections

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

Page 38: Grasshopper VB Scripting 2

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.

8.4 A complete example

[under construction]

Page 38

Page 39: Grasshopper VB Scripting 2

Grasshopper VB Scripting Primer, Version 2

9 The Rhino RMA.OpenNURBS Namespace OpenNURBS is an open source toolkit for reading and writing models in the Rhino3d file format (.3dm). The toolkit consists of a set of C++ classes for handling the geometry in Rhino3d files. This includes classes for representing the the different types of geometric objects, as well as classes for reading / writing the geometry to a file. It does not include actual 3d modelling operations such as creating a loft between a set of curves. For the 3d modelling operations, the RMA.Rhino library is required.

There is also a .NET wrapper of the OpenNURBS toolkit that allows .NET programmers to access the classes in the toolkit. It is this wrapper that is imported in the Grasshopper_Custom_Script template as the RMA.OpenNURBS library.

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

Page 40: Grasshopper VB Scripting 2

Grasshopper VB Scripting Primer, Version 2

The help file contains documentation for three libraries: RMA.OpenNURBS, RMA.Rhino and RMA.UI. Only the first two are imported by the Grasshopper_Custom_Script template, so the RMA.UI can be ignored. In this chapter, we will be focusing on the first one: RMA.OpenNURBS.

Be warned that the documentation in this help file is actually quite limited – it consists mostly of just the names of the classes and class members.

9.1.1 Classes and Interfaces

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]

9.1.2 Looking at a class

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

Page 41: Grasshopper VB Scripting 2

Grasshopper VB Scripting Primer, Version 2

However, points and vectors typically can be used with arithmetic operators and comparison operators.) For example, if you define a point pt1, then you can write pt1 / 2, which will divide the x, y and z values of the point by 2.

• On3dPoint Properties lists all the properties for this class. In this case there are three properties called x, y, and z, all of which are of type Double.

9.2 Points, Vectors and Planes

The basic geometric classes include things like points, vectors, and planes.

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

Page 42: Grasshopper VB Scripting 2

Grasshopper VB Scripting Primer, Version 2

[under construction – add stuff about OnPointGrid, OnPointCloud]

9.2.2 Vectors

[under construction – add stuff about OnVector]

9.2.3 Planes

[under construction OnPlane and OnPlaneEquation]

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

Page 43: Grasshopper VB Scripting 2

Grasshopper VB Scripting Primer, Version 2

Finally, for Bezier curves and Polynomial curves, there are specific classes:

• OnBezierCurve

• OnPolynomialCurve

9.3.1 Lines, Circles and Arcs

Below are some example of creating lines, circles and arcs.

‘Create an OnLine between 2 points Dim ln As New OnLine(pt1, pt2) ‘Create a circle by centerpoint and radiius Dim cir1 As New OnCircle(pt1, 20) ‘Create a circle through three points Dim cir2 As New OnCircle(pt1, pt2, pt3) ‘Create an arc through three points Dim arc As New OnArc(pt2, pt3, pt4)

9.3.2 Curves

Below are some example of creating different types of OnLineCurve and OnArcCurve. These curves are similar in form to their counterparts, OnLine and OnArc, but their behaviour (i.e. the kinds of methods they have) is very different.

'creating an OnLineCurve between two points Dim lnCrv1 As New OnLineCurve(pt2, pt4) 'converting an OnLine to OnLineCurve and moving it Dim lnCrv2 As New OnLineCurve(ln) 'creating an OnArcCurve from a OnCircle and moving it 'the domain of the new curve is set to be between 0 and 1 Dim arcCrv1 As New OnArcCurve(cir1, 0, 1) 'converting an OnArc to OnArcCurve Dim arcCrv2 As New OnArcCurve(arc)

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.

'creating an array of points Dim ptsArray() As On3dPoint = {pt1, pt2, pt3, pt4}

Page 43

Page 44: Grasshopper VB Scripting 2

Grasshopper VB Scripting Primer, Version 2

'creating a clamped curve Dim nc1 As New OnNurbsCurve() nc1.CreateClampedUniformNurbs(3, 3, ptsArray) 'creating a periodic curve Dim nc2 As New OnNurbsCurve() nc2.CreatePeriodicUniformNurbs(3, 3, ptsArray)

9.3.3 Polys

[under construction – discuss polylines and polycurves]

9.3.4 Translating, Rotating and Scaling

[under construction - OnXForm]

9.4 Surfaces

[under construction]

9.5 Meshes

[under construction]

9.6 Solids

[under construction]

Page 44

Page 45: Grasshopper VB Scripting 2

Grasshopper VB Scripting Primer, Version 2

10 The Rhino RMA.Rhino Namespace [under construction]

Page 45

Page 46: Grasshopper VB Scripting 2

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