Create Grasshopper Components with Python
Thursday 11, June 2015
If you are familiar with Grasshopper for Rhino, you may already know that its visual programming interface works with components that get plugged to each other—each of the components being a function that takes and returns parameters as inputs and outputs, respectively.
GhPython is a Grasshopper plugin which brings the flexibility of the python programming language and the rhinoscriptsyntax right into Grasshopper — so you can build custom Grasshopper components by coding scripts in python.
This plugin doesn't come with Grasshopper by default, but you can download it here, and install it by dragging it on top of Grasshopper. The new plugin will appear under the Math components' section the next time you run Grasshopper (or you can run the GrasshopperUnloadPlugin command in Rhino to unload the plugin, then run Grasshopper to open it back again).
You can customize the inputs and outputs on the Grasshopper interface. The input names will represent the name of those objects inside the python script. The output will be created setting a variable inside the python script with the same name that you set in the component. Even though they are editable, the inputs in the example are x and y, and the output is a.
Create the Grasshopper definition as you see in the screenshot, and then double click the Python component to edit its code. Add the following snippet:
# Load rhinoscriptsyntax library as rs import rhinoscriptsyntax as rs # Variables x and y are automatically defined # We output a point with (x, y, 0) on variable 'a' a = rs.AddPoint((x, y, 0))
The end result is output a, which is a Grasshopper Point created by our Python component. This point is exactly the same that if it was created with the Grasshopper Construct Point component.