270 likes | 845 Views
AutoCAD® . NET: Developing for AutoCAD Using IronPython and IronRuby. Kean Walmsley Senior Manager Worldwide Developer Technical Services Autodesk Developer Network. About the Presenter.
E N D
AutoCAD® .NET: Developing for AutoCAD Using IronPython and IronRuby Kean Walmsley Senior Manager Worldwide Developer Technical Services Autodesk Developer Network
About the Presenter • Kean joined DevTech in August 1995, and has since worked in a number of different positions and countries (UK, USA, India and Switzerland). These days he spends most of his time on management-related activities, but still manages to keep involved at a technical level with our products. • Since July 2006 Kean has maintained a development-related blog at: blogs.autodesk.com/through-the-interface • Kean holds a Licenced’Informatique from l’Université de Paris-Sud and a Masters in Computer Science from the University of Kent at Canterbury.
Agenda • Introduction • What Makes a Language Dynamic? • Microsoft’s Dynamic Language Runtime • Introducing IronPython & IronRuby • Hosting DLR Languages in AutoCAD • Applications: HelloWorld, SolidJig, PipeOverrule • Summary • An Honourable Mention: Boo • The Future • Resources
Introduction • Increasing interest in “dynamic” or “scripting” languages • Well-suited for gluing components and systems • Advances in language design have led to leaps in productivity • Computing power is becoming cheaper and more accessible • Quickly-developed, reusable code with modest runtime overhead is a desirable trade-off • Assembly language is the quickest code to execute • Now very common to work with a “process virtual machine” • Java Virtual Machine, .NET’s Common Language Runtime • Emphasis shifts from compile-time type-checking to unit testing • A very important step when working with dynamic languages
Typical Properties of a Dynamic Language • Dynamically typed • Fewer variable type declarations: code is cleaner and simpler • Looser rules around code boundaries for implementing objects/interfaces • Interpreted • A REPL (Read-Eval-Print Loop) lets you try code quickly • AutoCAD’s command-line is a REPL for AutoLISP • Reduced code volume • Code is smaller, more readable and should contain fewer bugs • Learnable • Straightforward syntax which leads to early productivity • True for Python & Ruby, perhaps less so for JavaScript
Important Dynamic Concept: Duck Typing “When I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck.” • James Whitcomb Riley 1849-1916 • An object's current protocol determines the valid semantics • Allows polymorphism without inheritance • Some pseudo-code * functioncalculate(a, b, c) => return (a+b)*c calculate (1, 2, 3) 9 calculate ([1, 2, 3], [4, 5, 6], 2) [1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6] calculate (‘one ', 'and two, ', 3) one and two, one and two, one and two, * assumes + and * operators are defined for integers, lists and strings
Microsoft’s Dynamic Language Runtime • Allows creation of dynamic .NET languages • Set of shared, dynamic services built on top of the CLR • Dynamic type system • Dynamic method dispatch • Dynamic code generation • Hosting API • Originally developed as part of IronPython 1.0 • Abstracted out and shipped separately with IronPython 2.0 • Now also used by IronRuby • Libraries can be shared between languages • Planned to be used by other language implementations • IronScheme, Managed JScript, Nua
IronPython • The first, most mature dynamic language on the CLR/DLR • Currently at version 2.6 • An implementation of Python • Developed by Guido van Rossum, first release in 1991 • Widely used at Google, Guido’s current employer • Defining principles • One best way of doing things, simple and consistent • Characteristics • Whitespace is significant • Immutable strings, tuples • Slices • Explicit self parameter in class methods
IronRuby • The more recent addition to the “Iron” stable (currently 0.91) • Also now using the DLR, but not yet the same version as IronPython • An implementation of Ruby • Developed by Yukihiro Matsumoto (Matz), first release in 1995 • Really became popular around 2005 • Defining principles • Flexibility, everything is an object, principle of least surprise, natural not simple • Characteristics • Blocks • Naming conventions • local_var, $global_var, @instance_var, @class_var • ClassName, method_name • No need for brackets in function calls • Cleaner object orientation support
Hosting DLR Languages in AutoCAD • Implement two simple loader applications using a CLR language • I’ve used C# , could also have used VB.NET or even F# • Need to be NETLOADed (or demand-loaded) in AutoCAD • Define a load command for their language (RBLOAD/PYLOAD) • Command uses the DLR Hosting API • Different techniques currently needed IronPython IronRuby LanguageSetupls= Ruby.CreateRubySetup(); ScriptRuntimeSetuprs= newScriptRuntimeSetup(); rs.LanguageSetups.Add(ls); rs.DebugMode = true; ScriptRuntime runtime = Ruby.CreateRuntime(rs); ScriptEngineengine = Ruby.GetEngine(runtime); engine.ExecuteFile(file); Dictionary<string, object> options = newDictionary<string, object>(); options["Debug"] = true; ScriptEngineengine = Python.CreateEngine(options); engine.ExecuteFile(file); • Enable scriptdebugging
HelloWorld • Very simple application defining two commands • MSG – print a message to the command-line • MYCIR – create a circle in the modelspace IronPython IronRuby def mycir doc = Aas::Application.document_manager.mdi_active_document db = doc.database tr = doc.transaction_manager.start_transaction bt= tr.get_object(db.block_table_id,Ads::OpenMode.for_read) btr= tr.get_object(db.current_space_id,Ads::OpenMode.for_write) pt = Ag::Point3d.new(10,10,0) cir = Ads::Circle.new(pt,Ag::Vector3d.z_axis,2) btr.append_entity(cir) tr.add_newly_created_d_b_object(cir, true) tr.commit tr.dispose defmycir(): doc = aas.Application.DocumentManager.MdiActiveDocument db = doc.Database tr = doc.TransactionManager.StartTransaction() bt= tr.GetObject(db.BlockTableId,ads.OpenMode.ForRead) btr = tr.GetObject(db.CurrentSpaceId,ads.OpenMode.ForWrite) pt = ag.Point3d(10,10,0) cir = ads.Circle(pt,ag.Vector3d.ZAxis,2) btr.AppendEntity(cir) tr.AddNewlyCreatedDBObject(cir, True) tr.Commit() tr.Dispose()
SolidJig • Define an EntityJig to create a Solid3d box • Define a BOXJIG command to run the jig IronPython IronRuby # A jig to create a Solid3d - in this case a box class SolidJig < Aei::EntityJig # Constructor def SolidJig.new(ent) super end # The function called to run the jig def start_jig(ed, pt) # The start point is specified outside the jig @start = pt @end = pt @sol = self.entity return ed.drag(self) end … # A jig to create a Solid3d - in this case a box classSolidJig(aei.EntityJig): # Initialization function def __init__(self, ent): # Store the object and call the base class self._sol = ent aei.EntityJig.__init__(self, ent) # The function called to run the jig defStartJig(self, ed, pt): # The start point is specific outside the jig self._start = pt self._end = pt returned.Drag(self) …
PipeOverrule • A more complex application using AutoCAD 2010’s Overrule API • DrawableOverrule for WorldDraw, TransformOverrule for Explode • Implemented for lines and circles • MAKEPIPE command to add XData, assigning a radius IronPython IronRuby def world_draw(d, wd) ... super ... # Draw a pipe around the line ... clr = Ads::Circle.new start, norm, radius pipe = Ads::ExtrudedSurface.new begin pipe.create_extruded_surface(clr,norm,@sweep_opts) rescue print_message "\nFailed with CreateExtrudedSurface." end clr.dispose() pipe.world_draw(wd) pipe.dispose() ... return true end def WorldDraw(self, d, wd): ... PipeDrawOverrule.WorldDraw(self, d, wd) ... # Draw a pipe around the line ... clr = ads.Circle(start, norm, radius) pipe = ads.ExtrudedSurface() try: pipe.CreateExtrudedSurface(clr,norm,self._sweepOpts) except: print_message("\nFailed with CreateExtrudedSurface.") clr.Dispose() pipe.WorldDraw(wd) pipe.Dispose() ... return True
Summary • Dynamic languages provide easy paths into programming • Great for simple tasks without stringent performance requirements • Arguably the majority of programming tasks, these days • Python and Ruby are ultimately quite similar • Sects of the same church, rather than different religions • IronPython and IronRuby are great options if using the CLR • Also interesting for AutoCAD .NET development • Will become more so over time, as they share a common DLR • That said…
An Honourable Mention: Boo • A statically-typed language on the CLR using Python syntax • Allows you to compile .NET assemblies (.EXE or .DLL) • Provides many advantages of dynamic languages • Simple syntax, duck typing • Has the “safety” of static type-checking • Compilation step creates assembly containing MSIL • Boo syntax is mostly like Python • Some improvements for CLR and OO support • “super” borrowed from Ruby • “import” additional namespaces, “override” for defs that implement virtuals • “constructor()” instead of “__init__(self)” • No direct support for global variables • Make them static members of a “Globals” class • Use assembly attributes to define commands, etc. • Overall a very interesting compromise
The Future • Dynamic languages have gained widespread acceptance • And are being used for serious development activities • They’re also influencing statically-typed languages • C# 4.0 introduces the “dynamic” keyword dynamiccalc = GetCalculator(); intsum = calc.Add(10, 20); • Expect to see more of this, over time • “Compiler as a service” will enable dynamic code generation • It’s a good time to think about the benefits of dynamic code • This style of programming is becoming increasingly pervasive
Agenda • Introduction • What Makes a Language Dynamic? • Microsoft’s Dynamic Language Runtime • Introducing IronPython& IronRuby • Hosting DLR Languages In AutoCAD • Applications: HelloWorld, SolidJig, PipeOverrule • Summary • An Honourable Mention: Boo • The Future • Resources
Resources • Scripting: Higher Level Programming for the 21st Century • home.pacbell.net/ouster/scripting.html (IEEE Computer, March ‘98) • Empirical comparison of C, C++, Java, Perl, Python, Rexx, & Tcl • page.mi.fu-berlin.de/prechelt/Biblio/jccpprt_computer2000.pdf • CodePlex projects (with current version) • Dynamic Language Runtime – codeplex.com/dlr (0.92) • IronPython – codeplex.com/ironpython(2.6) • IronRuby – codeplex.com/ironruby (0.91) • The Boo Programming Language – boo.codehaus.org • C# 4.0 and Beyond – code.msdn.microsoft.com/csharpfuture • My blog – blogs.autodesk.com/through-the-interface