Upgrade to Pro — share decks privately, control downloads, hide ads and more …

3D Modeling with OpenSCAD

3D Modeling with OpenSCAD

http://monctonug.net/2016/02/16/3d-modeling-with-openscad/

As 3D printers have become less expensive and more common, they have moved beyond industry R&D laboratories and into art and design studios, libraries, Makerspaces, and even homes. Contributors sharing their creations on web-sites like GitHub, BitBucket, and Thingiverse have made on-demand manufacturing a reality for items as mundane as replacement knobs and as breathtaking as fantasy armour.

While 3D modeling software options aren't quite so plentiful, they fill out the spectrum from payware to open source. Packages such as PhotoShop CS3 and Blender are very graphics-oriented; anyone with a CAD or graphic design background will find a familiar toolset. But for those more comfortable with logic and mathematics, there's OpenSCAD (pronounced "open ess cad").

This presentation will provide an overview and examples of the OpenSCAD API, including its (numerous) quirks and "gotcha"s. Also covered will be the practicalities of printing on a MakerBot. Bring your curiosity, your creativity, your questions, your DIY spirit, and everything you can remember from waaaaay back in Trigonometry class.

Moncton Developer User Group

February 16, 2016
Tweet

More Decks by Moncton Developer User Group

Other Decks in Programming

