Thursday, August 20, 2009

py2rhino - object creation

The py2rhino connection is a set of classes that allow you to control Rhino from Python through a programming interface called COM. The functions that we can execute via this interface are the same as the Rhinoscript functions.

When scripting with py2rhino, the first thing you need to do is to import it, like this:

import py2rhino as p2r

Note that the p2r bit is optional - this just means that 'p2r' is an alias for 'py2rhino', which saves a lot of typing. You can check which version of py2rhino you have installed as follows:

print "py2rhino version number: ", p2r._version

The py2rhino library has been created using an object-orientated approach. This means that instead of simply having a very long list of functions, in py2rhino you also have classes, and each class has a set of functions (called methods) associated with it.

All the graphic objects that you can create in Rhino, like curves, surfaces, and meshes, are represented by classes. The graphic object classes are all found in the 'p2r.obj' namespace. If you want to draw a line, you need to create an instance of the Line class. This is done by calling one of the class's factory methods whose names start with 'create'. For example, here is how to create a line:

start_point = (0,0,0)
end_point = (20,10,0)
line = p2r.obj.Line.create(start_point, end_point)

The list of graphic object classes includes the following:
  • Curves: NurbsCurve, Line, Polyline, Circle, Arc, Ellipse, EllipticalArc, PolyCurve
  • Surfaces: NurbsSurface, PlaneSurface, Cone, Cylinder, Sphere, Torus, PolySurface
  • Meshes:Mesh, PlanarMesh
Each of these classes will have a set of 'create' factory methods that can be used for instantiating the class. In addition, you can also create a instance by using the default constructor and passing in the rhino id. This can be done line this:

line = p2r.obj.Line("3a357c2a-652c-4826-9938-eb3bb5b7dc62")

Of course, the id that you pass in must be for an object that really exists in Rhino, and also that it really is a line. In Rhino, if you want to get the id of an object, click the 'Details' button in Object Properties.

Here are some more examples of creating various graphic objects:

points = ((0,-10,0), (0,0,0),(2,0,0),(3,4,0),(7,9,0))
pl = p2r.obj.Polyline.create(points)
crv = p2r.obj.NurbsCurve.create_by_pnts(points, degree=3)
srf = p2r.obj.NurbsSurface.create_by_extrude_crv_straight(crv, (0,0,0), (0,0,10))

When you select a particular create command in the code editor, there will be a help window that will pop up with some documentation. Read this carefully in order to understand what the required and optional parameters are.

No comments:

Post a Comment