Transcript

  1. Overview: What's Being Covered 1. Pros and Cons 2. The

    OpenSCAD UI 3. Code Structure 4. Creating Basic 3D Objects (“Singletons”) 5. Transforming and Manipulating Objects 6. Basic Debugging 7. Printing on MakerBot
  2. So who am I, right?  Chief cook and bottle-washer

    at Bonaventure Software  (Yet) Another programming side-step: Originally needed custom parts for Arduino-projects  Appalling drafting skills...in CAD or in meat-space  OpenSCAD, by contrast, builds shapes via math and code
  3. OpenSCAD: The Pros  Absolutely no drawing ability required 

    Free-as-in-beer open source (vs. Sketchup)  Uncomplicated UI (vs. Blender)  Supported on Linux, Mac, and Windows (vs. Sketchup)  Can be rendered and exported from the command- line  OpenSCAD provides an unparalleled opportunity to appreciate just how much Geometry / Trigonometry / Vector Algebra you've forgotten
  4. OpenSCAD: The Cons  API is rapidly evolving – not

    always backwards- compatible  Linux versions (in the official repositories) can lag considerably behind Windows/Mac  Arcs are not supported except in 3rd-party libraries  sizeof()-type functions not supported except in 3rd-party libraries  Primitive debugging capabilities  (My opinion) Some annoying API inconsistencies
  5. OpenSCAD UI: Manipulating Viewport  Left-click plus mouse-drag rotates on

    X, Y, and Z axes  Right-click plus mouse-drag moves the objects plus axes within viewport  Mouse-roll upward zooms in  Mouse-roll downward zooms out  Note: Later versions of OpenSCAD may have shortcut buttons for top view, side view, re-centering, etc.  “Preview” (F5) vs. “Render” (F6) modes
  6. Code Structure: The Non-drawing Parts  C-ish look and feel

     Variables (including the biggest “gotcha”)  Looping  Conditional logic  Operators  Built-in functions  Modules and Functions  API “chaining”
  7. C-ish Look and Feel, but...  Looks just enough like

    classic (K&R) C to trip you up.  Not object-oriented  “Functional” language in that functions can take other functions/modules as parameters  No exception-handling  echo() is your System.out.println()  Variable scope is what you'd expect...mostly  Gotcha: Undefined variables will equate to zero and generate a warning, but not a compiler error
  8. Variables in OpenSCAD  Variables are dynamically typed  Variable

    types are implicit, not declared  Six variable types:  Signed floating-point number: Approx -1.0e+308 – 1.0e+308  Boolean: Some counter-intuitive evaluations  String: Some vector-like characteristics  Vector/Matrix: Square-bracket syntax  Range: Used mainly in for-loops; two or three “parameters”  Undefined and NaN (udef and nan, respectively)  Gotcha: With few exceptions, variable values are set at compile-time, not run-time
  9. Looping  No while-loops  for-loops have a slightly different

    iteration syntax: for(i = [0:9]) {...} or for(i = [0:2:10]) {...} or for(i = [1.0, 1.1, 1.2, 1.3, 1.4]) or for(i = 2_dimensional_array_name)  Loops can be nested
  10. Conditional logic  if – else blocks look like C:

    if ([condition is true]) // do something else // do something else  if – else blocks can be nested  Inline-if syntax can only return values, not execute other code: [Test_condition] ? [True_value] : [False_value] (x == y) ? fltMax : fltMin;  Gotcha: if­else cannot be used to set variable values – code will not compile
  11. Operators  Most of the usual suspects from C are

    available:  Arithmetic: +, ­, *, /, %  Comparison: <, >, <=, >=, ==, !=  Logic: &&, ||, !  Minus-sign also negates or multiplies by -1  When used with a vector and number, * and / multiply/divide all vector elements w/that number  When used with two vectors (of the identical size), + and – add/subtract the vector elements  The usual rules about vector and matrix dot- products apply
  12. OpenSCAD's Built-in functions  Trigonometric functions: sin(), cos(), tan(), asin(),

    acos(), atan(), atan2()  Trig. functions take degrees, not radians, as arguments  π (PI) is a reserved word  Math functions: abs(), ceil(), floor(), min(), max(), exp(), pow(), sqrt(), sign(), ln(), log(), round(), rand()  Vector functions: concat(), cross(), len(), lookup(), norm()
  13. Code Execution  A .scad file is both compiled and

    executed by opening it in the OpenSCAD program  There is no application entry-point (e.g. no main() function)  Break reusable code out into modules and functions  Variables and functionality used by more than one model can be <include>d or <use>d  <use>d code makes variables/modules/functions available, but does not execute inline code  <include>d code executes any inline code as well as makes variables/modules/functions available
  14. Modules and Functions  Modules can draw objects, but cannot

    return a value.  Functions return a single value, cannot draw anything, and must be written inline: function computeSecant(fltDegrees)= (1 / cos(fltDegrees));  Both modules and functions can take parameters  Modules can call other modules as well as functions; functions can only call other functions
  15. Chaining API Calls  Particularly when using the “drawing” parts

    of the OpenSCAD API, functions can be “chained”  Basically, the API function is taking another API function as a parameter  Your own module can be used as the last parameter  For readability, use indentation and/or curly-braces  When chaining single-line function-calls, a semi- colon ends a chain  Closing curly-braces determine the end of a multi- line chain
  16. Three Ways to Make Singletons 1. Drawing 3D “primitives” 

    cube()  sphere()  cylinder()  polyhedron() -- “custom primitive” of vertices and planes 2. Projecting 2D shapes into 3D space  linear_extrude()  rotate_extrude()  text() 3. Programatically
  17. 3D “Primitives”: Cube  “Cube” is a misnomer: Can also

    be a rectangular block  Two parameters:  size: A float or vector that determines the XYZ dimensions  center: A Boolean indicating whether or not to center on the XYZ origin-point (false places cube “bottom” on Q1 of the XY plane.)  $fn, $fa, and $fs are pointless with blocks; don't bother with them
  18. 3D “Primitives”: Sphere  Does what it says on the

    label  Parameters:  r, for “radius”  d, for “diameter,” is not backwards-compatible  $fn, $fa, $fs (most likely $fn) to control granularity  “Gotcha”: You do not have the option of turning off centering at the origin – you have to explicitly move it
  19. 3D “Primitives”: Fragment Variables  Use to control resolution of

    3D primitives with curved surfaces (i.e., sphere and cylinder)  For spheres and cylinders, applies to “top” view  Three variables:  $fn specifies the number of fragments  $fa specifies the fragment angle in degrees  $fs specifies the fragment size in millimetres  Tradeoff: Finer resolution = more processing and longer printing-time
  20. 3D “Primitives”: Cylinder  You can also use it to

    make a cone (pointy or truncated)  Parameters:  r : float that indicates single radius (cylinder); r1 + r2 = bottom and top radii for a cone  d : float that specifies cylinder diameter; d1 + d2 = bottom and top diameters of a cone  h : float that indicates height  center : true centers on XYZ origin; false centers on XY origin  $fn, $fa, $fs : Specifies granularity of sides
  21. 3D “Primitives”: Polyhedrons  Points (vertices) and faces (planes) 

    Parameters:  points : a vector of XYZ points (themselves vectors of floats)  faces / triangles : a vector of vectors; the vectors are the indices of the points that make the corners of each face/triangle  Always define faces clockwise, from the perspective of the outside of the object  triangles is for pre-2014 OpenSCAD versions; all faces must be comprised of triangles!
  22. Polyhedron: Points & Triangles P0 [0.0, 0.0, 0.0] P1 [15.0,

    (sin(60.0) * 30.0), 0.0] P2 [30.0, 0.0, 0.0] Apex (top point): P3 [15.0, ((sin(60.0) / 2) * 30.0), (sin(60) * 3.0)]] T1 [P0, P3, P2] Underside: T0 [P0, P1, P2] T2 [P1, P3, P0] T3 [P2, P3, P1]
  23. 2D -> 3D Extrusion  Build a 2D object and

    project it into 3D space  linear_extrude() projects “up” from XY plane's “ground”  rotate_extrude() spins shape like on a pottery wheel  Can use built-in 2D objects (square, circle, ellipse), “custom” polygons, or imported .dxf files  Hack: Can use circle to make a regular polygon before extruding – just specify # of faces
  24. 2D -> 3D Extrusion: linear_extrude()  Example of function “chaining”:

    linear_extrude() specifies the 3D attributes of all that follows in its “chain”  Parameters:  height : float specifying height  center : Boolean specifying whether or not to center on the Z axis  convexity : float specifying max. # of points a line passing through shape would intersect  slices : specifies granularity on the Z-axis  twist : float specifying degrees of twist during build-up  scale : float specifies change in size for both X & Y; vector specifies change for each dimension
  25. linear_extrude() with scale, top view Gotcha: Polygon footprint will “hug”

    the X-Y origin; for a symmetrical extrusion, center 2D object on X-Y origin (0, 0)
  26. 2D -> 3D Extrusion: rotate_extrude()  Draws a 2D object

    on X-Y plane, which is automatically rotated 90 degrees around the X-axis before 360 degree rotation around the Z-axis  Parameters:  convexity : the max. # of times a line will intersect w/edges of 2D object it passes through  $fn, $fa, $fs : As with 3D primitives, specifies granularity  Gotcha #1: polygon() must be entirely in Q1  Gotcha #2: Documentation may not be correct
  27. 2D -> 3D Extrusion: Text  Only supported in the

    last stable release (2015.03)  Basic parameters:  The text itself, enclosed in quotation-marks  size : approx. font size, like in word processing  font : the font name, e.g. Liberation Serif  style : Bold and/or Italic  Non-system fonts must be installed with use, e.g. use <ttf/comic­papyrus/TROLLFACE.ttf>  Unicode characters can be specified with backslash notation: \x03, \u0123, or \U012345
  28. 2D -> 3D Extrusion: Aligning Text  Text layout and

    options are fairly primitive  Text vector specified by the direction parameter:  ltr : left-to-right  rtl : right-to-left  ttb : top-to-bottom  btt : bottom-to-top  Default is left-to-right if direction not specified  rtl prints each letter backwards as well as reversing their order, but btt does not print letters upside-down
  29. 2D -> 3D Extrusion: Aligning Text, cont.  Horizontal &

    vertical alignment text() parameters control positioning w/in bounding box  Possible halign values: left, center, and right  Possible valign values: top, bottom, center, and baseline  Default values are left and baseline, respectively, when not specified  In practice, you will probably use translate() more often that halign/valign to position text
  30. Programming 3D Objects  Basic idea: Combine logic and built-in

    functions  Typically, using for-loops to build shape in “slices”  “Slices” take the place of the $fn, $fa, $fs variables  The # of slices is a tradeoff between granularity of the finished product and the processing / printing required
  31. A 3D Project's “Toolkit”  Transform objects by stretching/compressing with

    scale() and resize()  Change object location with translate() and rotate()  Glue/Meld singletons together with union()  Subtract singletons with difference() and intersection()  Superpowers: hull() and minkowski()functions
  32. Transforming Objects with scale() & resize()  Both functions transform

    object dimensions in XYZ space  Both functions take an [X, Y, Z] vector as a parameter  With scale(v=[x, y, z]), x, y, and z are multiples of the original dimensions  With resize(newsize=[x, y, z]), x, y, and z are literal measurements unrelated to original dimensions
  33. scale() and resize(), cont.  For many purposes, scale() and

    resize() are equivalent  If you use zero as one of resize()'s newsize parameters, the object will not be resized in that dimension  Alternatively, set one newsize parameter, set the others to 0, and use the optional auto parameter to proportionally scale the other dimensions  Pro tip: resize() is handy for combining text w/other 3D objects
  34. Moving Objects on the 3D “Canvas”  By default, all

    objects are drawn relative to (0, 0, 0), with zero degrees of rotation around all axes  translate() and rotate() apply to the code- chain / code-block that follow, then OpenSCAD resets back to (0, 0, 0) with zero rotation  rotate() takes degrees, not radians, as parameters  translate() and rotate() can be mixed, nested and repeated as often as necessary  Gotcha: translate() + rotate() != rotate() + translate()
  35. Building Complex Shapes from Singletons  No parameters needed for

    union(), intersection(), and difference()  The usual rules of code-chaining apply: Use semi- colons and curly-braces accordingly  All three functions can be nested w/in blocks in infinite variety  Shortcuts for creating “shells” for compound objects: hull() and minkowski()  2D objects can use all of the above functions before being extruded to 3D
  36. Error-handling in OpenSCAD  Again, no try-catch exception handling :~(

     Compilation failures will prevent all rendering  Runtime errors (e.g. undefined variables, NaN, etc.) will generate warnings, but will render improperly  Errors and warnings are shown in the console area of the GUI  Gotcha: Included/Used files will throw off the line numbers of the error message
  37. Debugging “Toolkit”  The echo() function prints message to the

    console  Commas concatenate strings and numbers in echo()  An exclamation-point (!) before a block of code draws only that block of code  A hashtag (#) before a block of code draws its objects in semi-transparent colour to highlight them  An asterisk (*) before a block of code ignores it and draws everything else  Caveat: Asterix may have side effects, particularly with the difference() function
  38. 3D Models in Plasticspace  Export .scad to .stl or

    .obj files for printing  Units: 1.0 in OpenSCAD == 1mm on MakerBot  Printer puts down a “raft” before printing object; must be manually separated after printing  Orient object to print “into thin air” as little as possible – can be done w/Makerbot software – Supporting “legs” will need to be broken/sanded off – Consider coding objects so they can be glued together  Adjust infill (w/Makerbot software) to control amount of plastic used inside shape
  39. OpenSCAD: Resources  OpenSCAD website: http://www.openscad.org/  OpenSCAD user manual

    & language reference: https://en.wikibooks.org/wiki/OpenSCAD_Use r_Manual  Various sample projects (MakerBot website): http://www.thingiverse.com  New to C? The C Programming Language, Kernigan & Richie  Shameless plug for the MPL Makerspace/FabLab: http://monctonpubliclibrary.ca/makerspace/