1//////////////////////////////////////////////////////////////////////
   2// LibFile: screws.scad
   3//   Functions and modules for creating metric (ISO) and English (UTS) standard screws and nuts.
   4//   Included is a function for calculating the standard dimensions of screws including the
   5//   tolerance values that are required to make screws mate properly when they are formed
   6//   precisely.  If you can fabricate objects accurately then the modeled screws will mate
   7//   with standard hardware without the need to introduce extra gaps for clearance.
   8// Includes:
   9//   include <BOSL2/std.scad>
  10//   include <BOSL2/screws.scad>
  11// FileGroup: Threaded Parts
  12// FileSummary: ISO (metric) and UTS screws and nuts.
  13//////////////////////////////////////////////////////////////////////
  14
  15include <structs.scad>
  16include <threading.scad>
  17include <screw_drive.scad>
  18
  19// Section: Screw and Nut Parameters
  20//    This modules in this file create standard ISO (metric) and UTS (English) threaded screws.
  21//    The {{screw()}} and {{nut()}} modules produce
  22//    screws and nuts that comply with the relevant ISO and ASME standards,
  23//    including tolerances for screw fit.  You can also create screws with
  24//    various head types and drive types that should match standard hardware.
  25// Subsection: Screw Naming
  26//    You can specify screws using a string that specifies the screw.
  27//    Metric or ISO screws are specified by a diameter in millimeters and a thread pitch in millimeters.  For example,
  28//    an M8x2 screw has a nominal diameter of 8 mm and a thread pitch of 2 mm.  
  29//    The screw specification for these screws has the form: "M`<size>`x`<pitch>`,`<length>`,
  30//    so "M6x1,10" specifies a 6mm diameter screw with a thread pitch of 1mm and length of 10mm.
  31//    You can omit the pitch or length, e.g. "M6x1", or "M6,10", or just "M6".  If you omit the
  32//    length then you must provide the `length` parameter.  If you omit the pitch, the library
  33//    provides a standard pitch for the specified diameter.
  34//    .
  35//    Imperial or UTS screws are specified by a diameter and the number of threads per inch.
  36//    For large screws, the diameter is simply the nominal diameter in inches, so a 5/16-18 screw
  37//    has a nominal diameter of 5/16 inches and 18 threads per inch.  For diameters smaller than
  38//    1/4 inch, the screw diameter is given using a screw gauge, which can be from 0 up to 12.
  39//    A common smaller size is #8-32, an 8 gauge screw with 32 threads per inch.  
  40//    For UTS screws the specification has the form `<size>`-`<threadcount>`,`<length>`, e.g. 
  41//    "#8-32,1/2", or "1/4-20,1".  The units are in inches, including the length.  Size can be a
  42//    gauge number from 0 to 12 with or without a leading # to specify a screw gauge size, or any other
  43//    value to specify a diameter in inches, either as a float or a fraction, so "0.5-13" and
  44//    "1/2-13" are equivalent.  To force interpretation of the value as inches add '' (two
  45//    single-quotes) to the end, e.g. "1''-4" is a one inch screw and "1-80" is a very small
  46//    1-gauge screw.  The pitch is specified using a thread count, the number of threads per inch.
  47//    As with the ISO screws, you can omit the pitch or length and specify "#6-32", "#6,3/4", or simply #6.
  48//    As in the metric case, if you omit the length then you must provide the `length` parameter.  If you omit the pitch, the
  49//    library provides a standard pitch for the specified diameter.
  50// Subsection: Standard Screw Pitch
  51//    If you omit the pitch when specifying a screw or nut then the library supplies a standard screw pitch based
  52//    on the screw diameter as listed in ISO 724 or ASME B1.1.  For many diameters, multiple standard pitches exist.
  53//    The available thread pitch types are different for ISO and UTS:
  54//    .
  55//    | ISO      |    UTS   |
  56//    | -------- | -------- |
  57//    | "coarse" |  "coarse" or "UNC" |
  58//    | "fine"   |   "fine" or "UNF"  |
  59//    | "extrafine" or "extra fine" | "extrafine", "extra fine", or "UNEF"  |
  60//    | "superfine" or "super fine" |   |
  61//    | "none"   |  "none"  |
  62//    .
  63//    The default pitch selection is "coarse".  Note that this selection is case insensitive.
  64//    To set the pitch using these pitch strings you use the `thread=` argument to the modules.
  65//    You cannot incorporate a named pitch into the thread name.  The finer pitch categories
  66//    are defined only for larger screw diameters.  You can also use the `thread=` argument to
  67//    directly specify a pitch, so `thread=2` produces a thread pitch of 2mm.  Setting the
  68//    pitch to zero produces an unthreaded screws, the same as setting it to "none".  Specifying
  69//    a numeric value this way overrides a value given in the specification.  You can also set
  70//    `thread=true` or `thread=false` to turn threading on and off, with the same default coarse
  71//    threading when you set it to true.  
  72// Subsection: Screw Heads
  73//    By default screws do not have heads.  
  74//    You can request a screw head using `head=` parameter to specify the desired head type.  If you want the
  75//    head to have a recess for driving the screw you must also specify a drive type using `drive=`.  
  76//    The table below lists the head options.  Only some combinations of head and drive
  77//    type are supported.  Different sized flat heads exist for the same screw type.
  78//    Sometimes this depends on the type of recess.  If you specify "flat" then the size will be chosen
  79//    appropriately for the recess you specify.
  80//    .
  81//    The `drive=` argument can be set to "none", "hex", "slot", 
  82//    "phillips", "ph0" to "ph4" (for phillips of the specified size), "torx" or
  83//    "t<size>" (for Torx at a specified size, e.g. "t20").  If you have no head but still
  84//    give a drive type you will get a set screw.  The table below lists all of the head types and
  85//    shows which drive type is compatible with each head types.  Different head types work in ISO and UTS,
  86//    as marked in the first column.  
  87//    .
  88//    |ISO|UTS|Head            | Drive  |
  89//    |---|---|--------------- | ----------------------------|
  90//    |X|X|"none"          | hex, torx, slot |
  91//    |X|X|"hex"           | *none*|
  92//    |X|X|"socket"        | hex, torx|
  93//    |X|X|"button"        | hex, torx|
  94//    |X|X|"flat"          | slot, phillips, hex, torx|
  95//    |X|X|"flat sharp"    | slot, phillips, hex, torx|
  96//    | |X|"flat small"    | slot, phillips|
  97//    | |X|"flat large"    | hex, torx |
  98//    | |X|"flat undercut" | slot, phillips |
  99//    | |X|"flat 82"       | slot, phillips |
 100//    | |X|"flat 100"      | slot, phillips |
 101//    | |X|"round"         | slot, phillips |
 102//    | |X|"fillister"     | slot, phillips |
 103//    |X|X|"pan"           | slot, phillips, torx (ISO only) |
 104//    |X| |"cheese"        | slot, phillips, torx |
 105//    .
 106//    The drive size is specified appropriately for the drive type: drive number for phillips or torx,
 107//    and recess width in mm or inches (as appropriate) for hex.  Drive size is determined automatically
 108//    from the screw size, but by passing the `drive_size=` argument you can override the default, or
 109//    in cases where no default exists you can specify it.  Flat head screws have variations such as 100 degree
 110//    angle for UTS, or undercut heads.  You can also request a "sharp" screw which will set the screw diameter 
 111//    the theoretical maximum and produce sharp corners instead of a flat edge on the head.  For a flat head screw
 112//    the drive specification must start with "flat", but the flat head options
 113//    can be mixed in any order, for example, "flat sharp undercut" or "flat undercut sharp".
 114// Subsection: Nuts
 115//    Nuts come in standard sizes and BOSL2 has tables to produce sizes for both Imperial and metric nuts.
 116//    A nut for a given thread size is defined by its shape, width and thickness.  The shape is either "hex"
 117//    for hexagonal nuts or "square" for square nuts.  For hexagonal Imperial nuts, you can choose from thickness values
 118//    of "thin", "normal" or "thick", but the thin and thick nuts are defined only for thread sizes of 1/4 inch and above.
 119//    .
 120//    Metric nut standards are more complicated because ISO has a series of standards and DIN has a series of conflicting
 121//    standards.  Nuts from McMaster-Carr in the USA comply with DIN rather than ISO.  Furthermore, ISO does not appear
 122//    to specify dimensions for square nuts.  For metric nuts you can specify "thin", "normal" and "thick" and the
 123//    nut will be constructed to ISO standards (ISO 4035, ISO 4032, and ISO 4033 respectively).  The DIN standard for thin
 124//    nuts matches ISO, but the DIN normal thickness nuts are thinner than ISO nuts.  You can request DIN nuts
 125//    by specifying a thickness of "DIN" or "undersized".  If you request a square nut it necessariliy derives from DIN
 126//    instead of ISO.  For most nut sizes, the nut widths match between ISO and DIN, but they do differ for M10, M12, M14 and M22.
 127//    .
 128//    You can of course specify nuts by giving an explicit numerical width and thickness in millimeters. 
 129// Subsection: Tolerance
 130//    Without tolerance requirements, screws would not fit together.  The screw standards specify a
 131//    nominal size, but the tolerance determines a range of allowed sizes based on that nominal size.
 132//    So for example, an M10 screw with the default tolerance has an outside (major) diameter between 9.74 mm and 9.97 mm.
 133//    The library will use the center point in the allowed range and create a screw with a diameter of 9.86 mm.
 134//    A M10 nut at the default tolerance has a major diameter (which is the inside diameter) between 10 mm and 10.4 mm.
 135//    Shrinking the major diameter of a screw makes the screw loose.  Shrinking the major diameter of a nut, on the other hand,
 136//    makes the hole smaller and hence makes the nut tighter.  For this reason, we need a difference tolerance
 137//    for a screw than for a nut.  Screw tolerances shrink the diameter to make the screw looser whereas nut tolerances
 138//    increase the diameter to make the nut looser.  Screws modeled using this library will have dimensions consistent with the
 139//    standards they are based on, so that they will interface properly if fabricated by an accurate method.  The ISO and UTS
 140//    systems use different tolerance designations.
 141//    .
 142//    For UTS screw threads the tolerance is one of "1A", "2A" or "3A", in
 143//    order of increasing tightness.  The default tolerance is "2A", which
 144//    is the general standard for manufactured bolts.
 145//    .
 146//    For UTS nut threads, the tolerance is one of "1B", "2B" or "3B", in
 147//    order of increasing tightness.  The default tolerance is "2B", which
 148//    is the general standard for manufactured nuts.
 149//    .
 150//    The ISO tolerances are more complicated.  For both screws and nuts the ISO tolerance has the form of a number
 151//    and letter.  The letter specifies the "fundamental deviation", also called the "tolerance position", the gap
 152//    from the nominal size.  The number specifies the allowed range (variability) of the thread heights.  For
 153//    screws, the letter must be "e", "f", "g", or "h", where "e" is the loosest and "h" means no gap.  The number
 154//    for a screw tolerance must be a value from 3-9 for crest diameter and one of 4, 6, or 8 for pitch diameter.
 155//    A tolerance "6g" specifies both pitch and crest diameter to be the same, but they can be different, with a
 156//    tolerance like "5g6g" specifies a pitch diameter tolerance of "5g" and a crest diameter tolerance of "6g".
 157//    Smaller numbers give a tighter tolerance.  The default ISO screw tolerance is "6g".
 158//    .
 159//    For ISO nuts the letters specifying the fundamental deviation are upper case and must be "G" or "H" where "G"
 160//    is loose and "H" means no gap. The number specifying the variability must range from 4-8.  An allowed (loose)
 161//    nut tolerance is "7G".  The default ISO tolerance is "6H".
 162//    .
 163//    Clearance holes have a different tolerance system, described in {{screw_hole()}}.
 164//    .
 165//    If you wish to create screws at the nominal size you can set the tolerance to 0 or "none".  
 166// Subsection: screw_info and nut_info structures
 167//    When you make a screw or nut, information about the object such as the thread characteristics 
 168//    head and drive size, or nut thickness are placed into a data structure.  The screw and nut 
 169//    modules can accept screw names, as described above, or they can accept screw structures. 
 170//    When you use a screw structure as a specification, computed values like head type and size and
 171//    driver characteristics are fixed and cannot be changed, but values that are not computed
 172//    like length can still be altered.  If you want to create an unusual part you can hand
 173//    generate the structure with your desired parameters to fill in values that would normally
 174//    be produced automatically from the standard tables.  So if your hardware is missing from the
 175//    tables, or is sized differently, you can still create the part.  For details on the
 176//    screw_info and nut_info structures, see {{screw_info()}} and {{nut_info()}}.  
 177//    .
 178//    All of the screw related modules set the variable `$screw_spec` to contain the specification
 179//    for their screw.  This means that child modules can make use of this variable to create
 180//    mating (or identical) parts.  Note that the `shaft_oversize` and `head_oversize` screw
 181//    info fields are only inherited into modules that are the same as the parent module.
 182//    This means that if you create an oversized screw hole and then make a screw as s child, the
 183//    child screw will **not** inherit the oversize parameters.  But a screw_hole will inherit 
 184//    oversize parameters from a parent screw_hole.  
 185
 186/*
 187http://mdmetric.com/thddata.htm#idx
 188
 189Seems to show JIS has same nominal thread as others
 190https://www.nbk1560.com/~/media/Images/en/Product%20Site/en_technical/11_ISO%20General%20Purpose%20Metric%20Screw%20Threads.ashx?la=en
 191
 192Various ISO standards here:  https://www.fasteners.eu/standards/ISO/4026/
 193
 194Torx values:  https://www.stanleyengineeredfastening.com/-/media/web/sef/resources/docs/other/socket_screw_tech_manual_1.ashx
 195
 196*/
 197
 198
 199// Section: Making Screws
 200
 201// Module: screw()
 202// Synopsis: Creates a standard screw with optional tolerances.
 203// SynTags: Geom
 204// Topics: Threading, Screws
 205// See Also: screw_hole(), shoulder_screw()
 206// Usage:
 207//   screw([spec], [head], [drive], [thread=], [drive_size=], [length=|l=], [thread_len=], [undersize=], [shaft_undersize=], [head_undersize=], [tolerance=], [blunt_start=], [details=], [anchor=], [atype=], [orient=], [spin=]) [ATTACHMENTS];
 208// Description:
 209//   Create a screw.  See [screw and nut parameters](#section-screw-and-nut-parameters) for details on
 210//   the parameters that define a screw.  The tolerance determines the dimensions of the screw based
 211//   on ISO and ASME standards.  Screws fabricated at those dimensions will mate properly with
 212//   standard hardware.  Note that the $slop argument does not affect the size of screws: it only
 213//   adjusts screw holes.  This will work fine if you are printing both parts, but if you need to mate
 214//   printed screws to metal parts you may need to adjust the size of the screws, which you can do
 215//   with the undersize arguments.
 216//   .
 217//   You can generate a screw specification from {{screw_info()}}, possibly create a modified version
 218//   using {{struct_set()}}, and pass that in rather than giving the parameters.
 219//   .
 220//   Various anchor types refer to different parts of the screw, some of which are labeled below.  The
 221//   "screw" anchor type (the default) is simply the entire screw, so TOP and BOTTOM refer to the head
 222//   end and tip respectively, and CENTER is the midpoint of the whole screw, including the head.  The
 223//   "head" anchor refers to the head alone.  Both of these anchor types refer to the bounding
 224//   cylinder for the specified screw part, except for hex heads, which anchor to a hexagonal prism.
 225// Figure(2D,Med,VPD = 140, VPT = [18.4209, 14.9821, -3.59741], VPR = [0, 0, 0],NoAxes):
 226//   rpos=33;
 227//   fsize=2.5;
 228//   projection(cut=true) xrot(-90)screw("M8", head="socket", length=25, thread_len=10,anchor=BOT);
 229//   right(rpos)projection(cut=true) xrot(-90)screw("M8", head="flat", length=25, thread_len=10,anchor=BOT);
 230//   color("black"){
 231//      stroke([[5,0],[5,10]],endcaps="arrow2",width=.3);
 232//      back(5)right(6)text("threads",size=fsize,anchor=LEFT);
 233//      stroke([[5,10],[5,25]],endcaps="arrow2",width=.3);
 234//      back(10+15/2)right(6)text("shank",size=fsize,anchor=LEFT);
 235//      stroke([[-5,0],[-5,25]],endcaps="arrow2",width=.3);
 236//      back(25/2)right(-6)text("shaft",size=fsize,anchor=RIGHT);
 237//   }
 238//   sh=10.2841;
 239//   right(rpos)
 240//   color("black"){
 241//      stroke([[5,0],[5,10]],endcaps="arrow2",width=.3);
 242//      back(5)right(6)text("threads",size=fsize,anchor=LEFT);
 243//      stroke([[5,10],[5,10+sh]],endcaps="arrow2",width=.3);
 244//      back(10+sh/2)right(6)text("shank",size=fsize,anchor=LEFT);
 245//      stroke([[-5,0],[-5,10+sh]],endcaps="arrow2",width=.3);
 246//      back((10+sh)/2)right(-6)text("shaft",size=fsize,anchor=RIGHT);
 247//   }
 248// Arguments:
 249//   spec = screw specification, e.g. "M5x1" or "#8-32".  See [screw naming](#subsection-screw-naming).  This can also be a screw specification structure of the form produced by {{screw_info()}}.  
 250//   head = head type.  See [screw heads](#subsection-screw-heads)  Default: none
 251//   drive = drive type.  See [screw heads](#subsection-screw-heads) Default: none
 252//   ---
 253//   length / l = length of screw (in mm)
 254//   thread = thread type or specification. See [screw pitch](#subsection-standard-screw-pitch). Default: "coarse"
 255//   drive_size = size of drive recess to override computed value
 256//   thread_len = length of threaded portion of screw (in mm), for making partly threaded screws.  Default: fully threaded
 257//   details = toggle some details in rendering.  Default: true
 258//   tolerance = screw tolerance.  Determines actual screw thread geometry based on nominal sizing.  See [tolerance](#subsection-tolerance). Default is "2A" for UTS and "6g" for ISO.  
 259//   undersize = amount to decrease screw diameter, a scalar to apply to all parts, or a 2-vector to control shaft and head.  Replaces rather than adding to the head_oversize value in a screw specification.  
 260//   shaft_undersize = amount to decrease diameter of the shaft of screw; replaces rather than adding to the shaft_oversize value in a screw specification. 
 261//   head_undersize = amount to decrease the head diameter of the screw; replaces rather than adding to the head_oversize value in a screw specification. 
 262//   bevel1 = bevel bottom end of screw.  Default: true
 263//   bevel2 = bevel top end of threaded section.  Default: true for fully threaded or unthreaded headless, false otherwise
 264//   bevel = bevel both ends of the threaded section.
 265//   blunt_start = if true and hole is threaded, create blunt start threads.  Default: true
 266//   blunt_start1 = if true and hole is threaded, create blunt start threads at bottom end.
 267//   blunt_start2 = if true and hole is threaded, create blunt start threads top end.
 268//   atype = anchor type, one of "screw", "head", "shaft", "threads", "shank"
 269//   anchor = Translate so anchor point on the shaft is at origin (0,0,0).  See [anchor](attachments.scad#subsection-anchor).  Default: `CENTER`
 270//   spin = Rotate this many degrees around the Z axis after anchor.  See [spin](attachments.scad#subsection-spin).  Default: `0`
 271//   orient = Vector to rotate top towards, after spin.  See [orient](attachments.scad#subsection-orient).  Default: `UP`
 272// Side Effects:
 273//   `$screw_spec` is set to the spec specification structure. 
 274// Anchor Types:
 275//   screw = the entire screw (default)
 276//   head = screw head (invalid for headless screws)
 277//   shaft = screw shaft
 278//   shank = unthreaded section of shaft (invalid if screw is fully threaded)
 279//   threads = threaded section of screw     
 280// Extra Anchors:
 281//   top = top of screw
 282//   bot = bottom of screw
 283//   center = center of screw
 284//   head_top = top of head (same as top for headless screws)
 285//   head_bot = bottom of head (same as top for headless screws)
 286//   head_center = center of head (same as top for headless screws)
 287//   shaft_top = top of shaft
 288//   shaft_bot = bottom of shaft
 289//   shaft_center = center of shaft
 290//   shank_top = top of shank (invalid if screw is fully threaded)
 291//   shank_bot = bottom of shank (invalid if screw is fully threaded)
 292//   shank_center = center of shank (invalid if screw is fully threaded)
 293//   threads_top = top of threaded portion of screw (invalid if thread_len=0)
 294//   threads_bot = bottom of threaded portion of screw (invalid if thread_len=0)
 295//   threads_center = center of threaded portion of screw (invalid if thread_len=0)
 296// Example(Med): Selected UTS (English) screws
 297//   $fn=32;
 298//   xdistribute(spacing=8){
 299//     screw("#6", length=12);
 300//     screw("#6-32", head="button", drive="torx",length=12);
 301//     screw("#6-32,3/4", head="hex");
 302//     screw("#6", thread="fine", head="fillister",length=12, drive="phillips");
 303//     screw("#6", head="flat small",length=12,drive="slot");
 304//     screw("#6-32", head="flat large", length=12, drive="torx");
 305//     screw("#6-32", head="flat undercut",length=12);
 306//     screw("#6-24", head="socket",length=12);          // Non-standard threading
 307//     screw("#6-32", drive="hex", drive_size=1.5, length=12);
 308//   }
 309// Example(Med): A few examples of ISO (metric) screws
 310//   $fn=32;
 311//   xdistribute(spacing=8){
 312//     screw("M3", head="flat small",length=12);
 313//     screw("M3", head="button",drive="torx",length=12);
 314//     screw("M3", head="pan", drive="phillips",length=12);
 315//     screw("M3x1", head="pan", drive="slot",length=12);   // Non-standard threading!
 316//     screw("M3", head="flat large",length=12);
 317//     screw("M3", thread="none", head="flat", drive="hex",length=12);  // No threads
 318//     screw("M3", head="socket",length=12);
 319//     screw("M5,18", head="hex");
 320//   }
 321// Example(Med): Demonstration of all head types for UTS screws (using pitch zero for fast preview)
 322//   xdistribute(spacing=15){
 323//     ydistribute(spacing=15){
 324//        screw("1/4", thread=0,length=8, anchor=TOP, head="none", drive="hex");
 325//        screw("1/4", thread=0,length=8, anchor=TOP, head="none", drive="torx");
 326//        screw("1/4", thread=0,length=8, anchor=TOP, head="none", drive="slot");
 327//        screw("1/4", thread=0,length=8, anchor=TOP, head="none");
 328//     }
 329//     screw("1/4", thread=0, length=8, anchor=TOP, head="hex");
 330//     ydistribute(spacing=15){
 331//        screw("1/4", thread=0,length=8, anchor=TOP, head="socket", drive="hex");
 332//        screw("1/4", thread=0,length=8, anchor=TOP, head="socket", drive="torx");
 333//        screw("1/4", thread=0,length=8, anchor=TOP, head="socket");
 334//     }
 335//     ydistribute(spacing=15){
 336//        screw("1/4", thread=0,length=8, anchor=TOP, head="socket ribbed", drive="hex",$fn=32);
 337//        screw("1/4", thread=0,length=8, anchor=TOP, head="socket ribbed", drive="torx",$fn=32);
 338//        screw("1/4", thread=0,length=8, anchor=TOP, head="socket ribbed",$fn=24);
 339//     }
 340//     ydistribute(spacing=15){
 341//        screw("1/4", thread=0,length=8, anchor=TOP, head="button", drive="hex");
 342//        screw("1/4", thread=0,length=8, anchor=TOP, head="button", drive="torx");
 343//        screw("1/4", thread=0,length=8, anchor=TOP, head="button");
 344//     }
 345//     ydistribute(spacing=15){
 346//        screw("1/4", thread=0,length=8, anchor=TOP, head="round", drive="slot");
 347//        screw("1/4", thread=0,length=8, anchor=TOP, head="round", drive="phillips");
 348//        screw("1/4", thread=0,length=8, anchor=TOP, head="round");
 349//     }     
 350//     ydistribute(spacing=15){
 351//        screw("1/4", thread=0,length=8, anchor=TOP, head="pan", drive="slot");
 352//        screw("1/4", thread=0,length=8, anchor=TOP, head="pan", drive="phillips");
 353//        screw("1/4", thread=0,length=8, anchor=TOP, head="pan");
 354//     }
 355//     ydistribute(spacing=15){
 356//        screw("1/4", thread=0,length=8, anchor=TOP, head="fillister", drive="slot");
 357//        screw("1/4", thread=0,length=8, anchor=TOP, head="fillister", drive="phillips");
 358//        screw("1/4", thread=0,length=8, anchor=TOP, head="fillister");
 359//     }
 360//     ydistribute(spacing=15){
 361//        screw("1/4", thread=0,length=8, anchor=TOP, head="flat", drive="slot");
 362//        screw("1/4", thread=0,length=8, anchor=TOP, head="flat", drive="phillips");
 363//        screw("1/4", thread=0,length=8, anchor=TOP, head="flat", drive="hex");
 364//        screw("1/4", thread=0,length=8, anchor=TOP, head="flat", drive="torx");
 365//        screw("1/4", thread=0,length=8, anchor=TOP, head="flat large");
 366//        screw("1/4", thread=0,length=8, anchor=TOP, head="flat small");
 367//     }
 368//     ydistribute(spacing=15){
 369//        screw("1/4", thread=0,length=8, anchor=TOP, head="flat undercut", drive="slot");
 370//        screw("1/4", thread=0,length=8, anchor=TOP, head="flat undercut", drive="phillips");
 371//        screw("1/4", thread=0,length=8, anchor=TOP, head="flat undercut");
 372//     }
 373//     ydistribute(spacing=15){
 374//        screw("1/4", thread=0,length=8, anchor=TOP, head="flat 100", drive="slot");
 375//        screw("1/4", thread=0,length=8, anchor=TOP, head="flat 100", drive="phillips");
 376//        screw("1/4", thread=0,length=8, anchor=TOP, head="flat 100");
 377//     }
 378//   }
 379// Example(Med): Demonstration of all head types for metric screws without threading.
 380//   xdistribute(spacing=15){
 381//     ydistribute(spacing=15){
 382//       screw("M6x0", length=8, anchor=TOP,  head="none", drive="hex");
 383//       screw("M6x0", length=8, anchor=TOP,  head="none", drive="torx");
 384//       screw("M6x0", length=8, anchor=TOP,  head="none", drive="slot");
 385//       screw("M6x0", length=8, anchor=TOP);
 386//     }
 387//     screw("M6x0", length=8, anchor=TOP,  head="hex");
 388//     ydistribute(spacing=15){
 389//       screw("M6x0", length=8, anchor=TOP,  head="socket", drive="hex");
 390//       screw("M6x0", length=8, anchor=TOP,  head="socket", drive="torx");
 391//       screw("M6x0", length=8, anchor=TOP,  head="socket");
 392//     }
 393//     ydistribute(spacing=15){
 394//       screw("M6x0", length=8, anchor=TOP,  head="socket ribbed", drive="hex", $fn=32);
 395//       screw("M6x0", length=8, anchor=TOP,  head="socket ribbed", drive="torx", $fn=32);
 396//       screw("M6x0", length=8, anchor=TOP,  head="socket ribbed", $fn=32);
 397//     }
 398//     ydistribute(spacing=15){
 399//       screw("M6x0", length=8, anchor=TOP,  head="pan", drive="slot");
 400//       screw("M6x0", length=8, anchor=TOP,  head="pan", drive="phillips");
 401//       screw("M6x0", length=8, anchor=TOP,  head="pan", drive="torx");
 402//       screw("M6x0", length=8, anchor=TOP,  head="pan");
 403//       screw("M6x0", length=8, anchor=TOP,  head="pan flat");
 404//     }
 405//     ydistribute(spacing=15){
 406//       screw("M6x0", length=8, anchor=TOP,  head="button", drive="hex");
 407//       screw("M6x0", length=8, anchor=TOP,  head="button", drive="torx");
 408//       screw("M6x0", length=8, anchor=TOP,  head="button");
 409//     }
 410//     ydistribute(spacing=15){
 411//       screw("M6x0", length=8, anchor=TOP,  head="cheese", drive="slot");
 412//       screw("M6x0", length=8, anchor=TOP,  head="cheese", drive="phillips");
 413//       screw("M6x0", length=8, anchor=TOP,  head="cheese", drive="torx");
 414//       screw("M6x0", length=8, anchor=TOP,  head="cheese");
 415//     }
 416//     ydistribute(spacing=15){
 417//       screw("M6x0", length=8, anchor=TOP,  head="flat", drive="phillips");
 418//       screw("M6x0", length=8, anchor=TOP,  head="flat", drive="slot");
 419//       screw("M6x0", length=8, anchor=TOP,  head="flat", drive="hex");
 420//       screw("M6x0", length=8, anchor=TOP,  head="flat", drive="torx");
 421//       screw("M6x0", length=8, anchor=TOP,  head="flat small");
 422//       screw("M6x0", length=8, anchor=TOP,  head="flat large");
 423//     }
 424//   }
 425// Example: The three different English (UTS) screw tolerances (labeled on their heads)
 426//   module label(val)
 427//   {
 428//     difference(){
 429//        children();
 430//        yflip()linear_extrude(height=.35) text(val,valign="center",halign="center",size=8);
 431//     }
 432//   }
 433//   $fn=64;
 434//   xdistribute(spacing=15){
 435//     label("1") screw("1/4-20,5/8", head="hex",orient=DOWN,atype="head", anchor=TOP,tolerance="1A");  // Loose
 436//     label("2") screw("1/4-20,5/8", head="hex",orient=DOWN,atype="head", anchor=TOP,tolerance="2A");  // Standard
 437//     label("3") screw("1/4-20,5/8", head="hex",orient=DOWN,atype="head", anchor=TOP,tolerance="3A");  // Tight
 438//   }
 439// Example(2D,NoAxes): This example shows the gap between nut and bolt at the loosest tolerance for UTS.  This gap is what enables the parts to mesh without binding and is part of the definition for standard metal hardware.  Note that this gap is part of the standard definition for the metal hardware, not the 3D printing adjustment provided by the $slop parameter.  
 440//   $fn=32;
 441//   projection(cut=true)xrot(-90){
 442//       screw("1/4-20,3/8", head="hex",orient=UP,anchor=BOTTOM,tolerance="1A");
 443//       down(INCH*1/20*1.5) nut("1/4-20", thickness=8, nutwidth=0.5*INCH, tolerance="1B");
 444//   }
 445// Example: Here is a screw with nonstandard threading and a weird head size, which we create by modifying the screw structure:
 446//   spec = screw_info("M6x2,12",head="socket");
 447//   newspec = struct_set(spec,["head_size",20,"head_height",3]);
 448//   screw(newspec);
 449// Example: A bizarre custom screw with nothing standard about it.  If your screw is very strange, consider setting tolerance to zero so you get exactly the screw you defined.  You'll need to create your own clearance between mating threads in this case.  
 450//   spec = [["system","ISO"],
 451//           ["type","screw_info"],
 452//           ["pitch", 2.3],
 453//           ["head", "flat"],
 454//           ["head_size", 20],
 455//           ["head_size_sharp", 22],
 456//           ["head_angle", 60],
 457//           ["diameter",12],
 458//           ["length",22]];
 459//   screw(spec,tolerance=0);
 460
 461function _get_spec(spec, needtype, origin, thread,   // common parameters
 462                   head, drive, drive_size,          // screw parameters
 463                   shape, thickness                  // nut parameters
 464                  ) =
 465    assert(needtype=="screw_info" || needtype=="nut_info")
 466    assert(is_undef(thickness) || (is_num(thickness) && thickness>0) ||
 467           in_list(_downcase_if_str(thickness),["thin","normal","thick","undersized","din"]),
 468          "thickness must be a positive number of one of \"thin\", \"thick\", \"normal\", \"undersized\", or \"DIN\"")
 469    assert(!(is_undef(spec) && is_undef($screw_spec)), "No screw spec given and no parent spec available to inherit")
 470    let(
 471        spec=is_undef(spec) ? $screw_spec : spec,
 472        spec_origin = is_struct(spec) ? struct_val(spec,"origin") : undef
 473    )
 474    assert(is_string(spec) || is_struct(spec), "Screw/nut specification must be a string or struct")
 475    let(
 476        specname = is_struct(spec) ? struct_val(spec,"name") : undef,
 477        name = is_string(spec) ? spec
 478             : struct_val(spec,"type") != needtype ?       // if we switch between screw and nut we need a name 
 479                   let(specname=struct_val(spec,"name"))
 480                   assert(is_string(specname), 
 481                        "Parent screw_info or nut_info structure doesn't have a valid name, but a name is needed when child is of a different type")
 482               specname
 483             : undef,
 484        p = is_struct(spec) ? struct_val(spec,"pitch") : undef,
 485        thread = is_def(name) ? thread
 486                 // If the origin of the struct is a hole with pitch zero and we are making a screw, try to find a nonzero pitch
 487               : spec_origin=="screw_hole" && origin!="screw_hole" && p==0 && is_string(specname) ?
 488                    let(temp_info = screw_info(specname,thread))
 489                    struct_val(temp_info,"pitch")
 490//               : spec_origin=="screw_hole" && origin=="screw_hole" && all_positive([p]) ? p
 491//               : origin=="screw_hole" && is_undef(thread) ? 0
 492               : thread
 493    )
 494    is_def(name) ? (needtype=="screw_info" ? screw_info(name,_origin=origin, thread= origin=="screw_hole" ? default(thread,true) : thread,
 495                                                        head=head, drive=drive, drive_size=drive_size)
 496                                           : nut_info(name,_origin=origin, thread=thread, shape=shape, thickness=thickness))
 497  : 
 498    assert(in_list(struct_val(spec,"type"), ["nut_info","screw_info"]), "Screw/nut spec is invalid struct type")
 499    assert(is_undef(thread) || thread=="none" || thread==false || thread==true || is_num(thread),
 500           str("Thread type applied to struct specification must be numeric, \"none\" or false but got ",thread))
 501    assert(is_undef(thickness) || is_num(thickness), str("thickness applied to struct specification must be numeric but is ",thickness))
 502    assert(is_undef(head) || head=="none", str("The only head type allowed with struct specifications is \"none\" but got ",head))
 503    assert(num_defined([drive,drive_size])==0, "You cannot change drive or drive_size when using a struct specification")
 504    assert(is_undef(shape), "You cannot change nut shape when using a struct specification")
 505    let(
 506        spec = _struct_reset(spec,
 507                                   [ 
 508                                     ["origin", origin],
 509                                     if (origin=="screw") ["counterbore",0],
 510                                     if (head=="none") ["head","none"],
 511                                     if (head=="none") ["drive","none"],
 512                                     if (thread==false || thread=="none") ["pitch",0]
 513                                     else if (thread!=true) ["pitch",thread],
 514                                     ["thickness", thickness],
 515                                   ], grow=true),
 516        inherit = is_undef(spec_origin) || spec_origin==origin 
 517    )
 518    inherit ? spec
 519  : struct_remove(spec, ["shaft_oversize","head_oversize"]);
 520
 521
 522function _struct_reset(s, keyval, grow=true) =
 523  let(
 524      good = [for(kv=keyval) (grow || is_def(struct_val(s,kv[0]))) && is_def(kv[1])]
 525  )
 526  struct_set(s,flatten(bselect(keyval,good)));
 527
 528
 529function _nominal_diam(spec) = struct_val(spec,"diameter")+default(struct_val(spec,"shaft_oversize"),0);
 530                                                    
 531function screw(spec, head, drive, thread, drive_size, 
 532             length, l, thread_len, tolerance, details=true, 
 533             undersize, shaft_undersize, head_undersize,
 534             atype="screw",anchor, spin=0, orient=UP,
 535             _shoulder_diam=0, _shoulder_len=0,
 536             bevel,bevel1,bevel2,bevelsize,
 537             blunt_start,blunt_start1, blunt_start2,
 538             _internal=false, _counterbore, _teardrop=false)
 539   = no_function("screw");
 540module screw(spec, head, drive, thread, drive_size, 
 541             length, l, thread_len, tolerance, details=true, 
 542             undersize, shaft_undersize, head_undersize,
 543             atype="screw",anchor, spin=0, orient=UP,
 544             _shoulder_diam=0, _shoulder_len=0,
 545             bevel,bevel1,bevel2,bevelsize,
 546             blunt_start,blunt_start1, blunt_start2,
 547             _internal=false, _counterbore, _teardrop=false)
 548{
 549   tempspec = _get_spec(spec, "screw_info", _internal ? "screw_hole" : "screw",
 550                        thread=thread, head=head, drive=drive, drive_size=drive_size);
 551   undersize = is_num(undersize) ? [undersize,undersize]
 552             : undersize;
 553   dummyA=assert(is_undef(undersize) || is_vector(undersize,2), "Undersize must be a scalar or 2-vector")
 554          assert(is_undef(undersize) || num_defined([shaft_undersize, head_undersize])==0,
 555                 "Cannot combine \"undersize\" with other more specific undersize parameters");
 556   shaft_undersize = first_defined([shaft_undersize, undersize[0]]);
 557   head_undersize = first_defined([head_undersize, undersize[1]]);
 558   dummyB=assert(is_undef(shaft_undersize) || is_finite(shaft_undersize), "shaft_undersize must be a number")
 559          assert(is_undef(head_undersize) || is_finite(head_undersize), "head_undersize must be a number")
 560          assert(is_undef(_counterbore) || is_bool(_counterbore) || (is_finite(_counterbore) && _counterbore>=0),
 561                 "Counterbore must be a nonnegative number of boolean");
 562   l = one_defined([l,length],"l,length",dflt=undef);
 563   _counterbore = _counterbore==true ? struct_val(tempspec,"head_height") 
 564                : _counterbore==false ? undef
 565                : _counterbore;
 566   head = struct_val(tempspec,"head");
 567   headless = head=="none";
 568   flathead = is_def(head) && starts_with(head,"flat");
 569   reset_headsize = _internal && flathead ? struct_val(tempspec,"head_size_sharp") : undef;
 570   spec=_struct_reset(tempspec,[
 571                                ["length", l],
 572                                ["shaft_oversize", u_mul(-1,shaft_undersize)],
 573                                ["head_oversize", u_mul(-1,head_undersize)],
 574                                ["counterbore", _counterbore],
 575                                ["thread_len", thread_len],
 576                                ["head_size", reset_headsize],
 577                               ]);
 578   dummy = _validate_screw_spec(spec);
 579   $screw_spec = spec;
 580   pitch =  struct_val(spec, "pitch") ;
 581   threadspec = pitch==0 ? undef : thread_specification(spec, internal=_internal, tolerance=tolerance);
 582   nominal_diam = _nominal_diam(spec);
 583   d_major = pitch==0 ? nominal_diam : mean(struct_val(threadspec, "d_major"));
 584   length = struct_val(spec,"length");
 585   counterbore = default(struct_val(spec,"counterbore"),0);
 586   user_thread_len = struct_val(spec,"thread_len");
 587   dummyC = assert(in_list(atype,["shaft","head","shank","threads","screw","shoulder"]),str("Unknown anchor type: \"",atype,"\""))
 588            assert(is_finite(length) && length>0, "Must specify positive screw length")
 589            assert(is_finite(_shoulder_len) && _shoulder_len>=0, "Must specify a nonegative shoulder length")
 590            assert(is_finite(_shoulder_diam) && _shoulder_diam>=0, "Must specify nonnegative shoulder diameter")
 591            assert(is_undef(user_thread_len) || (is_finite(user_thread_len) && user_thread_len>=0), "Must specify nonnegative thread length")
 592            assert(!_teardrop || pitch==0);
 593   sides = max(pitch==0 ? 3 : 12, segs(nominal_diam/2));
 594   head_height = headless || flathead ? 0 
 595               : counterbore==true || is_undef(counterbore) || counterbore==0 ? struct_val(spec, "head_height")
 596               : counterbore;
 597   head_diam = struct_val(spec, "head_size",0) + struct_val(spec, "head_oversize",0);
 598   flat_height = !flathead ? 0 
 599               : let( given_height = struct_val(spec, "head_height"))
 600                 all_positive(given_height) ? given_height
 601               : (struct_val(spec,"head_size_sharp")+struct_val(spec,"head_oversize",0)-d_major)/2/tan(struct_val(spec,"head_angle")/2);
 602   flat_cbore_height = flathead && is_num(counterbore) ? counterbore : 0;
 603
 604   blunt_start1 = first_defined([blunt_start1,blunt_start,true]);
 605   blunt_start2 = first_defined([blunt_start2,blunt_start,true]);
 606
 607   shoulder_adj = _shoulder_len>0 ? flat_height:0;  // Adjustment because flathead height doesn't count toward shoulder length
 608   shoulder_full = _shoulder_len==0 ? 0 : _shoulder_len + flat_height;
 609   shank_len = is_def(user_thread_len) ? length - user_thread_len - (_shoulder_len==0?flat_height:0) : 0;
 610   thread_len = is_def(user_thread_len) ? user_thread_len
 611              : length - (_shoulder_len==0?flat_height:0);
 612   dummyD = assert(!(atype=="shank" && shank_len==0), "Specified atype of \"shank\" but screw has no shank (thread_len not given or it equals shaft length)")
 613            assert(!(atype=="shoulder" && _shoulder_len==0), "Specified atype of \"shoulder\" but screw has no shoulder")
 614            assert(!(atype=="threads" && thread_len==0), "Specified atype of \"threads\" but screw has no threaded part (thread_len=0)")
 615            assert(!(atype=="head" && headless), "You cannot anchor headless screws with atype=\"head\"");
 616   eps_gen = 0.01;
 617   eps_shoulder = headless && !_internal ? 0 : eps_gen;
 618   eps_shank = headless && !_internal && _shoulder_len==0 ? 0 : eps_gen;
 619   eps_thread = headless && !_internal && shank_len==0 && _shoulder_len==0 ? 0 : eps_gen;
 620   dummyL = assert(_shoulder_len>0 || is_undef(flat_height) || flat_height < length,
 621                   str("Length of screw (",length,") is shorter than the flat head height (",flat_height,")"));
 622   offset = atype=="head" ? (-head_height+flat_height-flat_cbore_height)/2
 623          : atype=="shoulder" ? _shoulder_len/2 + flat_height
 624          : atype=="shaft" ? _shoulder_len + (length+flat_height+shoulder_adj)/2
 625          : atype=="shank" ? _shoulder_len + (length-thread_len+flat_height+shoulder_adj)/2
 626          : atype=="threads" ? _shoulder_len + shoulder_adj + length-thread_len + thread_len/2
 627          : atype=="screw" ? (length-head_height+_shoulder_len+shoulder_adj-flat_cbore_height)/2
 628          : assert(false,"Unknown atype");
 629   dummyM = //assert(!headless || !in_list(anchor,["head_top","head_bot","head_center"]), str("Anchor \"",anchor,"\" not allowed for headless screw"))
 630            assert(shank_len>0 || !in_list(anchor,["shank_top","shank_bot","shank_center"]),
 631                   str("Screw has no unthreaded shank so anchor \"",anchor,"\" is not allowed"));
 632   anchor_list = [
 633          named_anchor("top", [0,0,offset+head_height+flat_cbore_height]),
 634          named_anchor("bot", [0,0,-length-shoulder_full+offset]),
 635          named_anchor("center", [0,0, -length/2 - shoulder_full/2 + head_height/2 + offset]),
 636          named_anchor("head_top", [0,0,head_height+offset]),
 637          named_anchor("head_bot", [0,0,-flat_height+offset]),
 638          named_anchor("head_center", [0,0,(head_height-flat_height)/2+offset]),
 639          if (_shoulder_len>0) named_anchor("shoulder_top", [0,0,offset-flat_height]),
 640          if (_shoulder_len>0) named_anchor("shoulder_bot", [0,0,offset-shoulder_full]),
 641          if (_shoulder_len>0) named_anchor("shoulder_center", [0,0,offset-flat_height-_shoulder_len/2]),
 642          named_anchor("shaft_top", [0,0,-_shoulder_len-flat_height+offset]),
 643          named_anchor("shaft_bot", [0,0,-length-shoulder_full+offset]),
 644          named_anchor("shaft_center", [0,0,(-_shoulder_len-flat_height-length-shoulder_full)/2+offset]),
 645          if (shank_len>0) named_anchor("shank_top", [0,0,-_shoulder_len-flat_height+offset]),
 646          if (shank_len>0) named_anchor("shank_bot", [0,0,-shank_len-_shoulder_len-flat_height+offset]),
 647          if (shank_len>0) named_anchor("shank_center", [0,0,-shank_len/2-_shoulder_len-flat_height+offset]),
 648          named_anchor("threads_top", [0,0,-shank_len-_shoulder_len-flat_height+offset]),
 649          named_anchor("threads_bot", [0,0,-length-shoulder_full+offset]),
 650          named_anchor("threads_center", [0,0,(-shank_len-length-_shoulder_len-shoulder_full-flat_height)/2+offset])
 651   ];
 652   rad_scale = _internal? (1/cos(180/sides)) : 1;
 653   islop = _internal ? 4*get_slop() : 0;
 654   vnf = head=="hex" && atype=="head" && counterbore==0 ? linear_sweep(hexagon(id=head_diam*rad_scale),height=head_height,center=true) : undef;
 655   head_diam_full = head=="hex" ? 2*head_diam/sqrt(3) : head_diam;
 656   attach_d = in_list(atype,["threads","shank","shaft"]) ? d_major 
 657            : atype=="screw" ? max(d_major,_shoulder_diam,default(head_diam_full,0))
 658            : atype=="shoulder" ? _shoulder_diam
 659            : is_def(vnf) ? undef
 660            : head_diam_full;
 661   attach_l = atype=="shaft" ? length-(_shoulder_len>0?0:flat_height)
 662            : atype=="shoulder" ? _shoulder_len
 663            : atype=="shank" ? shank_len
 664            : atype=="threads" ? thread_len
 665            : atype=="screw" ? length+head_height+shoulder_full + flat_cbore_height
 666            : is_def(vnf) ? undef
 667            : head_height+flat_height+flat_cbore_height;
 668   bevelsize = default(bevelsize, d_major/12);
 669   bevel1 = first_defined([bevel1,bevel,true]);
 670   bevel2 = first_defined([bevel2,bevel,headless && _shoulder_len==0 && shank_len==0]);
 671   attachable(
 672              vnf = vnf, 
 673              d = u_add(u_mul(attach_d, rad_scale), islop),
 674              l = attach_l,
 675              orient = orient,
 676              anchor = anchor,
 677              spin = spin,
 678              anchors=anchor_list)
 679   {
 680     up(offset)
 681       difference(){
 682         union(){
 683           screw_head(spec,details,counterbore=counterbore,flat_height=flat_height,
 684                      slop=islop,teardrop=_teardrop);
 685           if (_shoulder_len>0)
 686             up(eps_shoulder-flat_height){
 687               if (_teardrop)
 688                 teardrop(d=_shoulder_diam*rad_scale+islop, h=_shoulder_len+eps_shoulder, anchor=FRONT, orient=BACK, $fn=sides);
 689               else
 690                 cyl(d=_shoulder_diam*rad_scale+islop, h=_shoulder_len+eps_shoulder, anchor=TOP, $fn=sides, chamfer1=details ? _shoulder_diam/30:0);
 691             }
 692           if (shank_len>0 || pitch==0){
 693             L = pitch==0 ? length - (_shoulder_len==0?flat_height:0) : shank_len;
 694             bevsize = (_internal ? -1 : 1)*bevelsize;
 695             bev1 = pitch!=0 ? 0
 696                  : bevel1==true ? bevsize
 697                  : bevel1==false ? 0
 698                  : bevel1=="reverse" ? -bevsize
 699                  : bevel1;
 700             bev2 = pitch!=0 ? 0
 701                  : bevel2==true ? bevsize
 702                  : bevel2==false ? 0
 703                  : bevel2=="reverse" ? -bevsize
 704                  : bevel2;
 705             down(_shoulder_len+flat_height-eps_shank)
 706               if (_teardrop)
 707                 teardrop(d=d_major*rad_scale+islop, h=L+eps_shank, anchor=FRONT, orient=BACK, $fn=sides, chamfer1=bev1, chamfer2=bev2);
 708               else
 709                 cyl(d=d_major*rad_scale+islop, h=L+eps_shank, anchor=TOP, $fn=sides, chamfer1=bev1, chamfer2=bev2);
 710           }
 711           if (thread_len>0 && pitch>0){
 712             down(_shoulder_len+flat_height+shank_len-eps_thread)
 713                   threaded_rod([mean(struct_val(threadspec, "d_minor")),
 714                                 mean(struct_val(threadspec, "d_pitch")),
 715                                 d_major], 
 716                      pitch = struct_val(threadspec, "pitch"),
 717                      l=thread_len+eps_thread, left_handed=false, internal=_internal, 
 718                      bevel1=bevel1,
 719                      bevel2=bevel2,
 720                      blunt_start=blunt_start, blunt_start1=blunt_start1, blunt_start2=blunt_start2, 
 721                      $fn=sides, anchor=TOP);
 722            }
 723             
 724         }
 725         if (!_internal) _driver(spec);
 726       }
 727     children();
 728   }  
 729}
 730
 731
 732
 733// Module: screw_hole()
 734// Synopsis: Creates a screw hole.
 735// SynTags: Geom
 736// Topics: Threading, Screws
 737// See Also: screw()
 738// Usage:
 739//   screw_hole([spec], [head], [thread=], [length=|l=], [oversize=], [hole_oversize=], [teardrop=], [head_oversize], [tolerance=], [$slop=], [blunt_start=], [anchor=], [atype=], [orient=], [spin=]) [ATTACHMENTS];
 740// Description:
 741//   Create a screw hole mask.  See [screw and nut parameters](#section-screw-and-nut-parameters) for details on the parameters that define a screw.
 742//   The screw hole can be threaded to receive a screw or it can be an unthreaded clearance hole.  
 743//   The tolerance determines the dimensions of the screw
 744//   based on ISO and ASME standards.  Screws fabricated at those dimensions will mate properly with standard hardware.
 745//   The $slop argument makes the hole larger by 4*$slop to account for printing overextrusion.  It defaults to 0.
 746//   .
 747//   You can generate a screw specification from {{screw_info()}}, possibly create a modified version, and pass that in rather than giving the parameters.
 748//   .
 749//   The tolerance should be a nut tolerance for a threaded hole or a clearance hole tolerance for clearance holes.
 750//   For clearance holes, the UTS tolerances are "normal", "loose" and "close".  ASME also specifies the same naming for metric clearance holes.
 751//   However, ISO gives "fine", "medium" and "coarse" instead.  This function accepts all of these in either system.  It also takes "tight" to be equivalent to "close",
 752//   even though no standard suggests it, because it's a natural opposite of "loose".  The official tolerance designations for ISO are "H12" for "fine", "H13" for "medium"
 753//   and "H14" for "coarse".  These designations will also work, but only for metric holes.  You can also set tolerance to 0 or "none" to produce holes at the nominal size.
 754//   .
 755//   If you want to produce holes for tapping you can use a tolerance of "tap".  This produces a hole of the nominal screw diameter reduced by the thread pitch.  You may still
 756//   need to adjust $slop for best results.  Some people screw machine screws directly into plastic without tapping.  This works better with a somewhat larger hole, so
 757//   a tolerance of "self tap" produces such a hole.  Note that this tolerance also makes the default bevel2=true to bevel the top, which makes it much easier
 758//   to start the screw.  The "self tap" tolerance subtracts `0.72 * pitch` when pitch is below 1mm, `0.6 * pitch` when the pitch is over 1.5mm, and it interpolates between.
 759//   It was tested in PLA with a Prusa MK3S and $slop=0.05 and worked on UTS screws from #2 up to 1/2 inch.  
 760//   .
 761//   The counterbore parameter adds a cylindrical clearance hole above the screw shaft.  For flat heads it extends above the flathead and for other screw types it 
 762//   replaces the head with a cylinder large enough in diameter for the head to fit.  For a flat head you must specify the length of the counterbore.  For other heads you can
 763//   set counterbore to true and it will be sized to match the head height.  The counterbore will extend 0.01 above the TOP of the hole mask to ensure no
 764//   problems with differences.  Note that the counterbore defaults to true for non-flathead screws.  If you want the actual head shape to appear, set counterbore to zero.
 765//   .
 766//   For 3d printing circular holes can be problematic.  One solution is to use octagonal holes, setting $fn=8.  Another option is to use a teardrop hole, which
 767//   can be accomplished by setting `teardrop=true`.  The point of the teardrop will point in the Y direction (BACK) so you will need to ensure that you orient it
 768//   correctly in your final model.  
 769//   .
 770//   Anchoring for screw_hole() is the same as anchoring for {{screw()}}, with all the same anchor types and named anchors.  If you specify a counterbore it is treated as
 771//   the "head", or in the case of flat heads, it becomes part of the head.  If you make a teardrop hole the point is ignored for purposes of anchoring.
 772// Arguments:
 773//   spec = screw specification, e.g. "M5x1" or "#8-32".  See [screw naming](#subsection-screw-naming).  This can also be a screw specification structure of the form produced by {{screw_info()}}.  
 774//   head = head type.  See [screw heads](#subsection-screw-heads)  Default: none
 775//   ---
 776//   thread = thread type or specification for threaded masks, true to make a threaded mask with the standard threads, or false to make an unthreaded mask.  See [screw pitch](#subsection-standard-screw-pitch). Default: false
 777//   teardrop = if true produce teardrop hole.  Only compatible with clearance holes, not threaded.  Default: false
 778//   oversize = amount to increase diameter of the screw hole (hole and countersink).  A scalar or length 2 vector.  Default: use computed tolerance
 779//   hole_oversize = amount to increase diameter of the hole.  Overrides the use of tolerance and replaces any settings given in the screw specification. 
 780//   head_oversize = amount to increase diameter of head.  Overrides the user of tolerance and replaces any settings given in the screw specification.  
 781//   length / l= length of screw (in mm)
 782//   counterbore = set to length of counterbore, or true to make a counterbore equal to head height.  Default: false for flat heads and headless, true otherwise
 783//   tolerance = threading or clearance hole tolerance.  For internal threads, detrmines actual thread geometry based on nominal sizing.  See [tolerance](#subsection-tolerance). Default is "2B" for UTS and 6H for ISO.  For clearance holes, determines how much clearance to add.  Default is "normal".  
 784//   bevel = if true create bevel at both ends of hole.  Default: see below
 785//   bevel1 = if true create bevel at bottom end of hole.  Default: false
 786//   bevel2 = if true create bevel at top end of hole.     Default: true when tolerance="self tap", false otherwise
 787//   blunt_start = if true and hole is threaded, create blunt start threads.  Default: true
 788//   blunt_start1 = if true and hole is threaded, create blunt start threads at bottom end.
 789//   blunt_start2 = if true and hole is threaded, create blunt start threads top end.
 790//   $slop = add extra gap to account for printer overextrusion.  Default: 0
 791//   atype = anchor type, one of "screw", "head", "shaft", "threads", "shank"
 792//   anchor = Translate so anchor point on the shaft is at origin (0,0,0).  See [anchor](attachments.scad#subsection-anchor).  Default: `CENTER`
 793//   spin = Rotate this many degrees around the Z axis after anchor.  See [spin](attachments.scad#subsection-spin).  Default: `0`
 794//   orient = Vector to rotate top towards, after spin.  See [orient](attachments.scad#subsection-orient).  Default: `UP`
 795// Side Effects:
 796//   `$screw_spec` is set to the spec specification structure. 
 797// Anchor Types:
 798//   screw = the entire screw (default)
 799//   head = screw head (invalid for headless screws)
 800//   shaft = screw shaft
 801//   shank = unthreaded section of shaft (invalid if screw is fully threaded)
 802//   threads = threaded section of screw     
 803// Extra Anchors:
 804//   top = top of screw
 805//   bot = bottom of screw
 806//   center = center of screw
 807//   head_top = top of head (invalid for headless screws)
 808//   head_bot = bottom of head (invalid for headless screws)
 809//   head_center = center of head (invalid for headless screws)
 810//   shaft_top = top of shaft
 811//   shaft_bot = bottom of shaft
 812//   shaft_center = center of shaft
 813//   shank_top = top of shank (invalid if screw is fully threaded)
 814//   shank_bot = bottom of shank (invalid if screw is fully threaded)
 815//   shank_center = center of shank (invalid if screw is fully threaded)
 816//   threads_top = top of threaded portion of screw (invalid if thread_len=0)
 817//   threads_bot = bottom of threaded portion of screw (invalid if thread_len=0)
 818//   threads_center = center of threaded portion of screw (invalid if thread_len=0)
 819// Example: Counterbored clearance hole
 820//   diff()
 821//     cuboid(20)
 822//       attach(TOP)
 823//         screw_hole("1/4-20,.5",head="socket",counterbore=5,anchor=TOP);
 824// Example: Clearance hole for flathead 
 825//   diff()
 826//     cuboid(20)
 827//       attach(TOP)
 828//          screw_hole("1/4-20,.5",head="flat",counterbore=0,anchor=TOP);
 829// Example: Threaded hole, with inward bevel at the base
 830//   bottom_half()
 831//     diff()
 832//       cuboid(20)
 833//         attach(FRONT)
 834//           screw_hole("M16,15",anchor=TOP,thread=true,bevel1="reverse");
 835function screw_hole(spec, head, thread, oversize, hole_oversize, head_oversize, 
 836             length, l, thread_len, tolerance=undef, counterbore, teardrop=false,
 837             bevel, bevel1, bevel2, blunt_start, blunt_start1, blunt_start2, 
 838             atype="screw",anchor=CENTER,spin=0, orient=UP)
 839    = no_function("screw_hole");
 840module screw_hole(spec, head, thread, oversize, hole_oversize, head_oversize, 
 841             length, l, thread_len, tolerance=undef, counterbore, teardrop=false,
 842             bevel, bevel1, bevel2, blunt_start, blunt_start1, blunt_start2, 
 843             atype="screw",anchor=CENTER,spin=0, orient=UP)
 844{
 845   screwspec = _get_spec(spec, "screw_info", "screw_hole", 
 846                        thread=thread, head=head);
 847   bevel1 = first_defined([bevel1,bevel,false]);
 848   bevel2 = first_defined([bevel2,bevel,tolerance=="self tap"]);
 849   thread = default(thread,false);
 850   checkhead = struct_val(screwspec,"head");
 851   default_counterbore = checkhead=="none" || starts_with(checkhead,"flat") ? 0 : true;
 852   counterbore = default(counterbore, default_counterbore);
 853   dummy = _validate_screw_spec(screwspec);
 854   threaded = thread==true || (is_finite(thread) && thread>0) || (is_undef(thread) && struct_val(screwspec,"pitch")>0);
 855   dummy2 = assert(!threaded || !teardrop, "Cannot make threaded teardrop holes");
 856   oversize = force_list(oversize,2);
 857   hole_oversize = first_defined([hole_oversize, oversize[0],struct_val(screwspec,"shaft_oversize")]);
 858   head_oversize = first_defined([head_oversize, oversize[1],struct_val(screwspec,"head_oversize")]);
 859   if (threaded || is_def(hole_oversize) || tolerance==0 || tolerance=="none") {
 860     default_tag("remove")
 861       screw(spec,head=head,thread=thread,shaft_undersize=u_mul(-1,hole_oversize), head_undersize=u_mul(-1,head_oversize),
 862             blunt_start=blunt_start, blunt_start1=blunt_start1, blunt_start2=blunt_start2, 
 863             length=length,l=l,thread_len=thread_len, tolerance=tolerance, _counterbore=counterbore,
 864             bevel1=bevel1, bevel2=bevel2, 
 865             atype=atype, anchor=anchor, spin=spin, orient=orient, _internal=true, _teardrop=teardrop)
 866         children();
 867   }
 868   else {
 869     tolerance = default(tolerance, "normal");
 870     pitch = struct_val(screwspec,"pitch");
 871     dummy3 = assert((downcase(tolerance) != "tap" && downcase(tolerance)!="self tap") || pitch!=0,
 872                     "\"tap\" clearance requires a pitch size, but pitch is set to zero");
 873     // UTS clearances from ASME B18.2.8
 874     UTS_clearance = [
 875       [ // Close fit
 876         [0.1120 * INCH,0.008*INCH],
 877         [0.1250 * INCH, 1/64*INCH],
 878         [7/16   * INCH, 1/64*INCH],
 879         [1/2    * INCH, 1/32*INCH],
 880         [1.25   * INCH, 1/32*INCH],
 881         [1.375  * INCH, 1/16*INCH]
 882       ],
 883       [ // Normal fit
 884         [0.1120 * INCH, 1/64*INCH],
 885         [0.1250 * INCH, 1/32*INCH],
 886         [7/16   * INCH, 1/32*INCH],
 887         [1/2    * INCH, 1/16*INCH],
 888         [7/8    * INCH, 1/16*INCH],
 889         [1      * INCH, 3/32*INCH],
 890         [1.25   * INCH, 3/32*INCH],
 891         [1.375  * INCH,  1/8*INCH],
 892       ],
 893       [ // Loose fit
 894         [0.1120 * INCH, 1/32*INCH],
 895         [0.1250 * INCH, 3/64*INCH],
 896         [7/16   * INCH, 3/64*INCH],
 897         [1/2    * INCH, 7/64*INCH],
 898         [5/8    * INCH, 7/64*INCH],
 899         [3/4    * INCH, 5/32*INCH],
 900         [1      * INCH, 5/32*INCH],
 901         [1.125  * INCH, 3/16*INCH],
 902         [1.25   * INCH, 3/16*INCH],
 903         [1.375  * INCH,15/64*INCH]
 904       ]
 905     ];
 906     // ISO clearances appear in ASME B18.2.8 and ISO 273
 907     ISO_clearance = [
 908       [ // Close, Fine, H12 
 909         [2.5, 0.1],
 910         [3.5, 0.2],
 911         [4,   0.3],
 912         [5,   0.3],
 913         [6,   0.4],
 914         [8,   0.4],
 915         [10,  0.5],
 916         [12,  1],
 917         [42,  1],
 918         [48,  2],
 919         [80,  2],
 920         [90,  3],
 921         [100, 4],
 922       ],
 923       [  // Normal, Medium, H13
 924         [1.6, 0.2],
 925         [2,   0.4],
 926         [3.5, 0.4],
 927         [4,   0.5],
 928         [5,   0.5],
 929         [6,   0.6],
 930         [8,   1],
 931         [10,  1],
 932         [12,  1.5],
 933         [16,  1.5],
 934         [20,  2],
 935         [24,  2],
 936         [30,  3],
 937         [42,  3],
 938         [48,  4],
 939         [56,  6],
 940         [90,  6],
 941         [100, 7],
 942       ],
 943       [  // Loose, Coarse, H14
 944         [1.6, 0.25],
 945         [2,   0.3],
 946         [3,   0.6],
 947         [3.5, 0.7],
 948         [4,   0.8],
 949         [5,   0.8],
 950         [6,   1],
 951         [8,   2],
 952         [10,  2],
 953         [12,  2.5],
 954         [16,  2.5],
 955         [20,  4],
 956         [24,  4],
 957         [30,  5],
 958         [36,  6],
 959         [42,  6],
 960         [48,  8],
 961         [56, 10],
 962         [72, 10],
 963         [80, 11],
 964         [90, 11],
 965         [100,12],
 966       ]
 967     ];
 968     tol_ind = in_list(downcase(tolerance), ["close", "fine", "tight"]) ? 0
 969             : in_list(downcase(tolerance), ["normal", "medium", "tap", "self tap"]) ? 1
 970             : in_list(downcase(tolerance), ["loose", "coarse"]) ? 2
 971             : in_list(tolerance, ["H12","H13","H14"]) ?
 972                   assert(struct_val(screwspec,"system")=="ISO", str("Hole tolerance ", tolerance, " only allowed with ISO screws"))
 973                   parse_int(substr(tolerance,1))
 974             : assert(false,str("Unknown tolerance ",tolerance, " for clearance hole"));
 975     tol_table = struct_val(screwspec,"system")=="UTS" ? UTS_clearance[tol_ind] : ISO_clearance[tol_ind];
 976     tol_gap = lookup(_nominal_diam(screwspec), tol_table);
 977     // If we got here, hole_oversize is undefined and oversize is undefined
 978     hole_oversize = downcase(tolerance)=="tap" ? -pitch
 979                   : downcase(tolerance)=="self tap" ? -pitch*lookup(pitch,[[1,0.72],[1.5,.6]])
 980                   : tol_gap;
 981     head_oversize = default(head_oversize, tol_gap);
 982     default_tag("remove")     
 983       screw(spec,head=head,thread=0,shaft_undersize=-hole_oversize, head_undersize=-head_oversize, 
 984             length=length,l=l,thread_len=thread_len, _counterbore=counterbore,
 985             bevel1=bevel1, bevel2=bevel2, bevelsize=pitch>0?pitch:undef,
 986             atype=atype, anchor=anchor, spin=spin, orient=orient, _internal=true, _teardrop=teardrop)
 987         children();
 988   }
 989} 
 990
 991// Module: shoulder_screw()
 992// Synopsis: Creates a shoulder screw.
 993// SynTags: Geom
 994// Topics: Threading, Screws
 995// See Also: screw(), screw_hole()
 996// Usage:
 997//   shoulder_screw(s, d, length, [head=], [thread_len=], [tolerance=], [head_size=], [drive=], [drive_size=], [thread=], [undersize=], [shaft_undersize=], [head_undersize=], [shoulder_undersize=],[atype=],[anchor=],[orient=],[spin=]) [ATTACHMENTS];
 998// Description:
 999//   Create a shoulder screw.  See [screw and nut parameters](#section-screw-and-nut-parameters) for details on the parameters that define a screw.
1000//   The tolerance determines the dimensions of the screw
1001//   based on ISO and ASME standards.  Screws fabricated at those dimensions will mate properly with standard hardware.
1002//   Note that the $slop argument does not affect the size of screws: it only adjusts screw holes.  This will work fine
1003//   if you are printing both parts, but if you need to mate printed screws to metal parts you may need to adjust the size
1004//   of the screws, which you can do with the undersize arguments.
1005//   .
1006//   Unlike a regular screw, a shoulder screw is based on its shoulder dimensions: diameter and length.  The ISO and ASME standards
1007//   specify for a given shoulder diameter the thread size and even the length of the threads.  Note that these standards specify only
1008//   a small range of sizes.  You can specify a shoulder screw by giving the system, either "ISO" or "UTS" and the shoulder diameter
1009//   and length, and shoulder_screw() will supply the other parameters.
1010//   .
1011//   Hardware sources like McMaster sell many screws that don't comply with the standards.  If you want to make such a screw then
1012//   you can specify parameters like thread_len, the length of the threaded portion below the shoulder, and you can choose a different head
1013//   type.  You will need to specify the size of the head, since it cannot be looked up in tables.  You can also 
1014//   generate a screw specification from {{screw_info()}}, possibly create a modified version using {{struct_set()}}, and pass that in rather than giving the parameters.
1015//   .
1016//   The anchors and anchor types are the same as for {{screw()}} except that there is an anchor type for the shoulder and an additional set of named anchors
1017//   refering to parts of the shoulder.  
1018// Arguments:
1019//   s = screw system to use, case insensitive, either "ISO", "UTS", "english" or "metric", or a screw name or specification.  See [screw naming](#subsection-screw-naming).
1020//   d = nominal shoulder diameter in mm for ISO or inches for UTS
1021//   length = length of the shoulder (in mm)
1022//   ---
1023//   thread_len = length of threads
1024//   tolerance = screw tolerance.  Determines actual screw thread geometry based on nominal sizing.  See [tolerance](#subsection-tolerance). Default is "2A" for UTS and "6g" for ISO.
1025//   drive = drive type.  See [screw heads](#subsection-screw-heads) set to "none" for no drive.  Default: "hex"
1026//   drive_size = size of the drive recess
1027//   thread = thread type or specification. See [screw pitch](#subsection-standard-screw-pitch). Default: "coarse"
1028//   spec = screw specification to define the thread size 
1029//   head_size = scalar or vector to give width or [width, height].  If you only give width, height is computed using a formula for socket heads.  For flat head screws the second value in the vector is the sharp size; if you don't give it then the sharp size will be 12% more than the given size
1030// Side Effects:
1031//   `$screw_spec` is set to the spec specification structure. 
1032// Anchor Types:
1033//   screw = the entire screw (default)
1034//   head = screw head (invalid for headless screws)
1035//   shoulder = the shoulder
1036//   shaft = screw shaft
1037//   threads = threaded section of screw     
1038// Extra Anchors:
1039//   top = top of screw
1040//   bot = bottom of screw
1041//   center = center of screw
1042//   head_top = top of head (invalid for headless screws)
1043//   head_bot = bottom of head (invalid for headless screws)
1044//   head_center = center of head (invalid for headless screws)
1045//   shoulder_top = top of shoulder
1046//   shoulder_bot = bottom of shoulder
1047//   shoulder_center = center of shoulder
1048//   shaft_top = top of shaft
1049//   shaft_bot = bottom of shaft
1050//   shaft_center = center of shaft
1051//   threads_top = top of threaded portion of screw (invalid if thread_len=0)
1052//   threads_bot = bottom of threaded portion of screw (invalid if thread_len=0)
1053//   threads_center = center of threaded portion of screw (invalid if thread_len=0)
1054// Example: ISO shoulder screw
1055//   shoulder_screw("iso",10,length=20);
1056// Example: English shoulder screw
1057//   shoulder_screw("english",1/2,length=20);
1058// Example: Custom example.  You must specify thread_len and head_size when creating custom configurations.  
1059//   shoulder_screw("M6", 9.3, length=17, thread_len=8, head_size=14);
1060// Example: Another custom example:
1061//   shoulder_screw("M6", 9.3, length=17, thread_len=8, head_size=14, head="button", drive="torx");
1062// Example: Threadless 
1063//   shoulder_screw("iso",10,length=15,thread=0);
1064// Example: No drive recess
1065//   shoulder_screw("iso",10,length=15,drive="none");
1066// Example: Headless
1067//   shoulder_screw("iso", 16, length=20, head="none");
1068// Example: Changing head height
1069//   shoulder_screw("iso", 16, length=20, head_size=[24,5]);
1070function shoulder_screw(s,d,length,head, thread_len, tolerance, head_size, drive, drive_size, thread,
1071                      undersize, shaft_undersize, head_undersize, shoulder_undersize=0,
1072                      blunt_start, blunt_start1, blunt_start2, 
1073                      atype="screw", anchor=BOT, orient,spin) = no_function("shoulder_screw");
1074module shoulder_screw(s,d,length,head, thread_len, tolerance, head_size, drive, drive_size, thread,
1075                      undersize, shaft_undersize, head_undersize, shoulder_undersize=0,
1076                      blunt_start, blunt_start1, blunt_start2, 
1077                      atype="screw", anchor=BOT, orient,spin)
1078{
1079  d1= assert(is_num(d) && d>0, "Must specify shoulder diameter")
1080      assert (is_num(length) && length>0, "Must specify shoulder length");
1081  systemOK=is_string(s) && in_list(downcase(s),["iso","metric","uts","english"]);
1082  info_temp = systemOK ? undef
1083            : is_struct(s) ? s
1084            : screw_info(s);
1085  infoOK = systemOK ? false
1086         : _nominal_diam(info_temp) && struct_val(info_temp,"pitch") && struct_val(info_temp,"system");
1087  d2=assert(systemOK || infoOK, "System must be \"ISO\", \"UTS\", \"English\" or \"metric\" or a valid screw specification string")
1088     assert(!is_struct(s) || num_defined([drive, drive_size, thread, head])==0,
1089            "With screw struct, \"head\", \"drive\", \"drive_size\" and \"thread\" are not allowed");
1090  drive = drive=="none" ? undef : default(drive,"hex");
1091  thread = default(thread,"coarse");
1092  head = default(head, "socket");                                    
1093  usersize = systemOK ? undef : s;
1094  system = systemOK ? s : struct_val(info_temp,"system");
1095  undersize = is_undef(undersize) ? undersize
1096            : is_num(undersize) ? [undersize,undersize]
1097            : undersize;
1098  shaft_undersize = first_defined([shaft_undersize, undersize[0], 0]);
1099  head_undersize = first_defined([head_undersize, undersize[1], 0]);
1100  
1101  iso = in_list(downcase(system), ["iso","metric"]);
1102
1103  factor = iso ? 1 : INCH;
1104
1105  table = iso ?   //  iso shoulder screws, hex drive socket head  ISO 7379
1106                  //  Mcmaster has variations like 12mm shoulder for m10, 6mm shoulder for M5
1107                  // shld   screw  thread  head  hex  hex     head  
1108                  // diam   size   length  diam      depth     ht 
1109                  [                                                 
1110                     [6.5,  ["M5",   9.5,   10,   3,  2.4,     4.5]],
1111                     [8  ,  ["M6",   11 ,   13,   4,  3.3,     5.5]],
1112                     [10 ,  ["M8",   13 ,   16,   5,  4.2,     7  ]],
1113                     [13 ,  ["M10",  16 ,   18,   6,  4.9,     9  ]],
1114                     [16 ,  ["M12",  18 ,   24,   8,  6.6,    11  ]],
1115                     [20 ,  ["M16",  22 ,   30,  10,  8.8,    14  ]],
1116                     [25 ,  ["M20",  27 ,   36,  12,  10 ,    16  ]]
1117                   ]
1118        :
1119                   // UTS shoulder screws, b18.3 (table 13)
1120                   // sh diam  screw   thread len, head diam   hex size  hex depth
1121                   [
1122                      [1/8  ,  ["#4",     5/32 ,    1/4      ,  5/64   ,  0.067]],
1123                      [5/32 ,  ["#6",     3/16 ,    9/32     ,  3/32   ,  0.067]],
1124                      [3/16 ,  ["#8",     3/16 ,    5/16     ,  3/32   ,  0.079]],
1125                      [1/4  ,  ["#10",    3/8  ,    3/8      ,  1/8    ,  0.094]],
1126                      [5/16 ,  ["1/4",    7/16 ,    7/16     ,  5/32   ,  0.117]],
1127                      [3/8  ,  ["5/16",   1/2  ,    9/16     ,  3/16   ,  0.141]],
1128                      [1/2  ,  ["3/8",    5/8  ,    3/4      ,  1/4    ,  0.188]],
1129                      [5/8  ,  ["1/2",    3/4  ,    7/8      ,  5/16   ,  0.234]],
1130                      [3/4  ,  ["5/8",    7/8  ,    1        ,  3/8    ,  0.281]],
1131                      [1    ,  ["3/4",    1    ,    1+5/16   ,  1/2    ,  0.375]],
1132                      [1+1/4,  ["7/8",    1+1/8,    1+3/4    ,  5/8    ,  0.469]],
1133                      [1+1/2,  ["1.125",  1+1/2,    2+1/8    ,  7/8    ,  0.656]],
1134                      [1+3/4,  ["1.25",   1+3/4,    2+3/8    ,  1      ,  0.750]],
1135                      [2    ,  ["1.5",    2    ,    2+3/4    ,  1+1/4  ,  0.937]]
1136                   ];           
1137  entry = struct_val(table, d);
1138  shoulder_diam = d * factor - shoulder_undersize;
1139  spec = first_defined([usersize, entry[0]]);
1140  dummy2=assert(is_def(spec),"No shoulder screw found with specified diameter");
1141  thread_len = first_defined([thread_len, u_mul(entry[1],factor)]);
1142  head_size = first_defined([head_size, u_mul(entry[2],factor)]);
1143  drive_size = first_defined([drive_size, u_mul(entry[3],factor)]);
1144  drive_depth = u_mul(entry[4],factor);
1145  head_height_table = iso? first_defined([entry[5],d/2+1.5])
1146                    : d<3/4 ? (d/2 + 1/16)*INCH
1147                    : (d/2 + 1/8)*INCH;
1148  shoulder_tol = tolerance==0 || tolerance=="none" ? 0
1149               : iso ? lookup(d, [[10,0.03],[13,0.037],[16,0.037],[20,0.046]])
1150               : 1; //0.003 * INCH;
1151  info = is_struct(s) ? s
1152       : screw_info(spec, head, drive, drive_size=drive_size, thread=thread);
1153
1154  final_headsize = is_num(head_size) ? head_size
1155                 : head_size[0];
1156  d5=assert(is_num(final_headsize), "Head size invalid or missing");
1157  final_sharpsize =  head!="flat" ? undef : is_vector(head_size)? head_size[1] : final_headsize*1.12;
1158  head_height_flat = head!="flat" ? undef : (final_sharpsize-(shoulder_diam-shoulder_tol))/2/tan(struct_val(info,"head_angle")/2);
1159  headfields = concat(
1160                      ["head_size", final_headsize],
1161                      head=="flat" ? ["head_size_sharp", final_sharpsize, "head_height", head_height_flat]
1162                                   : ["head_height",   is_vector(head_size) ? head_size[1]
1163                                                     : is_num(head_height_table)? head_height_table
1164                                                     : final_headsize/2 + 1.5],
1165                      is_def(drive_depth) ? ["drive_depth", drive_depth] :[]
1166                     );
1167  dummy3=assert(is_num(length) && length>0, "Must give a positive shoulder length");
1168  screw(struct_set(info, headfields),
1169        _shoulder_len = length, _shoulder_diam = shoulder_diam-shoulder_tol,
1170        length=thread_len, tolerance=tolerance, shaft_undersize=shaft_undersize, head_undersize=head_undersize,
1171        blunt_start=blunt_start, blunt_start1=blunt_start1, blunt_start2=blunt_start2,                 
1172        atype=atype, anchor=anchor, orient=orient, spin=spin)
1173    children();
1174}        
1175                     
1176
1177
1178module _driver(spec)
1179{
1180  drive = struct_val(spec,"drive");
1181  if (is_def(drive) && drive!="none") {
1182    head = struct_val(spec,"head");
1183    diameter = _nominal_diam(spec);
1184    drive_size = struct_val(spec,"drive_size");
1185    drive_diameter = struct_val(spec, "drive_diameter");
1186    drive_depth = first_defined([struct_val(spec, "drive_depth"), .7*diameter]); // Note hack for unspecified depth
1187    head_top = starts_with(head,"flat") || head=="none" ? 0 :
1188               struct_val(spec,"head_height");
1189    up(head_top-drive_depth){
1190      // recess should be positioned with its bottom center at (0,0) and the correct recess depth given above
1191      if (drive=="phillips") phillips_mask(drive_size,anchor=BOTTOM);
1192      if (drive=="torx") torx_mask(size=drive_size, l=drive_depth+1, center=false);
1193      if (drive=="hex") hex_drive_mask(drive_size,drive_depth+1,anchor=BOT);
1194      if (drive=="slot") {
1195          head_width = first_defined([u_add(struct_val(spec, "head_size"),struct_val(spec,"head_oversize",0)), diameter]);
1196          cuboid([2*head_width, drive_size, drive_depth+1],anchor=BOTTOM);
1197      }
1198    }
1199  }
1200}
1201
1202
1203function _ISO_thread_tolerance(diameter, pitch, internal=false, tolerance=undef) =
1204  let(
1205    P = pitch,
1206    H = P*sqrt(3)/2,
1207    tolerance = first_defined([tolerance, internal?"6H":"6g"]),
1208
1209    pdiam = diameter - 2*3/8*H,          // nominal pitch diameter
1210    mindiam = diameter - 2*5/8*H,        // nominal minimum diameter
1211
1212    EI = [   // Fundamental deviations for nut thread
1213          ["G", 15+11*P],
1214          ["H", 0],            // Standard practice
1215         ],
1216
1217    es = [    // Fundamental deviations for bolt thread
1218          ["e", -(50+11*P)],   // Exceptions if P<=0.45mm
1219          ["f", -(30+11*P)],
1220          ["g", -(15+11*P)],   // Standard practice
1221          ["h", 0]             // Standard practice for tight fit
1222         ],
1223
1224    T_d6 = 180*pow(P,2/3)-3.15/sqrt(P),
1225    T_d = [  // Crest diameter tolerance for major diameter of bolt thread
1226           [4, 0.63*T_d6],
1227           [6, T_d6],
1228           [8, 1.6*T_d6]
1229          ],
1230
1231    T_D1_6 = 0.2 <= P && P <= 0.8 ? 433*P - 190*pow(P,1.22) :
1232             P > .8 ? 230 * pow(P,0.7) : undef,
1233    T_D1 = [ // Crest diameter tolerance for minor diameter of nut thread
1234             [4, 0.63*T_D1_6],
1235             [5, 0.8*T_D1_6],
1236             [6, T_D1_6],
1237             [7, 1.25*T_D1_6],
1238             [8, 1.6*T_D1_6]
1239           ],
1240
1241    rangepts = [0.99, 1.4, 2.8, 5.6, 11.2, 22.4, 45, 90, 180, 300],
1242    d_ind = floor(lookup(diameter,hstack(rangepts,count(len(rangepts))))),
1243    avgd = sqrt(rangepts[d_ind]* rangepts[d_ind+1]),
1244
1245    T_d2_6 = 90*pow(P, 0.4)*pow(avgd,0.1),
1246    T_d2 = [ // Pitch diameter tolerance for bolt thread
1247             [3, 0.5*T_d2_6],
1248             [4, 0.63*T_d2_6],
1249             [5, 0.8*T_d2_6],
1250             [6, T_d2_6],
1251             [7, 1.25*T_d2_6],
1252             [8, 1.6*T_d2_6],
1253             [9, 2*T_d2_6],
1254           ],
1255
1256    T_D2 = [  // Tolerance for pitch diameter of nut thread
1257              [4, 0.85*T_d2_6],
1258              [5, 1.06*T_d2_6],
1259              [6, 1.32*T_d2_6],
1260              [7, 1.7*T_d2_6],
1261              [8, 2.12*T_d2_6]
1262           ],
1263
1264    internal = is_def(internal) ? internal : tolerance[1] != downcase(tolerance[1]),
1265    internalok = !internal || (
1266                               len(tolerance)==2 && str_find("GH",tolerance[1])!=undef && str_find("45678",tolerance[0])!=undef),
1267    tol_str = str(tolerance,tolerance),
1268    externalok = internal || (
1269                              (len(tolerance)==2 || len(tolerance)==4)
1270                                                          && str_find("efgh", tol_str[1])!=undef
1271                                                          && str_find("efgh", tol_str[3])!=undef
1272                                                          && str_find("3456789", tol_str[0]) != undef
1273                                                          && str_find("468", tol_str[2]) !=undef)
1274  )
1275  assert(internalok,str("Invalid internal thread tolerance, ",tolerance,".  Must have form <digit><letter>"))
1276  assert(externalok,str("invalid external thread tolerance, ",tolerance,".  Must have form <digit><letter> or <digit><letter><digit><letter>"))
1277  let(
1278    tol_num_pitch = parse_num(tol_str[0]),
1279    tol_num_crest = parse_num(tol_str[2]),
1280    tol_letter = tol_str[1]
1281  )
1282  assert(tol_letter==tol_str[3],str("Invalid tolerance, ",tolerance,".  Cannot mix different letters"))
1283  internal ?
1284    let(  // Nut case
1285      fdev = struct_val(EI,tol_letter)/1000,
1286      Tdval = struct_val(T_D1, tol_num_crest)/1000,
1287      Td2val = struct_val(T_D2, tol_num_pitch)/1000,
1288      bot=[diameter+fdev, diameter+fdev+Td2val+H/6],
1289      xdiam = [mindiam+fdev,mindiam+fdev+Tdval],
1290      pitchdiam = [pdiam + fdev, pdiam+fdev+Td2val]
1291    )
1292    [["pitch",P],["d_minor",xdiam], ["d_pitch",pitchdiam], ["d_major",bot],["basic",[mindiam,pdiam,diameter]]]
1293  :
1294    let( // Bolt case
1295      fdev = struct_val(es,tol_letter)/1000,
1296      Tdval = struct_val(T_d, tol_num_crest)/1000,
1297      Td2val = struct_val(T_d2, tol_num_pitch)/1000,
1298      mintrunc = P/8,
1299      d1 = diameter-5*H/4,
1300      maxtrunc = H/4 - mintrunc * (1-cos(60-acos(1-Td2val/4/mintrunc)))+Td2val/2,
1301      bot = [diameter-2*H+2*mintrunc+fdev, diameter-2*H+2*maxtrunc+fdev],
1302      xdiam = [diameter+fdev,diameter+fdev-Tdval],
1303      pitchdiam = [pdiam + fdev, pdiam+fdev-Td2val]
1304    )
1305    [["pitch",P],["d_major",xdiam], ["d_pitch",pitchdiam], ["d_minor",bot],["basic",[mindiam,pdiam,diameter]]];
1306
1307function _UTS_thread_tolerance(diam, pitch, internal=false, tolerance=undef) =
1308  let(
1309    d = diam/INCH,   // diameter in inches
1310    P = pitch/INCH,  // pitch in inches
1311    H = P*sqrt(3)/2,
1312    tolerance = first_defined([tolerance, internal?"2B":"2A"]),
1313    tolOK = in_list(tolerance, ["1A","1B","2A","2B","3A","3B"]),
1314    internal = tolerance[1]=="B"
1315  )
1316  assert(tolOK,str("Tolerance was ",tolerance,". Must be one of 1A, 2A, 3A, 1B, 2B, 3B"))
1317  let(
1318    LE = 9*P,   // length of engagement.  Is this right?
1319    pitchtol_2A = 0.0015*pow(d,1/3) + 0.0015*sqrt(LE) + 0.015*pow(P,2/3),
1320    pitchtol_table = [
1321                 ["1A", 1.500*pitchtol_2A],
1322                 ["2A",       pitchtol_2A],
1323                 ["3A", 0.750*pitchtol_2A],
1324                 ["1B", 1.950*pitchtol_2A],
1325                 ["2B", 1.300*pitchtol_2A],
1326                 ["3B", 0.975*pitchtol_2A]
1327               ],
1328     pitchtol = struct_val(pitchtol_table, tolerance),
1329     allowance = tolerance=="1A" || tolerance=="2A" ? 0.3 * pitchtol_2A : 0,
1330     majortol = tolerance == "1A" ? 0.090*pow(P,2/3) :
1331                tolerance == "2A" || tolerance == "3A" ? 0.060*pow(P,2/3) :
1332                pitchtol+pitch/4/sqrt(3),    // Internal case
1333     minortol = tolerance=="1B" || tolerance=="2B" ?
1334                    (
1335                      d < 0.25 ? constrain(0.05*pow(P,2/3)+0.03*P/d - 0.002, 0.25*P-0.4*P*P, 0.394*P)
1336                               : (P > 0.25 ? 0.15*P : 0.25*P-0.4*P*P)
1337                    ) :
1338                tolerance=="3B" ? constrain(0.05*pow(P,2/3)+0.03*P/d - 0.002, P<1/13 ? 0.12*P : 0.23*P-1.5*P*P, 0.394*P)
1339                     :0, // not used for external threads
1340     basic_minordiam = d - 5/4*H,
1341     basic_pitchdiam = d - 3/4*H,
1342     majordiam = internal ? [d,d] :          // A little confused here, paragraph 8.3.2
1343                          [d-allowance-majortol, d-allowance],
1344     pitchdiam = internal ? [basic_pitchdiam, basic_pitchdiam + pitchtol]
1345                          : [majordiam[1] - 3/4*H-pitchtol, majordiam[1]-3/4*H],
1346     minordiam = internal ? [basic_minordiam, basic_minordiam + minortol]
1347                          : [pitchdiam[0] - 3/4*H, basic_minordiam - allowance - H/8]   // the -H/8 is for the UNR case, 0 for UN case
1348    )
1349    [["pitch",P*INCH],["d_major",majordiam*INCH], ["d_pitch", pitchdiam*INCH], ["d_minor",minordiam*INCH],
1350     ["basic", INCH*[basic_minordiam, basic_pitchdiam, d]]];
1351
1352function _exact_thread_tolerance(d,P) =
1353   let(
1354       H = P*sqrt(3)/2,
1355       basic_minordiam = d - 5/4*H,
1356       basic_pitchdiam = d - 3/4*H
1357      )
1358    [["pitch", P], ["d_major", [d,d]], ["d_pitch", [basic_pitchdiam,basic_pitchdiam]], ["d_minor", [basic_minordiam,basic_minordiam]],
1359     ["basic", [basic_minordiam, basic_pitchdiam, d]]];
1360
1361
1362// Takes a screw name as input and returns a list of the form
1363// [system, diameter, thread, length]
1364// where system is either "english" or "metric".  
1365
1366function _parse_screw_name(name) =
1367    let( commasplit = str_split(name,","),
1368         length = parse_num(commasplit[1]),
1369         xdash = str_split(commasplit[0], "-x"),
1370         type = xdash[0],
1371         thread = parse_float(xdash[1])
1372    )
1373    assert(len(commasplit)<=2, str("More than one comma found in screw name, \"",name,"\""))
1374    assert(len(xdash)<=2, str("Screw name has too many '-' or 'x' characters, \"",name,"\""))
1375    assert(len(commasplit)==1 || is_num(length), str("Invalid length \"", commasplit[1],"\" in screw name, \"",name,"\""))
1376    assert(len(xdash)==1 || all_nonnegative(thread),str("Thread pitch not a valid number in screw name, \"",name,"\""))
1377    type[0] == "M" || type[0] == "m" ? 
1378        let(diam = parse_float(substr(type,1)))
1379        assert(is_num(diam), str("Screw size must be a number in screw name, \"",name,"\""))
1380        ["metric", parse_float(substr(type,1)), thread, length] 
1381    :
1382    let(
1383        diam = type[0] == "#" ? type :
1384               suffix(type,2)=="''" ? parse_float(substr(type,0,len(type)-2)) :
1385               let(val=parse_num(type))
1386               assert(all_positive(val), str("Screw size must be a number in screw name, \"",name,"\""))
1387               val == floor(val) && val>=0 && val<=12 ? str("#",type) : val
1388    )
1389    assert(is_str(diam) || is_num(diam), str("Invalid screw diameter in screw name, \"",name,"\""))
1390    ["english", diam, thread, u_mul(25.4,length)];
1391
1392
1393// drive can be "hex", "phillips", "slot", "torx", or "none"
1394// or you can specify "ph0" up to "ph4" for phillips and "t20" for torx 20
1395function _parse_drive(drive=undef, drive_size=undef) =
1396    is_undef(drive) ? ["none",undef] 
1397  : assert(is_string(drive))
1398    let(drive = downcase(drive))
1399    in_list(drive,["hex","phillips", "slot", "torx", "phillips", "none"]) ? [drive, drive_size] 
1400  : drive[0]=="t" ? let(size = parse_int(substr(drive,1))) ["torx",size,torx_depth(size) ] 
1401  : starts_with(drive,"ph") && search(drive[2], "01234")!=[] ? ["phillips", ord(drive[2])-ord("0")] 
1402  : assert(false,str("Unknown screw drive type ",drive));
1403
1404
1405// Module: screw_head()
1406// Synopsis: Creates a screw head.
1407// SynTags: Geom
1408// Topics: Threading, Screws
1409// See Also: screw(), screw_hole()
1410// Usage:
1411//    screw_head(screw_info, [details],[counterbore],[flat_height],[teardrop],[internal])
1412// Description:
1413//    Draws the screw head described by the data structure `screw_info`, which
1414//    should have the fields produced by {{screw_info()}}.  See that function for
1415//    details on the fields.  Standard orientation is with the head centered at (0,0)
1416//    and oriented in the +z direction.  Flat heads appear below the xy plane.
1417//    Other heads appear sitting on the xy plane.  
1418// Arguments:
1419//    screw_info = structure produced by {{screw_info()}}
1420//    ---
1421//    details = true for more detailed model.  Default: false
1422//    counterbore = counterbore height.  Default: no counterbore
1423//    flat_height = height of flat head
1424//    teardrop = if true make flathead and counterbores teardrop shaped
1425//    slop = enlarge diameter by this extra amount (beyond that specified in the screw specification).  Default: 0
1426function screw_head(screw_info,details=false, counterbore=0,flat_height,teardrop=false,slop=0) = no_function("screw_head");
1427module screw_head(screw_info,details=false, counterbore=0,flat_height,teardrop=false,slop=0) {
1428   no_children($children);
1429   head_oversize = struct_val(screw_info, "head_oversize",0) + slop;
1430   head = struct_val(screw_info, "head");
1431   head_size = struct_val(screw_info, "head_size",0) + head_oversize;
1432   head_height = struct_val(screw_info, "head_height");
1433   dum0=assert(is_def(head_height) || in_list(head,["flat","none"]), "Undefined head height only allowed with flat head or headless screws");
1434   heightok = (is_undef(head_height) && in_list(head,["flat","none"])) || all_positive(head_height);
1435   dum1=assert(heightok, "Head hight must be a postive number");
1436   dum2=assert(counterbore==0 || counterbore==false || head!="none", "Cannot counterbore a headless screw");
1437   counterbore_temp = counterbore==false? 0 
1438                    : head!="flat" && counterbore==true ? head_height 
1439                    : counterbore;
1440   dum3=assert(is_finite(counterbore_temp) && counterbore_temp>=0, str(counterbore==true? "Must specify numerical counterbore height with flat head screw"
1441                                                             : "Counterbore must be a nonnegative number"));
1442
1443   counterbore = counterbore_temp==0 && head!="flat" ? counterbore_temp : counterbore_temp + 0.01;
1444   adj_diam = struct_val(screw_info, "diameter") + head_oversize;   // Used for determining chamfers and ribbing
1445   attachable(){
1446     union(){
1447         if (head!="flat" && counterbore>0){
1448           d = head=="hex"? 2*head_size/sqrt(3) : head_size;
1449           if (teardrop)
1450             teardrop(d=d, l=counterbore, orient=BACK, anchor=BACK);
1451           else                    
1452             cyl(d=d, l=counterbore, anchor=BOTTOM);
1453         }  
1454         if (head=="flat") {   // For flat head, counterbore is integrated
1455           angle = struct_val(screw_info, "head_angle")/2;
1456           sharpsize = struct_val(screw_info, "head_size_sharp")+head_oversize;
1457           sidewall_height = (sharpsize - head_size)/2 / tan(angle);
1458           cylheight = counterbore + sidewall_height;
1459           slopeheight = flat_height - sidewall_height;
1460           r1 = head_size/2;
1461           r2 = r1 - tan(angle)*slopeheight;
1462           n = segs(r1);
1463           prof1 = teardrop ? teardrop2d(r=r1,$fn=n) : circle(r=r1, $fn=n);
1464           prof2 = teardrop ? teardrop2d(r=r2,$fn=n) : circle(r=r2, $fn=n);
1465           skin([prof2,prof1,prof1], z=[-flat_height, -flat_height+slopeheight, counterbore],slices=0);
1466         }
1467         if (head!="flat" && counterbore==0) {
1468           if (in_list(head,["round","pan round","button","fillister","cheese"])) {
1469             base = head=="fillister" ? 0.75*head_height :
1470                    head=="pan round" ? .6 * head_height :
1471                    head=="cheese" ? .7 * head_height :
1472                    0.1 * head_height;   // round and button
1473             head_size2 = head=="cheese" ?  head_size-2*tan(5)*head_height : head_size; // 5 deg slope on cheese head
1474             segs = segs(head_size);
1475             cyl(l=base, d1=head_size, d2=head_size2,anchor=BOTTOM, $fn=segs)
1476               attach(TOP)
1477                 zrot(180) // Needed to align facets when $fn is odd
1478                 rotate_extrude($fn=segs)  // ensure same number of segments for cap as for head body
1479                   intersection(){
1480                     arc(points=[[-head_size2/2,0], [0,-base+head_height * (head=="button"?4/3:1)], [head_size2/2,0]]);
1481                     square([head_size2, head_height-base]);
1482                   }
1483           }
1484           if (head=="pan flat")
1485             cyl(l=head_height, d=head_size, rounding2=0.2*head_size, anchor=BOTTOM);
1486           if (head=="socket")
1487             cyl(l=head_height, d=head_size, anchor=BOTTOM, chamfer2=details? adj_diam/10:undef);
1488           if (head=="socket ribbed"){
1489             // These numbers are based on ISO specifications that dictate how much oversizsed a ribbed socket head can be
1490             // We are making our ribbed heads the same size as unribbed (by cutting the ribbing away), but these numbers are presumably a good guide
1491             rib_size = [[2, .09],
1492                         [3, .09],
1493                         [6, .11],
1494                         [12, .135],
1495                         [20, .165]];
1496             intersection() {
1497               cyl(h=head_height/4, d=head_size, anchor=BOT)
1498                  attach(TOP) cyl(l=head_height*3/4, d=head_size, anchor=BOT, texture="trunc_ribs", tex_counts=[31,1], tex_scale=-lookup(adj_diam,rib_size));
1499               cyl(h=head_height,d=head_size, chamfer2=adj_diam/10, anchor=BOT);
1500             }
1501           }
1502           if (head=="hex")
1503             up(head_height/2)_nutshape(head_size,head_height,"hex",false,true);
1504         }
1505     }    
1506     union(){};
1507   }
1508}
1509
1510
1511// Section: Nuts and nut traps
1512
1513
1514// Module: nut()
1515// Synopsis: Creates a standard nut.
1516// SynTags: Geom
1517// Topics: Threading, Screws
1518// See Also: screw(), screw_hole()
1519// Usage:
1520//   nut([spec], [shape], [thickness], [nutwidth], [thread=], [tolerance=], [hole_oversize=], [bevel=], [$slop=], [anchor=], [spin=], [orient=]) [ATTACHMENTS];
1521// Description:
1522//   Generates a hexagonal or square nut.  See [screw and nut parameters](#section-screw-and-nut-parameters) for details on the parameters that define a nut.
1523//   As with screws, you can give the specification in `spec` and then omit the name.  The diameter is the flat-to-flat
1524//   size of the nut produced.  The thickness can be "thin", "normal" or "thick" to choose standard nut dimensions.  For metric
1525//   nuts you can also use thickness values of "DIN" or "undersized".  The nut's shape is hexagonal by default; set shape to "square" for
1526//   a square nut.
1527//   .
1528//   By default all nuts have the internal holes beveled and hex nuts have their corners beveled.  Square nuts get no outside bevel by default.
1529//   ASME specifies that small square nuts should not be beveled, and many square nuts are beveled only on one side.   The bevel angle, specified with bevang,
1530//   gives the angle for the bevel.  The default of 15 is shallow and may not be printable.  Internal hole are beveled at 45 deg by the depth of one thread.  
1531//   .
1532//   The tolerance determines the actual thread sizing based on the nominal size in accordance with standards.  
1533//   The $slop parameter determines extra gaps left to account for printing overextrusion.  It defaults to 0.
1534// Arguments:
1535//   spec = nut specification, e.g. "M5x1" or "#8-32".  See [screw naming](#subsection-screw-naming).  This can also be a nut or screw specification structure of the form produced by {{nut_info()}} or {{screw_info()}}.  
1536//   shape = "hex" or "square" to specify nut shape.  Default: "hex"
1537//   thickness = "thin", "normal", "thick", or a thickness in mm.  See [nuts](#subsection-nuts).  Default: "normal"
1538//   ---
1539//   nutwidth = width of nut (overrides table values)
1540//   thread = thread type or specification. See [screw pitch](#subsection-standard-screw-pitch). Default: "coarse"
1541//   hole_oversize = amount to increase hole diameter.  Default: 0
1542//   bevel = if true, bevel the outside of the nut.  Default: true for hex nuts, false for square nuts
1543//   bevel1 = if true, bevel the outside of the nut bottom.
1544//   bevel2 = if true, bevel the outside of the nut top. 
1545//   bevang = set the angle for the outside nut bevel.  Default: 15
1546//   ibevel = if true, bevel the inside (the hole).   Default: true
1547//   ibevel1 = if true bevel the inside, bottom end.
1548//   ibevel2 = if true bevel the inside, top end.
1549//   blunt_start = If true apply truncated blunt start threads at both ends.  Default: true
1550//   blunt_start1 = If true apply truncated blunt start threads bottom end.
1551//   blunt_start2 = If true apply truncated blunt start threads top end.
1552//   tolerance = nut tolerance.  Determines actual nut thread geometry based on nominal sizing.  See [tolerance](#subsection-tolerance). Default is "2B" for UTS and "6H" for ISO.
1553//   $slop = extra space left to account for printing over-extrusion.  Default: 0
1554//   anchor = Translate so anchor point is at origin (0,0,0).  See [anchor](attachments.scad#subsection-anchor).  Default: `CENTER`
1555//   spin = Rotate this many degrees around the Z axis after anchor.  See [spin](attachments.scad#subsection-spin).  Default: `0`
1556//   orient = Vector to rotate top towards, after spin.  See [orient](attachments.scad#subsection-orient).  Default: `UP`
1557// Side Effects:
1558//   `$screw_spec` is set to the spec specification structure. 
1559// Example: All the UTS nuts at one size.  Note that square nuts come in only one thickness.  
1560//   xdistribute(spacing=0.75*INCH){
1561//       nut("3/8",thickness="thin");
1562//       nut("3/8",thickness="normal");
1563//       nut("3/8",thickness="thick");
1564//       nut("3/8",shape="square");
1565//   }
1566// Example: All the ISO (and DIN) nuts at one size.  Note that M10 is one of the four cases where the DIN nut width is larger.  
1567//   ydistribute(spacing=30){
1568//      xdistribute(spacing=22){
1569//         nut("M10", thickness="thin");
1570//         nut("M10",thickness="undersized");
1571//         nut("M10",thickness="normal");
1572//         nut("M10",thickness="thick");
1573//      }
1574//      xdistribute(spacing=25){
1575//         nut("M10", shape="square", thickness="thin");
1576//         nut("M10", shape="square", thickness="normal");      
1577//      }
1578//   }
1579// Example: The three different UTS nut tolerances (thickner than normal nuts)
1580//   module mark(number)
1581//   {
1582//     difference(){
1583//        children();
1584//        ycopies(n=number, spacing=1.5)right(.25*INCH-2)up(8-.35)cyl(d=1, h=1);
1585//     }
1586//   }
1587//   $fn=64;
1588//   xdistribute(spacing=17){
1589//     mark(1) nut("1/4-20", thickness=8, nutwidth=0.5*INCH,tolerance="1B");
1590//     mark(2) nut("1/4-20", thickness=8, nutwidth=0.5*INCH,tolerance="2B");
1591//     mark(3) nut("1/4-20", thickness=8, nutwidth=0.5*INCH,tolerance="3B");
1592//   }
1593// Example: Threadless nut
1594//   nut("#8", thread="none");
1595
1596function nut(spec, shape, thickness, nutwidth, thread, tolerance, hole_oversize, 
1597           bevel,bevel1,bevel2,bevang=15,ibevel,ibevel1,ibevel2,blunt_start, blunt_start1, blunt_start2, anchor=BOTTOM, spin=0, orient=UP, oversize=0)
1598           = no_function("nut");
1599module nut(spec, shape, thickness, nutwidth, thread, tolerance, hole_oversize, 
1600           bevel,bevel1,bevel2,bevang=15,ibevel,ibevel1,ibevel2,blunt_start, blunt_start1, blunt_start2, anchor=BOTTOM, spin=0, orient=UP, oversize=0)
1601{
1602   dummyA = assert(is_undef(nutwidth) || (is_num(nutwidth) && nutwidth>0));
1603   
1604   tempspec = _get_spec(spec, "nut_info", "nut", 
1605                        thread=thread, shape=shape, thickness=thickness);
1606   spec=_struct_reset(tempspec,[
1607                                ["width", nutwidth],
1608                                ["shaft_oversize", hole_oversize],
1609                               ]);
1610   dummy=_validate_nut_spec(spec);
1611   $screw_spec = spec;
1612   shape = struct_val(spec, "shape");
1613   pitch =  struct_val(spec, "pitch") ;
1614   threadspec = pitch==0 ? undef : thread_specification(spec, internal=true, tolerance=tolerance);
1615   nutwidth = struct_val(spec, "width");
1616   thickness = struct_val(spec, "thickness");
1617   threaded_nut(
1618        nutwidth=nutwidth,
1619        id=pitch==0 ? _nominal_diam(spec)
1620          : [mean(struct_val(threadspec, "d_minor")),
1621             mean(struct_val(threadspec, "d_pitch")),
1622             mean(struct_val(threadspec, "d_major"))],
1623        pitch = pitch, 
1624        h=thickness,
1625        shape=shape, 
1626        bevel=bevel,bevel1=bevel1,bevel2=bevel2,bevang=bevang,
1627        ibevel=ibevel,ibevel1=ibevel1,ibevel2=ibevel2,
1628        blunt_start=blunt_start, blunt_start1=blunt_start1, blunt_start2=blunt_start2,         
1629        anchor=anchor,spin=spin,orient=orient) children();
1630}
1631
1632
1633
1634
1635
1636
1637// Module: nut_trap_side()
1638// Synopsis: Creates a side nut trap mask.
1639// SynTags: Geom
1640// Topics: Threading, Screws
1641// See Also: screw(), screw_hole()
1642// Usage:
1643//   nut_trap_side(trap_width, [spec], [shape], [thickness], [nutwidth=], [poke_len=], [poke_diam=], [$slop=], [anchor=], [orient=], [spin=]) [ATTACHMENTS];
1644// Description:
1645//   Create a nut trap that extends sideways, so the nut slides in perpendicular to the screw axis.
1646//   The CENTER anchor is the center of the screw hole location in the trap.  The trap width is
1647//   measured from the screw hole center point.  You can optionally create a poke hole to use for
1648//   removing the nut by specifying a poke_len value that determines the length of the poke hole, measured
1649//   from the screw center.  The diameter of the poke hole defaults to the thickness of the nut.  The nut dimensions
1650//   will be increased by `2*$slop` to allow adjusting the fit of the trap for your printer.  
1651//   The trap will have a default tag of "remove" if no other tag is in force.  
1652// Arguments:
1653//   trap_width = width of nut trap, measured from screw center, must be larger than half the nut width  (If spec is omitted this argument must be given by name.)
1654//   spec = nut specification, e.g. "M5" or "#8".  See [screw naming](#subsection-screw-naming).  This can also be a screw or nut specification structure of the form produced by {{nut_info()}} or {{screw_info()}}.  
1655//   shape = "hex" or "square" to specify the shape of the nut.   Default: "hex"
1656//   thickness = "thin", "normal", or "thick".  "DIN" or "undersized" for metric nuts.  See [nuts](#subsection-nuts). Default: "normal"
1657//   ---
1658//   nutwidth = width of the nut.  Default: determined from tables
1659//   poke_len = length of poke hole.  Default: no poke hole
1660//   poke_diam = diameter of poke hole.  Default: nut thickness
1661//   $slop = extra space left to account for printing over-extrusion.  Default: 0
1662//   anchor = Translate so anchor point is at origin (0,0,0).  See [anchor](attachments.scad#subsection-anchor).  Default: `BOTTOM`
1663//   spin = Rotate this many degrees around the Z axis after anchor.  See [spin](attachments.scad#subsection-spin).  Default: `0`
1664//   orient = Vector to rotate top towards, after spin.  See [orient](attachments.scad#subsection-orient).  Default: `UP`
1665// Side Effects:
1666//   `$screw_spec` is set to the spec specification structure. 
1667// Example: Basic trap.  Note that screw center is at the origin and the width is measured from the origin.  
1668//   nut_trap_side(10, "#8");
1669// Example: Trap with poke hole for removing nut.  The poke hole length is also measured from the screw center at the origin
1670//   $fn=16;
1671//   nut_trap_side(10, "#8", poke_len=10);
1672// Example: Trap for square nut
1673//   $fn=16;
1674//   nut_trap_side(10, "#8", shape="square", poke_len=10);
1675// Example: Trap with looser fit
1676//   nut_trap_side(10, "#8", $slop=0.1);
1677// Example: Trap placed at the bottom of a screw hole
1678//   $fn=24;
1679//   screw_hole("#8,1") 
1680//     position(BOT) nut_trap_side(10,poke_len=8);
1681// Example: Trap placed at the bottom of a screw hole 2mm extra screw hole below the trap
1682//   $fn=24;
1683//   screw_hole("#8,1") 
1684//     up(2) position(BOT) nut_trap_side(trap_width=10,poke_len=8);
1685// Example: Hole-trap assembly removed from an object
1686//   $fn=24;
1687//   back_half()
1688//   diff()
1689//   cuboid(30)
1690//      position(TOP)screw_hole("#8,1",anchor=TOP) 
1691//        position(BOT) nut_trap_side(trap_width=16);
1692// Example: Hole-trap assembly where we position the trap relative to a feature on the model and then position the screw hole through the trap as a child to the trap.  
1693//  diff()
1694//   cuboid([30,30,20])
1695//     position(RIGHT)cuboid([4,20,3],anchor=LEFT)
1696//       right(1)position(TOP+LEFT)nut_trap_side(15, "#8",anchor=BOT+RIGHT)
1697//         screw_hole(length=20,anchor=BOT);
1698module nut_trap_side(trap_width, spec, shape, thickness, nutwidth, anchor=BOT, orient, spin, poke_len=0, poke_diam) {
1699  dummy9=assert(is_num(trap_width), "trap_width is missing or the wrong type");
1700  tempspec = _get_spec(spec, "nut_info", "nut_trap", shape=shape, thickness=thickness);
1701  nutdata = _struct_reset(tempspec, [["width", nutwidth]]);
1702  $screw_spec = is_def(spec) ? nutdata : $screw_spec;
1703  dummy8 = _validate_nut_spec(nutdata);
1704  nutwidth = struct_val(nutdata,"width")+2*get_slop();
1705  dummy = assert(is_num(poke_len) && poke_len>=0, "poke_len must be a nonnegative number")
1706          assert(is_undef(poke_diam) || (is_num(poke_diam) && poke_diam>0), "poke_diam must be a positive number")
1707          assert(is_num(trap_width) && trap_width>=nutwidth/2, str("trap_width is smaller than nut width: ",nutwidth));
1708  nutthickness = struct_val(nutdata, "thickness")+2*get_slop();
1709  cubesize = [trap_width, nutwidth,nutthickness];
1710  halfwidth = shape=="square" ? nutwidth/2 : nutwidth/sqrt(3);
1711  shift = cubesize[0]/2 - halfwidth/2;
1712  default_tag("remove")
1713    attachable(size=cubesize+[halfwidth,0,0], offset=[shift,0,0],anchor=anchor,orient=orient,spin=spin)
1714    {
1715       union(){
1716         if (shape=="square") left(nutwidth/2) cuboid(cubesize+[halfwidth,0,0],anchor=LEFT);
1717         else {
1718            cuboid(cubesize,anchor=LEFT);
1719            linear_extrude(height=nutthickness,center=true)hexagon(id=nutwidth);
1720         }
1721         if (poke_len>0)
1722           xcyl(l=poke_len, d=default(poke_diam, nutthickness), anchor=RIGHT);
1723       }
1724       children();
1725    }     
1726}
1727
1728// Module: nut_trap_inline()
1729// Synopsis: Creates an inline nut trap mask.
1730// SynTags: Geom
1731// Topics: Threading, Screws
1732// See Also: screw(), screw_hole()
1733// Usage:
1734//   nut_trap_inline(length|l|heigth|h, [spec], [shape], [$slop=], [anchor=], [orient=], [spin=]) [ATTACHMENTS];
1735// Description:
1736//   Create a nut trap that extends along the axis of the screw.  The nut width
1737//   will be increased by `2*$slop` to allow adjusting the fit of the trap for your printer.
1738//   If no tag is present the trap will be tagged with "remove".  Note that you can omit the specification
1739//   and it will be inherited from a parent screw_hole to provide the screw size.  It's also possible to 
1740//   do this backwards, to declare a trap at a screw size and make a child screw hole, which will inherit
1741//   the screw dimensions.  
1742// Arguments:
1743//   length/l/height/h = length/height of nut trap
1744//   spec = nut specification, e.g. "M5" or "#8".  See [screw naming](#subsection-screw-naming).  This can also be a screw or nut specification structure of the form produced by {{nut_info()}} or {{screw_info()}}.  
1745//   shape = "hex" or "square to determine type of nut.  Default: "hex"
1746//   ---
1747//   $slop = extra space left to account for printing over-extrusion.  Default: 0
1748//   anchor = Translate so anchor point is at origin (0,0,0).  See [anchor](attachments.scad#subsection-anchor).  Default: `TOP`
1749//   spin = Rotate this many degrees around the Z axis after anchor.  See [spin](attachments.scad#subsection-spin).  Default: `0`
1750//   orient = Vector to rotate top towards, after spin.  See [orient](attachments.scad#subsection-orient).  Default: `UP`
1751// Side Effects:
1752//   `$screw_spec` is set to the spec specification structure. 
1753// Example: Basic trap
1754//   nut_trap_inline(10, "#8");
1755// Example: Basic trap with allowance for a looser fit
1756//   nut_trap_inline(10, "#8", $slop=.1);
1757// Example: Square trap (just a cube, but hopefully just the right size)
1758//   nut_trap_inline(10, "#8", shape="square");
1759// Example: Attached to a screw hole
1760//   screw_hole("#8,1",head="socket",counterbore=true, $fn=32) 
1761//     position(BOT) nut_trap_inline(10);
1762// Example: Nut trap with child screw hole
1763//   nut_trap_inline(10, "#8")
1764//     position(TOP)screw_hole(length=10,anchor=BOT,head="flat",$fn=32);
1765// Example(Med,NoAxes): a pipe clamp
1766//   $fa=5;$fs=0.5;
1767//   bardiam = 32;
1768//   bandwidth = 10;
1769//   thickness = 3;
1770//   back_half()
1771//   diff()
1772//     tube(id=bardiam, wall = thickness, h=bandwidth, orient=BACK)
1773//       left(thickness/2) position(RIGHT) cube([bandwidth, bandwidth, 14], anchor = LEFT, orient=FWD)
1774//       {
1775//          screw_hole("#4",length=12, head="socket",counterbore=6,anchor=CENTER)
1776//             position(BOT) nut_trap_inline(l=6,anchor=BOT);
1777//          tag("remove")right(1)position(RIGHT)cube([11+thickness, 11, 2], anchor = RIGHT);
1778//       }
1779module nut_trap_inline(length, spec, shape, l, height, h, nutwidth, anchor, orient, spin) {
1780  tempspec = _get_spec(spec, "nut_info", "nut_trap", shape=shape, thickness=undef);
1781  nutdata = _struct_reset(tempspec, [["width", nutwidth]]);
1782  $screw_spec = is_def(spec) ? nutdata : $screw_spec;
1783  dummy = _validate_nut_spec(nutdata);
1784  length = one_defined([l,length,h,height],"l,length,h,height");
1785  assert(is_num(length) && length>0, "length must be a positive number");
1786  nutwidth = struct_val(nutdata,"width")+2*get_slop();
1787  default_tag("remove"){
1788    if (shape=="square")
1789      cuboid([nutwidth,nutwidth,length], anchor=anchor, orient=orient, spin=spin) children();
1790    else
1791      linear_sweep(hexagon(id=nutwidth),height=length, anchor=anchor,orient=orient, spin=spin) children();
1792  }
1793}
1794
1795
1796
1797// Section: Screw and Nut Information
1798
1799
1800// Function: screw_info()
1801// Synopsis: Returns the dimensions and other info for the given screw.
1802// Topics: Threading, Screws
1803// See Also: screw(), screw_hole()
1804// Usage:
1805//   info = screw_info(name, [head], [drive], [thread=], [drive_size=], [oversize=], [head_oversize=])
1806// Description:
1807//   Look up screw characteristics for the specified screw type.
1808//   See [screw and nut parameters](#section-screw-and-nut-parameters) for details on the parameters that define a screw.
1809//   .
1810//   The `oversize=` parameter adds the specified amount to the screw and head diameter to make an
1811//   oversized screw.  Does not affect length, thread pitch or head height.
1812//   .
1813//   Note that flat head screws are defined by two different diameters, the theoretical maximum diameter, "head_size_sharp"
1814//   and the actual diameter, "head_size".  The screw form is defined using the theoretical maximum, which gives
1815//   sharp circular edge at the top of the screw.  Real screws have a flat chamfer around the edge.  
1816// Figure(2D,Med,NoAxes,VPD=39,VPT=[0,-4,0],VPR=[0,0,0]):  Flat head screw geometry
1817//   polysharp = [[0, -5.07407], [4.92593, -5.07407], [10, 0], [10, 0.01], [0, 0.01]];
1818//   color("blue"){
1819//       xflip_copy()polygon(polysharp);
1820//       back(1/2)stroke([[-10,0],[10,0]],endcaps="arrow2",width=.15);    
1821//       back(1.7)text("\"head_size_sharp\"", size=.75,anchor=BACK);
1822//   }
1823//   poly= [[0, -5.07407], [4.92593, -5.07407], [9.02, -0.98], [9.02, 0.01], [0, 0.01]];
1824//   xflip_copy()polygon(poly);
1825//   rect([10,10],anchor=TOP);
1826//   color("black"){
1827//     fwd(1/2)stroke([[-9.02,0],[9.02,0]],endcaps="arrow2",width=.15);
1828//     fwd(1)text("\"head_size\"", size=.75,anchor=BACK);
1829//   }  
1830// Continues:
1831//   The output is a [struct](structs.scad) with the following fields:
1832//   . 
1833//   Field              | What it is
1834//   ------------------ | ---------------
1835//   "type"           | Always set to "screw_info"
1836//   "system"         | Either `"UTS"` or `"ISO"` (used for correct tolerance computation).
1837//   "origin"         | Module that generated the structure
1838//   "name"           | Screw name used to make the structure
1839//   "diameter"       | The nominal diameter of the screw shaft in mm.
1840//   "pitch"          | The thread pitch in mm.  (0 for no threads)
1841//   "head"           | The type of head (a string)
1842//   "head_size"      | Size of the head (usually diameter) in mm.
1843//   "head_size_sharp"| Theoretical head diameter for a flat head screw if it is made with sharp edges (or for countersinks)
1844//   "head_angle"     | Countersink angle for flat heads.
1845//   "head_height"    | Height of the head beyond the screw's nominal length.  The screw's total length is "length" + "head_height".  For flat heads "head_height" is zero, because they do not extend the screw.  
1846//   "drive"          | The drive type (`"phillips"`, `"torx"`, `"slot"`, `"hex"`, `"none"`)
1847//   "drive_size"     | The drive size, either a drive number (phillips, torx) or a dimension in mm (hex, slot).
1848//   "drive_depth"    | Depth of the drive recess.
1849//   "length"         | Length of the screw in mm measured in the customary fashion.  For flat head screws the total length and for other screws, the length from the bottom of the head to the screw tip.
1850//   "thread_len"     | Length of threaded portion of screw in mm
1851//   "shaft_oversize"| Amount to oversize the threads
1852//   "head_oversize"   | Amount to oversize the head
1853//   .
1854//   If you want to define a custom drive for a screw you will need to provide the drive size and drive depth.  
1855//
1856// Arguments:
1857//   name = screw specification, e.g. "M5x1" or "#8-32".  See [screw naming](#subsection-screw-naming).
1858//   head = head type.  See [screw heads](#subsection-screw-heads)  Default: none
1859//   drive = drive type.  See [screw heads](#subsection-screw-heads) Default: none
1860//   ---
1861//   thread = thread type or specification. See [screw pitch](#subsection-standard-screw-pitch). Default: "coarse"
1862//   drive_size = size of drive recess to override computed value
1863//   shaft_oversize = amount to increase screw diameter for clearance holes.  Default: 0
1864//   head_oversize = amount to increase head diameter for countersink holes.  Default: 0 
1865
1866function screw_info(name, head, drive, thread, drive_size, shaft_oversize, head_oversize, _origin) =
1867  assert(is_string(name), "Screw specification must be a string")
1868  let(
1869      thread = is_undef(thread) || thread==true ? "coarse"
1870             : thread==false || thread=="none" ? 0
1871             : thread,
1872      head = default(head,"none"),
1873      type=_parse_screw_name(name),
1874      drive_info = _parse_drive(drive, drive_size),
1875      drive=drive_info[0],
1876      screwdata =   type[0] == "english" ? _screw_info_english(type[1],type[2], head, thread, drive) 
1877                  : type[0] == "metric" ? _screw_info_metric(type[1], type[2], head, thread, drive) 
1878                  : []
1879    )
1880    assert(is_def(struct_val(screwdata,"head")),str("Screw head \"",head,"\" unknown or unsupported for specified screw"))
1881    _struct_reset(screwdata,
1882         [
1883          ["drive_depth", drive_info[2]],
1884          ["length", type[3]],
1885          ["drive_size", drive_info[1]],
1886          ["name", name],
1887          ["shaft_oversize", shaft_oversize],
1888          ["head_oversize", head_oversize],
1889          ["origin",_origin]
1890         ]);
1891      
1892
1893// Function: nut_info()
1894// Synopsis: Returns the dimensions and other info for the given nut.
1895// Topics: Threading, Screws
1896// See Also: screw(), screw_hole()
1897// Usage:
1898//   nut_spec = nut_info(name, [shape], [thickness=], [thread=], [width=], [hole_oversize=]);
1899// Description:
1900//   Produces a nut specification structure that describes a nut.  You can specify the width
1901//   and thickness numerically, or you can let the width be calculated automatically from
1902//   the thread specification.  The thickness can be "normal" (the default) or "thin" or "thick".
1903//   Note that square nuts are only available in "normal" thickness, and "thin" and "thick" nuts
1904//   are only available for 1/4 inch and above.  
1905//   .
1906//   The output is a [struct](structs.scad) with the following fields:
1907//   . 
1908//   Field              | What it is
1909//   ------------------ | ---------------
1910//   "type"           | Always set to "nut_info"
1911//   "system"         | Either `"UTS"` or `"ISO"` (used for correct tolerance computation).
1912//   "origin"         | Module that created the structure
1913//   "name"           | Name used to specify threading, such as "M6" or "#8"
1914//   "diameter"       | The nominal diameter of the screw hole in mm.
1915//   "pitch"          | The thread pitch in mm.  (0 for no threads)
1916//   "shape"          | Shape of the nut, either "hex" or "square"
1917//   "width"          | Flat to flat width of the nut
1918//   "thickness"      | Thickness of the nut
1919//   "shaft_oversize" | amount to oversize the threads (not including $slop)
1920// Arguments:
1921//   name = screw name, e.g. "M5x1" or "#8-32".  See [screw naming](#subsection-screw-naming).
1922//   shape = shape of the nut, either "hex" or "square".  Default: "hex"
1923//   ---
1924//   thread = thread type or specification. See [screw pitch](#subsection-standard-screw-pitch). Default: "coarse"
1925//   thickness = thickness of the nut (in mm) or one of "thin", "normal", or "thick".  Default: "normal"
1926//   width = width of nut in mm.  Default: computed from thread specification
1927//   hole_oversize = amount ot increase diameter of hole in nut.  Default: 0
1928
1929function nut_info(name, shape, thickness, thread, hole_oversize=0, width, _origin) =
1930  assert(is_undef(thickness) || (is_num(thickness) && thickness>0) ||
1931           in_list(_downcase_if_str(thickness),["thin","normal","thick","undersized","din"]),
1932          "thickness must be a positive number of one of \"thin\", \"thick\", \"normal\", \"undersized\", or \"DIN\"")
1933  let(
1934      shape = _downcase_if_str(default(shape,"hex")),
1935      thickness = _downcase_if_str(default(thickness, "normal"))
1936  )
1937  assert(is_string(name), str("Nut nameification must be a string ",name))
1938  assert(in_list(shape, ["hex","square"]), "Nut shape must be \"hex\" or \"square\"")
1939  assert(is_undef(width) || (is_num(width) && width>0), "Specified width must be a positive number")
1940  let(
1941      type = _parse_screw_name(name),
1942      thread = is_undef(thread) || thread==true ? "coarse"
1943             : thread==false || thread=="none" ? 0
1944             : thread,
1945      nutdata = type[0]=="english" ? _nut_info_english(type[1],type[2], thread, shape, thickness, width)
1946              : type[0]=="metric" ?  _nut_info_metric(type[1],type[2], thread, shape, thickness, width)
1947              : []
1948  )
1949  _struct_reset(nutdata, [["name", name],
1950                          ["shaft_oversize",hole_oversize],
1951                          ["width", width],
1952                          ["origin",_origin]
1953                         ]);
1954
1955
1956// Nut data is from ASME B18.2.2, mostly Table A-1
1957function _nut_info_english(diam, threadcount, thread, shape, thickness, width) =
1958  assert(!is_string(thickness) || in_list(thickness,["normal","thin","thick"]),
1959         "You cannot use thickness \"DIN\" or \"undersized\" with English nuts")
1960  let(
1961       screwspec=_screw_info_english(diam, threadcount, head="none", thread=thread),
1962       diameter = struct_val(screwspec,"diameter")/INCH,
1963       //         thickness  width
1964       normal = [
1965            ["#0", [ 3/64 , 5/32  ]],
1966            ["#1", [ 3/64 , 5/32  ]],
1967            ["#2", [ 1/16 , 3/16  ]],
1968            ["#3", [ 1/16 , 3/16  ]],
1969            ["#4", [ 3/32 ,  1/4  ]],
1970            ["#5", [ 7/64 , 5/16  ]],
1971            ["#6", [ 7/64 , 5/16  ]],
1972            ["#8", [  1/8 ,11/32  ]],
1973            ["#10",[  1/8 ,  3/8  ]],
1974            ["#12",[ 5/32 , 7/16  ]],
1975            [1/4,  [ 7/32 , 7/16  ]],
1976       ],
1977       thin = [  // thickness
1978            [1/4,  [ 5/32]],
1979            [5/16, [ 3/16]],
1980            [3/8,  [ 7/32]],
1981            [7/16, [  1/4]],
1982            [1/2,  [ 5/16]],
1983            [9/16, [ 5/16]],
1984            [5/8,  [  3/8]]
1985       ],
1986       thick = [
1987            [1/4,  [9/32 ]],
1988            [5/16, [21/64]],
1989            [3/8,  [13/32]],
1990            [7/16, [29/64]],
1991            [1/2,  [9/16]],
1992            [9/16, [39/64]],
1993            [5/8,  [23/32]],
1994            [3/4,  [13/16]],
1995            [7/8,  [29/32]],
1996            [1,    [1]],
1997            [1+1/8,[1+5/32]],
1998            [1+1/4,[1+1/4]],
1999            [1+3/8,[1+3/8]],
2000            [1+1/2,[1+1/2]]
2001       ]
2002  )
2003  assert(is_num(thickness) || thickness=="normal" || diameter >=1/4,
2004         str("No ", thickness, " nut available at requested thread size"))
2005  assert(diameter <= 1.5, "No thickness available for nut diameter over 1.5 inches")
2006  assert(shape=="hex" || thickness=="normal" || is_num(thickness),"Square nuts only come in normal thickness")
2007  let(
2008      table = thickness=="normal" ? normal
2009            : thickness=="thick" ? thick
2010            : thickness=="thin"  ? thin
2011            : [],
2012      entry = struct_val(table, diam),
2013      thickness = is_num(thickness) ? thickness/INCH
2014                : is_def(entry) ? entry[0]
2015                : shape=="square" ? ( approx(diameter,1.125) ? 1
2016                                                             : quantdn(7/8 * diameter,1/64))
2017                : thickness=="thin" ? (diameter < 1+3/16 ? quantdn(0.5*diameter + 3/64,1/64)
2018                                                         : 0.5*diameter + 3/32)
2019                  // remaining case is "normal" thickness
2020                : diameter < 11/16 ? quantdn(7/8*diameter,1/64)
2021                : diameter < 1+3/16 ? 7/8*diameter - 1/64
2022                : 7/8 * diameter - 1/32, 
2023      width = is_num(width) ? width/INCH
2024            : is_def(entry[1]) ? entry[1]
2025            : shape=="square" ? (diameter<5/8 ? quantup(1.5*diameter,1/16)+1/16 : 1.5*diameter)
2026            : quantup(1.5*diameter,1/16)
2027  )
2028  [["type","nut_info"],
2029   ["system", "UTS"],
2030   ["diameter", struct_val(screwspec, "diameter")],
2031   ["pitch", struct_val(screwspec,"pitch")],
2032   ["width", width*INCH],
2033   ["thickness", thickness*INCH],
2034   ["shape", shape]];
2035
2036
2037function _downcase_if_str(s) = is_string(s) ? downcase(s) : s;
2038
2039function _nut_info_metric(diam, pitch, thread, shape, thickness, width) =
2040  let(
2041       screwspec=_screw_info_metric(diam, pitch, head="none", thread=thread),
2042       diameter = struct_val(screwspec,"diameter"),
2043
2044       ISO_table =      //     - ASME B18.4.1M -    DIN 439
2045          //                   --- ISO 4032 ----   ISO 4035   ISO 4033 
2046          //                   normal     normal     thin       thick
2047          // diam    width     midpt      max        (max)      (max)
2048          // Preferred threads
2049          [
2050             [1.6,   [3.2 ,     1.2,       1.3,       1.0   ]],
2051             [2,     [4   ,     1.5,       1.6,       1.2   ]],
2052             [2.5,   [5   ,     1.875,     2,         1.6   ]],
2053             [3,     [5.5 ,     2.25,      2.4,       1.8   ]],
2054             [4,     [7   ,     3,         3.2,       2.2   ]],
2055             [5,     [8   ,     4.5 ,      4.7,       2.7,      5.1]],
2056             [6,     [10  ,     5,         5.2,       3.2,      5.7]],
2057             [8,     [13  ,     6.675,     6.8,      undef,      7.5]],
2058             [10,    [16  ,     8.25,      8.4,      undef,      9.3]],
2059             [12,    [18  ,     10.5,     10.8,      undef,     12  ]],
2060             [16,    [24  ,     14.5,     14.8,      undef,     16.4]],
2061             [20,    [30  ,     17.5,     18,        undef,     20.3]],
2062             [24,    [36  ,     21,       21.5,      undef,     23.9]],
2063             [30,    [46  ,     25,       25.6,      undef,     28.6]],
2064             [36,    [55  ,     30,       31,        undef,     34.7]],
2065             [42,    [65  ,     33,       34,        undef      ]],
2066             [48,    [75  ,     37,       38,        undef      ]],
2067             [56,    [85  ,     44,       45,        undef      ]],
2068             [64,    [95  ,     50,       51,        undef      ]],
2069          // Non-preferred threads
2070             [3.5,   [ 6,       2.675,     2.8,      2          ]],
2071             [14,    [21,      12.5,      12.8,      undef,     14.1]],
2072             [18,    [27,      15.5,      15.8,      undef,     17.6]],
2073             [22,    [34,      19,        19.4,      undef,     21.8]],
2074             [27,    [41,      23,        23.8,      undef,     26.7]],
2075             [33,    [50,      28,        28.7,      undef,     32.5]],
2076             [39,    [60,      33,        33.4,      undef      ]],
2077             [45,    [70,      35,        36,        undef      ]],
2078             [52,    [80,      41,        42,        undef      ]],
2079             [60,    [90,      47,        48,        undef      ]]
2080          ],
2081       DIN_table =
2082          [
2083             //                  DIN 934   DIN 936  DIN 562     DIN 557
2084             //diam      width   normal    thin    thin square   square
2085             [   1,    [   2.5,    0.8,   undef]],
2086             [   1.2,  [   3,      1  ,   undef]],
2087             [   1.4,  [   3,      1.2,   undef]],
2088             [   1.6,  [   3.2,    1.3,   undef,      1.0]],
2089             [   2,    [   4,      1.6,   undef,      1.2]],
2090             [   2.5,  [   5,      2  ,   undef,      1.6]],
2091             [   3,    [   5.5,    2.4,   undef,      1.8]],
2092             [   3.5,  [   6,      2.8,   undef,      2.0]],
2093             [   4,    [   7,      3.2,     2.8,      2.2]],
2094             [   5,    [   8,      4,       3.5,      2.7]],
2095             [   6,    [  10,      5,       4  ,      3.2]],
2096             [   7,    [  11,      5.5,     4  ]],
2097             [   8,    [  13,      6.5,     5        ]],
2098             [  10,    [  17,      8,       6        ]],     //
2099             [  12,    [  19,     10,       7  ]],  //
2100             [  14,    [  22,     11,       8  ]],  //
2101             [  16,    [  24,     13,       8  ]],
2102             [  18,    [  27,     15,       9  ]],
2103             [  20,    [  30,     16,       9  ]],
2104             [  22,    [  32,     18,      10  ]],  //
2105             [  24,    [  36,     19,      10  ]],
2106             [  27,    [  41,     22,      12  ]],
2107             [  30,    [  46,     24,      12  ]],
2108             [  33,    [  50,     26,      14  ]],
2109             [  36,    [  55,     29,      14  ]],
2110             [  39,    [  60,     31,      16  ]],
2111             [  42,    [  65,     34,      16  ]],
2112             [  45,    [  70,     36,      18  ]],
2113             [  48,    [  75,     38,      18  ]],
2114             [  52,    [  80,     42,      20  ]],
2115             [  56,    [  85,     45]],
2116             [  60,    [  90,     48]],
2117             [  64,    [  95,     51]],
2118             [  68,    [ 100,     54]],
2119             [  72,    [ 105,     58]],
2120             [  76,    [ 110,     61]],
2121             [  80,    [ 115,     64]],
2122             [  85,    [ 120,     68]],
2123             [  90,    [ 130,     72]],
2124             [ 100,    [ 145,     80]],
2125             [ 110,    [ 155,     88]],
2126             [ 125,    [ 180,    100]],
2127             [ 140,    [ 200,    112]],
2128             [ 160,    [ 230,    128]]
2129          ],
2130          useDIN = thickness=="din" || thickness=="undersized" || shape=="square", 
2131          entry = struct_val(useDIN ? DIN_table : ISO_table, diameter),
2132          width = is_def(width) ? width
2133                : entry[0],
2134          thickind = useDIN && thickness=="thin" ? 3
2135                   : useDIN ? 1 
2136                   : thickness=="normal" ? 2
2137                   : thickness=="thin" ? 3
2138                   : thickness=="thick" ? 4
2139                   : undef,
2140          thickness = is_num(thickness) ? thickness
2141                    : is_def(entry[thickind]) ? entry[thickind]
2142                    : thickness=="thin" && diameter > 8 ? diam/2
2143                    : undef
2144  )
2145  assert(is_def(thickness) && is_def(width), "Unknown thickness, size and shape combination for nut")
2146  [["type","nut_info"],
2147   ["system", "ISO"],
2148   ["diameter", struct_val(screwspec, "diameter")],
2149   ["pitch", struct_val(screwspec,"pitch")],
2150   ["width", width],
2151   ["thickness", thickness],
2152   ["shape", shape]];
2153          
2154
2155function _screw_info_english(diam, threadcount, head, thread, drive) =
2156 let(
2157   diameter = is_string(diam) ? parse_int(substr(diam,1))*0.013 +0.06 
2158                              : diam,
2159   diamgroup = diameter<7/16 ? 0
2160             : diameter==7/16 ? 1
2161             : 2,
2162   pitch =
2163     is_num(thread) ? thread :
2164     is_def(threadcount) ? INCH/threadcount :
2165     let(
2166        tind=struct_val([["coarse",0],["unc",0],
2167                         ["fine",1],["unf",1],
2168                         ["extra fine",2],["extrafine",2],["unef",2]],
2169                         downcase(thread)),
2170        dummy = assert(is_def(tind), str("Unknown thread type, \"",thread,"\"")),
2171                 // coarse  fine  xfine
2172                 // UNC     UNF   UNEF
2173        UTS_thread = [
2174            ["#0", [undef,    80, undef]],
2175            ["#1", [   64,    72, undef]],
2176            ["#2", [   56,    64, undef]],
2177            ["#3", [   48,    56, undef]],
2178            ["#4", [   40,    48, undef]],
2179            ["#5", [   40,    44, undef]],
2180            ["#6", [   32,    40, undef]],
2181            ["#8", [   32,    36, undef]],
2182            ["#10",[   24,    32, undef]],
2183            ["#12",[   24,    28,    32]],
2184            [1/4,  [   20,    28,    32]],
2185            [5/16, [   18,    24,    32]],
2186            [3/8,  [   16,    24,    32]],
2187            [7/16, [   14,    20,    28]],
2188            [1/2,  [   13,    20,    28]],
2189            [9/16, [   12,    18,    24]],
2190            [5/8,  [   11,    18,    24]],
2191            [3/4,  [   10,    16,    20]],
2192            [7/8,  [    9,    14,    20]],
2193            [1,    [    8,    12,    20]],
2194            [1.125,[    7,    12,    18]],
2195            [1.25, [    7,    12,    18]],
2196            [1.375,[    6,    12,    18]],
2197            [1.5,  [    6,    12,    18]],
2198            [1.75, [    5, undef, undef]],
2199            [2,    [  4.5, undef, undef]],
2200         ],
2201       tentry = struct_val(UTS_thread, diam)
2202     )
2203     assert(is_def(tentry), str("Unknown screw size, \"",diam,"\""))
2204     assert(is_def(tentry[tind]), str("No ",thread," pitch known for screw size, \"",diam,"\""))
2205     INCH / tentry[tind],
2206   head_data =
2207       head=="none" ? let (
2208          UTS_setscrew = [
2209               // hex width, hex depth torx,  torx depth    slot width   slot depth 
2210            ["#0", [0.028,   0.050,   undef,     undef,       0.012,       0.018]],
2211            ["#1", [0.035,   0.060,   undef,     undef,       0.014,       0.018]],
2212            ["#2", [0.035,   0.060,   undef,     undef,       0.016,       0.022]],
2213            ["#3", [0.05 ,   0.070,   undef,     undef,       0.018,       0.025]],
2214            ["#4", [0.05 ,   0.045,      6,      0.027,       0.021,       0.028]],
2215            ["#5", [1/16 ,   0.080,      7,      0.036,       0.023,       0.031]],
2216            ["#6", [1/16 ,   0.080,      7,      0.036,       0.025,       0.035]],
2217            ["#8", [5/64 ,   0.090,      8,      0.041,       0.029,       0.041]],
2218            ["#10",[3/32 ,   0.100,      10,     0.049,       0.032,       0.048]],
2219            ["#12",[undef,   undef,   undef,    undef,        0.038,       0.056]],
2220            [1/4,  [1/8  ,   0.125,      15,     0.068,       0.045,       0.063]],
2221            [5/16, [5/32 ,   0.156,      25,     0.088,       0.051,       0.078]],
2222            [3/8,  [3/16 ,   0.188,      30,     0.097,       0.064,       0.094]],
2223            [7/16, [7/32 ,   0.219,      40,     0.117,       0.072,       0.109]],
2224            [1/2,  [1/4  ,   0.250,      45,     0.137,       0.081,       0.125]],
2225            [9/16, [undef,   undef,   undef,    undef,        0.091,       0.141]],
2226            [5/8,  [5/16 ,   0.312,      55,     0.202,       0.102,       0.156]],
2227            [3/4,  [3/8  ,   0.375,      60,     0.202,       0.129,       0.188]],
2228            [7/8,  [1/2  ,   0.500,      70,     0.291]],     
2229            [1,    [9/16 ,   0.562,      70,     0.291]],     
2230            [1.125,[9/16 ,   0.562]],
2231            [1.25, [5/8  ,   0.625]],
2232            [1.375,[5/8  ,   0.625]],
2233            [1.5,  [3/4  ,   0.750]],
2234            [1.75, [1    ,   1.000]],
2235            [2,    [1    ,   1.000]],
2236            ],
2237          entry = struct_val(UTS_setscrew, diam),
2238          dummy=assert(is_def(entry), str("Screw size ",diam," unsupported for headless screws")),
2239          drive_dims = drive == "hex" ? [["drive_size", INCH*entry[0]], ["drive_depth", INCH*entry[1]]]
2240                     : drive == "torx" ? [["drive_size", entry[2]], ["drive_depth", INCH*entry[3]]] 
2241                     : drive == "slot" ? [["drive_size", INCH*entry[4]], ["drive_depth", INCH*entry[5]]]
2242                     : []
2243         ) concat([["head","none"]], drive_dims) 
2244     : head=="hex" ? let( 
2245            UTS_hex = [
2246               // flat to flat width, height
2247               ["#2", [    1/8,   1/16]],
2248               ["#4", [   3/16,   1/16]],
2249               ["#6", [    1/4,   3/32]],
2250               ["#8", [    1/4,   7/64]],
2251               ["#10",[   5/16,    1/8]],
2252               ["#12",[   5/16,   5/32]],
2253               [1/4,  [   7/16,   5/32]],
2254               [5/16, [    1/2,  13/64]],
2255               [3/8,  [   9/16,    1/4]],
2256               [7/16, [    5/8,  19/64]],
2257               [1/2,  [    3/4,  11/32]],
2258               [9/16, [  13/16,  23/64]],
2259               [5/8,  [  15/16,  27/64]],
2260               [3/4,  [  1.125,    1/2]],
2261               [7/8,  [ 1+5/16,  37/64]],
2262               [1,    [    1.5,  43/64]],
2263               [1.125,[1+11/16,  11/16]],
2264               [1.25, [  1+7/8,  27/32]],
2265               [1.5,  [   2.25,  15/16]],
2266               [1.75, [  2+5/8, 1+3/32]],
2267               [2,    [      3, 1+7/32]],
2268            ],
2269            entry = struct_val(UTS_hex, diam)
2270           )
2271           assert(is_def(entry), str("Screw size ",diam," unsupported for head type \"",head,"\""))
2272           [["head", "hex"], ["head_size", INCH*entry[0]], ["head_height", INCH*entry[1]]] 
2273     : in_list(head,["socket","socket ribbed"]) ? let(
2274            UTS_socket = [    // height = screw diameter
2275                       //diam,   hex, torx size, hex depth, torx depth
2276               ["#0", [  0.096,  0.05, 6,         0.025,      0.027]],
2277               ["#1", [  0.118,  1/16, 7,         0.031,      0.036]],
2278               ["#2", [   9/64,  5/64, 8,         0.038,      0.037]],
2279               ["#3", [  0.161,  5/64, 8,         0.044,      0.041]],   // For larger sizes, hex recess depth is
2280               ["#4", [  0.183,  3/32, 10,        0.051,      0.049]],   // half the screw diameter
2281               ["#5", [  0.205,  3/32, 10,        0.057,      0.049]],
2282               ["#6", [  0.226,  7/64, 15,        0.064,      0.058]],
2283               ["#8", [  0.270,  9/64, 25,        0.077,      0.078]],
2284               ["#10",[   5/16,  5/32, 27,        undef,      0.088]],
2285               ["#12",[  0.324,  5/32, 27,        undef,      0.088]],
2286               [1/4,  [    3/8,  3/16, 30,        undef,      0.097]],
2287               [5/16, [  15/32,   1/4, 45,        undef,      0.137]],
2288               [3/8,  [   9/16,  5/16, 50,        undef,      0.155]],
2289               [7/16, [  21/32,   3/8, 55,        undef,      0.202]],
2290               [1/2,  [    3/4,   3/8, 55,        undef,      0.202]],
2291               [9/16, [  27/32,  7/16, 60,        undef,      0.240]],
2292               [5/8,  [  15/16,   1/2, 70,        undef,      0.291]],
2293               [3/4,  [  1.125,   5/8, 80,        undef,      0.332]],
2294               [7/8,  [ 1+5/16,   3/4, 100,       undef,      0.425]],
2295               [1,    [    1.5,   3/4, 100,       undef,      0.425]],
2296               [1.125,[1+11/16,   7/8, undef,     undef,      undef]],
2297               [1.25, [  1+7/8,   7/8, undef,     undef,      undef]],
2298               [1.375,[ 2+1/16,     1, undef,     undef,      undef]],
2299               [1.5,  [   2.25,     1, undef,     undef,      undef]],
2300               [1.75, [  2+5/8,  1.25, undef,     undef,      undef]],
2301               [2,    [      3,   1.5, undef,     undef,      undef]],
2302            ],
2303            entry = struct_val(UTS_socket, diam),
2304            dummy=assert(is_def(entry), str("Screw size ",diam," unsupported for head type \"",head,"\"")),
2305            hexdepth = is_def(entry[3]) ? entry[3]
2306                     : is_def(diameter) ? diameter/2
2307                     : undef,
2308            drive_size =  drive=="hex" ? [["drive_size",INCH*entry[1]], ["drive_depth",INCH*hexdepth]] :
2309                          drive=="torx" ? [["drive_size",entry[2]],["drive_depth",INCH*entry[4]]] : []
2310            )
2311            concat([["head",head],["head_size",INCH*entry[0]], ["head_height", INCH*diameter]],drive_size) 
2312     : head=="pan" ? let (
2313           UTS_pan = [  // pan head for phillips or slotted
2314                 //              head height 
2315                 //    diam,   slotted  phillips  phillips drive, phillips diam, phillips width, phillips depth, slot width, slot depth  torx size
2316               ["#0", [0.116,   0.039,   0.044,        0,          0.067,          0.013,           0.039,       0.023,         0.022]],
2317               ["#1", [0.142,   0.046,   0.053,        0,          0.085,          0.015,           0.049,       0.027,         0.027]],
2318               ["#2", [0.167,   0.053,   0.063,        1,          0.104,          0.017,           0.059,       0.031,         0.031,      8]],
2319               ["#3", [0.193,   0.060,   0.071,        1,          0.112,          0.019,           0.068,       0.035,         0.036]],
2320               ["#4", [0.219,   0.068,   0.080,        1,          0.122,          0.019,           0.078,       0.039,         0.040,     10]],
2321               ["#5", [0.245,   0.075,   0.089,        2,          0.158,          0.028,           0.083,       0.043,         0.045]],
2322               ["#6", [0.270,   0.082,   0.097,        2,          0.166,          0.028,           0.091,       0.048,         0.050,     15]],
2323               ["#8", [0.322,   0.096,   0.115,        2,          0.182,          0.030,           0.108,       0.054,         0.058,     20]],
2324               ["#10",[0.373,   0.110,   0.133,        2,          0.199,          0.031,           0.124,       0.060,         0.068,     25]],
2325               ["#12",[0.425,   0.125,   0.151,        3,          0.259,          0.034,           0.141,       0.067,         0.077]],
2326               [1/4,  [0.492,   0.144,   0.175,        3,          0.281,          0.036,           0.161,       0.075,         0.087,     30]],
2327               [5/16, [0.615,   0.178,   0.218,        4,          0.350,          0.059,           0.193,       0.084,         0.106]],
2328               [3/8,  [0.740,   0.212,   0.261,        4,          0.389,          0.065,           0.233,       0.094,         0.124]],
2329            ],
2330            htind = drive=="slot" ? 1 : 2,
2331            entry = struct_val(UTS_pan, diam),
2332            dummy=assert(is_def(entry), str("Screw size ",diam," unsupported for head type \"",head,"\"")),
2333            drive_size = drive=="phillips" ? [["drive_size", entry[3]],
2334                                             // ["drive_diameter",INCH*entry[4]],
2335                                             // ["drive_width",INCH*entry[5]],
2336                                              ["drive_depth",INCH*entry[6]]]
2337                                           : [["drive_size", INCH*entry[7]],
2338                                              ["drive_depth",INCH*entry[8]]])
2339           concat([["head","pan round"], ["head_size", INCH*entry[0]], ["head_height", INCH*entry[htind]]], drive_size) 
2340     : head=="button" || head=="round" ? let(
2341            UTS_button = [    // button, hex or torx drive
2342                 //   head diam, height, phillips, hex,   torx, hex depth
2343               ["#0", [0.114,    0.032,   undef,   0.035,  5    , 0.020, 0.015]],
2344               ["#1", [0.139,    0.039,   undef,   3/64,   5    , 0.028, 0.022]],
2345               ["#2", [0.164,    0.046,   undef,   3/64,   6    , 0.028, 0.023]],
2346               ["#3", [0.188,    0.052,   undef,   1/16,   undef, 0.035, undef]],
2347               ["#4", [0.213,    0.059,   undef,   1/16,   8    , 0.035, 0.032]],
2348               ["#5", [0.238,    0.066,   undef,   5/64,   10   , 0.044, 0.038]],
2349               ["#6", [0.262,    0.073,   undef,   5/64,   10   , 0.044, 0.038]],
2350               ["#8", [0.312,    0.087,   undef,   3/32,   15   , 0.052, 0.045]],
2351               ["#10",[0.361,    0.101,   undef,   1/8,    25   , 0.070, 0.052]],
2352               ["#12",[0.413,    0.114,   undef,   1/8,    undef, 0.070, undef]],   // also 0.410, .115, 9/64, hex depth guessed
2353               [1/4,  [0.437,    0.132,   undef,   5/32,   27   , 0.087, 0.068]],
2354               [5/16, [0.547,    0.166,   undef,   3/16,   40   , 0.105, 0.090]],
2355               [3/8,  [0.656,    0.199,   undef,   7/32,   45   , 0.122, 0.106]],
2356               [7/16, [0.750,    0.220,   undef,   1/4,    undef, 0.193, undef]],  // hex depth interpolated
2357               [1/2,  [0.875,    0.265,   undef,   5/16,   55   , 0.175, 0.158]],
2358               [5/8,  [1.000,    0.331,   undef,   3/8,    60   , 0.210, 0.192]],
2359               [3/4,  [1.1,      0.375,   undef,   7/16,   undef, 0.241]],  // hex depth extrapolated
2360             ],
2361             UTS_round = [   // slotted, phillips
2362                  // head diam, head height, phillips drive, hex, torx, ph diam, ph width, ph depth, slot width, slot depth
2363               ["#0", [0.113, 0.053, 0, undef, undef]],
2364               ["#1", [0.138, 0.061, 0, undef, undef]],
2365               ["#2", [0.162, 0.069, 1, undef, undef, 0.100, 0.017, 0.053, 0.031, 0.048]],
2366               ["#3", [0.187, 0.078, 1, undef, undef, 0.109, 0.018, 0.062, 0.035, 0.053]],
2367               ["#4", [0.211, 0.086, 1, undef, undef, 0.118, 0.019, 0.072, 0.039, 0.058]],
2368               ["#5", [0.236, 0.095, 2, undef, undef, 0.154, 0.027, 0.074, 0.043, 0.063]],
2369               ["#6", [0.260, 0.103, 2, undef, undef, 0.162, 0.027, 0.084, 0.048, 0.068]],
2370               ["#8", [0.309, 0.120, 2, undef, undef, 0.178, 0.030, 0.101, 0.054, 0.077]],
2371               ["#10",[0.359, 0.137, 2, undef, undef, 0.195, 0.031, 0.119, 0.060, 0.087]],
2372               ["#12",[0.408, 0.153, 3, undef, undef, 0.249, 0.032, 0.125, 0.067, 0.096]],
2373               [1/4,  [0.472, 0.175, 3, undef, undef, 0.268, 0.034, 0.147, 0.075, 0.109]],
2374               [5/16, [0.590, 0.216, 3, undef, undef, 0.308, 0.040, 0.187, 0.084, 0.132]],
2375               [3/8,  [0.708, 0.256, 4, undef, undef, 0.387, 0.064, 0.228, 0.094, 0.155]],
2376               [1/2,  [0.813, 0.355, 4, undef, undef, 0.416, 0.068, 0.256, 0.106, 0.211]]
2377             ],
2378             entry = struct_val(head=="button" ? UTS_button : UTS_round, diam),
2379             dummy=assert(is_def(entry), str("Screw size ",diam," unsupported for head type \"",head,"\"")),
2380             drive_index = drive=="phillips" ? 2 :
2381                           drive=="hex" ? 3 :
2382                           drive=="torx" ? 4 : undef,
2383             drive_size = drive=="phillips" && head=="round" ? [["drive_size", entry[2]],
2384                                                               // ["drive_diameter",u_mul(INCH,entry[5])],
2385                                                               // ["drive_width",INCH*entry[6]],
2386                                                                ["drive_depth",INCH*entry[7]]]
2387                        : drive=="slot" && head=="round" ?  [["drive_size", INCH*entry[8]],
2388                                                             ["drive_depth",u_mul(INCH,entry[9])]]
2389                        : drive=="hex" && head=="button" ? [["drive_size", INCH*entry[drive_index]],
2390                                                            ["drive_depth", u_mul(INCH,entry[5])]]
2391                        : drive=="torx" && head=="button" ? [["drive_size", entry[drive_index]],
2392                                                             ["drive_depth", u_mul(INCH,entry[6])]]
2393                        : is_def(drive_index) && head=="button" ? [["drive_size", entry[drive_index]]] : []
2394             )
2395             concat([["head",head],["head_size",INCH*entry[0]], ["head_height", INCH*entry[1]]],drive_size) 
2396     : head=="fillister" ? let(
2397             UTS_fillister = [ // head diam, head height, slot width, slot depth, phillips diam, phillips depth, phillips width, phillips #
2398                   ["#0", [0.096, 0.055, 0.023, 0.025, 0.067, 0.039, 0.013, 0]],
2399                   ["#1", [0.118, 0.069, 0.027, 0.031, 0.085, 0.049, 0.015,  ]],
2400                   ["#2", [0.140, 0.083, 0.031, 0.037, 0.104, 0.059, 0.017,  ]],
2401                   ["#3", [0.161, 0.095, 0.035, 0.043, 0.112, 0.068, 0.019, 1]],
2402                   ["#4", [0.183, 0.107, 0.039, 0.048, 0.122, 0.078, 0.019, 1]],
2403                   ["#5", [0.205, 0.120, 0.043, 0.054, 0.143, 0.067, 0.027, 2]],
2404                   ["#6", [0.226, 0.132, 0.048, 0.060, 0.166, 0.091, 0.028, 2]],
2405                   ["#8", [0.270, 0.156, 0.054, 0.071, 0.182, 0.108, 0.030, 2]],
2406                   ["#10",[0.313, 0.180, 0.060, 0.083, 0.199, 0.124, 0.031, 2]],
2407                   ["#12",[0.357, 0.205, 0.067, 0.094, 0.259, 0.141, 0.034, 3]],
2408                   [1/4,  [0.414, 0.237, 0.075, 0.109, 0.281, 0.161, 0.036, 3]],
2409                   [5/16, [0.518, 0.295, 0.084, 0.137, 0.322, 0.203, 0.042, 3]],
2410                   [3/8,  [0.622, 0.355, 0.094, 0.164, 0.389, 0.233, 0.065, 4]],
2411             ],
2412             entry = struct_val(UTS_fillister, diam),
2413             dummy=assert(is_def(entry), str("Screw size ",diam," unsupported for head type \"",head,"\"")),
2414             drive_size = drive=="phillips" ? [["drive_size", entry[7]],
2415                                            //   ["drive_diameter",INCH*entry[4]],
2416                                            //   ["drive_width",INCH*entry[6]],
2417                                               ["drive_depth",INCH*entry[5]]] 
2418                        : drive=="slot"?  [["drive_size", INCH*entry[2]],
2419                                           ["drive_depth",INCH*entry[3]]] : []
2420             )
2421             concat([["head", "fillister"], ["head_size", INCH*entry[0]], ["head_height", INCH*entry[1]]], drive_size) 
2422     : starts_with(head,"flat ") || head=="flat" ? 
2423         let(
2424             headparts = str_split(head," ",keep_nulls=false),
2425             partsok = [for (part=headparts) if (!in_list(part, ["flat","undercut","100","82","small","large","sharp"])) part], 
2426             dummy1=assert(partsok==[], str("Unknown flat head parameter(s) ",partsok)),
2427             dummy2=assert(!(in_list("small",headparts) && in_list("large",headparts)), "Cannot specify large and small flat head at the same time"),
2428             undercut = in_list("undercut", headparts),
2429             small = in_list("small",headparts) || (!in_list("large",headparts) && drive!="hex" && drive!="torx"),
2430             angle = in_list("100", headparts) ? 100 : 82,
2431             dummy3=assert(!undercut || angle==82, "Cannot make undercut 100 degree screw"),
2432             dummy4=assert(small || angle==82, "Only 82 deg large screws are supported"),
2433             dummy5=assert(small || !undercut, "Undercut only supported for small flatheads"),
2434             UTS_flat_small = [  // for phillips drive, slotted, and torx   ASME B18.6.3
2435                    //                     ----- Phillips ----              undercut phillips
2436                    //    ph drive, torx , diam,  depth, width, slotwidth,  diam, depth, width
2437                    //       0       1       2      3      4        5           6        7  
2438                   ["#0", [  0,     undef, 0.062, 0.035, 0.014,   0.023,   0.062, 0.035, 0.014]],
2439                   ["#1", [  0,     undef, 0.070, 0.043, 0.015,   0.026,   0.070, 0.043, 0.015]],
2440                   ["#2", [  1,     6    , 0.096, 0.055, 0.017,   0.031,   0.088, 0.048, 0.017]],
2441                   ["#3", [  1,     undef, 0.100, 0.060, 0.018,   0.035,   0.099, 0.059, 0.018]],
2442                   ["#4", [  1,     8    , 0.122, 0.081, 0.018,   0.039,   0.110, 0.070, 0.018]],
2443                   ["#5", [  2,     undef, 0.148, 0.074, 0.027,   0.043,   0.122, 0.081, 0.018]], //ph#1 for undercut
2444                   ["#6", [  2,     10   , 0.168, 0.094, 0.029,   0.048,   0.140, 0.066, 0.025]],
2445                   ["#8", [  2,     15   , 0.182, 0.110, 0.030,   0.054,   0.168, 0.094, 0.029]],
2446                   ["#10",[  2,     20   , 0.198, 0.124, 0.032,   0.060,   0.182, 0.110, 0.030]],
2447                   ["#12",[  3,     undef, 0.262, 0.144, 0.035,   0.067,   0.226, 0.110, 0.030]],
2448                   [1/4,  [  3,     27   , 0.276, 0.160, 0.036,   0.075,   0.244, 0.124, 0.032]],
2449                   [5/16, [  4,     40   , 0.358, 0.205, 0.061,   0.084,   0.310, 0.157, 0.053]],
2450                   [3/8,  [  4,     40   , 0.386, 0.234, 0.065,   0.094,   0.358, 0.205, 0.061]],
2451                   [1/2,  [  4,     undef, 0.418, 0.265, 0.069,   0.106,   0.402, 0.252, 0.068]]
2452             ],
2453             UTS_flat_small_100 = [  // for phillips drive, slotted, 100 deg angle  ASME B18.6.3
2454                    //                     ----- Phillips ----            
2455                    //    ph drive, torx , diam,  depth, width, slotwidth
2456                    //       0       1       2      3      4        5    
2457                   ["#0", [  0,     undef, 0.054, 0.027, 0.013,   0.023]],
2458                   ["#1", [  0,     undef, 0.062, 0.035, 0.014,   0.026]],
2459                   ["#2", [  1,     6    , 0.088, 0.048, 0.012,   0.031]],
2460                   ["#3", [  1,     undef, 0.096, 0.055, 0.014,   0.035]],
2461                   ["#4", [  1,     8    , 0.110, 0.070, 0.018,   0.039]],
2462                   ["#6", [  2,     10   , 0.148, 0.074, 0.027,   0.048]],
2463                   ["#8", [  2,     15   , 0.162, 0.090, 0.028,   0.054]],
2464                   ["#10",[  2,     20   , 0.178, 0.104, 0.030,   0.060]],
2465                   [1/4,  [  3,     27   , 0.240, 0.124, 0.033,   0.075]],
2466                   [5/16, [  4,     40   , 0.310, 0.157, 0.053,   0.084]],
2467                   [3/8,  [  4,     40   , 0.336, 0.182, 0.056,   0.094]],
2468             ],
2469             UTS_flat_large = [   // for hex drive, torx     ASME B18.3
2470                       // minimum
2471                       // head diam, hex drive size, torx size, hex depth, torx depth
2472                   ["#0", [ 0.117,   1/32,            3    ,     0.025,    0.016]],
2473                   ["#1", [ 0.143,   3/64,            6    ,     0.031,    0.036]],
2474                   ["#2", [ 0.168,   3/64,            6    ,     0.038,    0.036]],
2475                   ["#3", [ 0.193,   1/16,            8    ,     0.044,    0.041]],
2476                   ["#4", [ 0.218,   1/16,            10   ,     0.055,    0.038]],
2477                   ["#5", [ 0.240,   5/64,            10   ,     0.061,    0.038]],
2478                   ["#6", [ 0.263,   5/64,            15   ,     0.066,    0.045]],
2479                   ["#8", [ 0.311,   3/32,            20   ,     0.076,    0.053]],
2480                   ["#10",[ 0.359,    1/8,            25   ,     0.087,    0.061]],
2481                   [1/4,  [ 0.480,   5/32,            30   ,     0.111,    0.075]],
2482                   [5/16, [ 0.600,   3/16,            40   ,     0.135,    0.090]],
2483                   [3/8,  [ 0.720,   7/32,            45   ,     0.159,    0.106]],
2484                   [7/16, [ 0.781,    1/4,            50   ,     0.172,    0.120]],
2485                   [1/2,  [ 0.872,   5/16,            50   ,     0.220,    0.120]],
2486                   [5/8,  [ 1.112,    3/8,            55   ,     0.220,    0.158]],
2487                   [3/4,  [ 1.355,    1/2,            60   ,     0.248,    0.192]],
2488                   [7/8,  [ 1.604,   9/16,            undef,     0.297,    undef]],
2489                   [1,    [ 1.841,    5/8,            undef,     0.325,    undef]],
2490                   [1.125,[ 2.079,    3/4,            undef,     0.358,    undef]],
2491                   [1.25, [ 2.316,    7/8,            undef,     0.402,    undef]],
2492                   [1.375,[ 2.688,    7/8,            undef,     0.402,    undef]],
2493                   [1.5,  [ 2.938,      1,            undef,     0.435,    undef]],
2494             ],
2495             entry = struct_val(    angle==100 ? UTS_flat_small_100 
2496                                  : small ? UTS_flat_small 
2497                                  : UTS_flat_large, 
2498                                diam),
2499             dummy=assert(is_def(entry), str("Screw size ",diam," unsupported for head type \"",head,"\"")),
2500             a=[1.92+1.82, 1.88+1.8, 1.88+1.8]/2,
2501             b=[.003+.013, .063+.073, .125+.135]/2,
2502             smallsize = a[diamgroup]*diameter-b[diamgroup],
2503     
2504             csmall=[2.04, 2, 2],
2505             dsmall=[.003, .063, .125], 
2506             dlarge = [-.031, .031, .062],
2507             sharpsize = small ? csmall[diamgroup]*diameter-dsmall[diamgroup] // max theoretical (sharp) head diam
2508                                     : diameter < 0.1 ? [0.138,0.168,0.0822,0.0949][(diameter - 0.06)/.013] 
2509                                     : 2*diameter-dlarge[diamgroup],
2510             largesize = lerp(entry[0],sharpsize,.20),   // Have min size and max theory size.  Use point 20% up from min size
2511             undercut_height = let(
2512                                   a=[.432+.386, .417+.37, .417+.37]/2,
2513                                   b=[.001+.005, .026+.029, .052+.055]/2
2514                               )
2515                               a[diamgroup]*diameter + b[diamgroup],
2516             e=undercut ? [.202+.134, .192+.129, .192+.129]/2 
2517              : angle==100 ? [.222+.184]/2 
2518              : [.288+.192, .274+.184, .274+.184]/2,
2519             f=undercut ? [.002, .012+.011, .024+.019]/2
2520              : angle==100 ? [.0005+.004]/2 
2521              : [.004, .015+.017, .034+.027],
2522             tipdepth_small = e[diamgroup]*diameter + f[diamgroup],
2523             driveind = small && drive=="phillips" ? 0
2524                      : !small && drive=="hex" ? 1 
2525                      : drive=="torx" ? 2 
2526                      : undef,
2527             drive_dims = small ? (
2528                            drive=="phillips" && !undercut ? [
2529                                                            //  ["drive_diameter",INCH*entry[2]],
2530                                                            //  ["drive_width",INCH*entry[4]],
2531                                                              ["drive_depth",INCH*entry[3]]
2532                                                             ]
2533                          : drive=="phillips" && undercut ?  [
2534                                                             // ["drive_diameter",INCH*entry[6]],
2535                                                             // ["drive_width",INCH*entry[8]],
2536                                                              ["drive_depth",INCH*entry[7]]
2537                                                             ] 
2538                          : drive=="slot" ? [["drive_size", INCH*entry[5]], 
2539                                             ["drive_depth", INCH*tipdepth_small]] :
2540                            
2541                            []
2542                            )
2543                         :
2544                           (
2545                             drive=="hex" ? [["drive_depth", INCH*entry[3]]] :
2546                             drive=="torx" ? [["drive_depth", INCH*entry[4]]] : []
2547                           )
2548         )
2549         [
2550           ["head","flat"],
2551           ["head_angle",angle],
2552           ["head_size", in_list("sharp",headparts) ? sharpsize*INCH
2553                        : small ? smallsize*INCH : largesize*INCH], //entry[0]*INCH],
2554           ["head_size_sharp", sharpsize*INCH],
2555           if (is_def(driveind)) ["drive_size", (drive=="hex"?INCH:1)*entry[driveind]],
2556           if (undercut) ["head_height", undercut_height*INCH],
2557           each drive_dims
2558         ]
2559     : []
2560 )
2561 concat([
2562           ["type","screw_info"],
2563           ["system","UTS"],
2564           ["diameter",INCH*diameter],
2565           ["pitch", pitch],
2566           ["drive",drive]
2567         ],
2568         head_data
2569 );
2570
2571
2572function _screw_info_metric(diam, pitch, head, thread, drive) =
2573 let(
2574   pitch =
2575     is_num(thread) ? thread :
2576     is_def(pitch) ? pitch :
2577     let(
2578        tind=struct_val([["coarse",0],
2579                         ["fine",1],
2580                         ["extra fine",2],["extrafine",2],
2581             ["super fine",3],["superfine",3]],
2582                         downcase(thread)),
2583        dummy = assert(is_def(tind), str("Unknown thread type, \"",thread,"\"")),
2584                            // coarse  fine  xfine superfine
2585        ISO_thread = [
2586                      [1  , [0.25,    0.2 ,   undef, undef,]],
2587                      [1.2, [0.25,    0.2 ,   undef, undef,]],
2588                      [1.4, [0.3 ,    0.2 ,   undef, undef,]],
2589                      [1.6, [0.35,    0.2 ,   undef, undef,]],
2590                      [1.7, [0.35,   undef,   undef, undef,]],
2591                      [1.8, [0.35,    0.2 ,   undef, undef,]],
2592                      [2  , [0.4 ,    0.25,   undef, undef,]],
2593                      [2.2, [0.45,    0.25,   undef, undef,]],
2594                      [2.3, [0.4 ,   undef,   undef, undef,]],
2595                      [2.5, [0.45,    0.35,   undef, undef,]],
2596                      [2.6, [0.45,   undef,   undef, undef,]],
2597                      [3  , [0.5 ,    0.35,   undef, undef,]],
2598                      [3.5, [0.6 ,    0.35,   undef, undef,]],
2599                      [4  , [0.7 ,    0.5 ,   undef, undef,]],
2600                      [5  , [0.8 ,    0.5 ,   undef, undef,]],
2601                      [6  , [1   ,    0.75,   undef, undef,]],
2602                      [7  , [1   ,    0.75,   undef, undef,]],
2603                      [8  , [1.25,    1   ,    0.75, undef,]],
2604                      [9  , [1.25,    1   ,    0.75, undef,]],
2605                      [10 , [1.5 ,    1.25,    1   ,  0.75,]],
2606                      [11 , [1.5 ,    1   ,    0.75, undef,]],
2607                      [12 , [1.75,    1.5 ,    1.25,  1,   ]],
2608                      [14 , [2   ,    1.5 ,    1.25,  1,   ]],
2609                      [16 , [2   ,    1.5 ,    1   , undef,]],
2610                      [18 , [2.5 ,    2   ,    1.5 ,  1,   ]],
2611                      [20 , [2.5 ,    2   ,    1.5 ,  1,   ]],
2612                      [22 , [2.5 ,    2   ,    1.5 ,  1,]],
2613                      [24 , [3   ,    2   ,    1.5 ,  1,]],
2614                      [27 , [3   ,    2   ,    1.5 ,  1,]],
2615                      [30 , [3.5 ,    3   ,    2   ,  1.5,]],
2616                      [33 , [3.5 ,    3   ,    2   ,  1.5,]],
2617                      [36 , [4   ,    3   ,    2   ,  1.5,]],
2618                      [39 , [4   ,    3   ,    2   ,  1.5,]],
2619                      [42 , [4.5 ,    4   ,    3   ,  2,]],
2620                      [45 , [4.5 ,    4   ,    3   ,  2,]],
2621                      [48 , [5   ,    4   ,    3   ,  2,]],
2622                      [52 , [5   ,    4   ,    3   ,  2,]],
2623                      [56 , [5.5 ,    4   ,    3   ,  2,]],
2624                      [60 , [5.5 ,    4   ,    3   ,  2,]],
2625                      [64 , [6   ,    4   ,    3   ,  2,]],
2626                      [68 , [6   ,    4   ,    3   ,  2,]],
2627                      [72 , [6   ,    4   ,    3   ,  2,]],
2628                      [80 , [6   ,    4   ,    3   ,  2,]],
2629                      [90 , [6   ,    4   ,    3   ,  2,]],
2630                      [100, [6   ,    4   ,    3   ,  2,]],
2631        ],
2632        tentry = struct_val(ISO_thread, diam)
2633     )
2634     assert(is_def(tentry), str("Unknown screw size, M",diam))
2635     assert(is_def(tentry[tind]), str("No ",thread," pitch known for M",diam))
2636     tentry[tind],
2637   
2638   head_data =
2639       head=="none" ? let(
2640           metric_setscrew =
2641               [
2642                  //   hex    torx, torx depth, slot width, slot depth 
2643                [1.2, [undef, undef,   undef,    0.330,        0.460]],
2644                [1.4, [0.7,   undef,   undef,    undef,        undef]],
2645                [1.6, [0.7,   undef,   undef,    0.380,        0.650]],
2646                [1.8, [0.7,   undef,   undef,    undef,        undef]],
2647                [2,   [0.9,   undef,   undef,    0.380,        0.740]],
2648                [2.5, [1.3,   undef,   undef,    0.530,        0.835]],
2649                [3,   [1.5,     6,     0.77,     0.530,        0.925]],
2650                [3.5, [undef, undef,   undef,    0.630,        1.085]],
2651                [4,   [2,       8,     1.05,     0.730,        1.270]],
2652                [5,   [2.5,    10,     1.24,     0.930,        1.455]],
2653                [6,   [3,      15,     1.74,     1.130,        1.800]],
2654                [8,   [4,      25,     2.24,     1.385,        2.250]],
2655                [10,  [5,      40,     2.97,     1.785,        2.700]],
2656                [12,  [6,      45,     3.48,     2.185,        3.200]],
2657                [16,  [8,      55,     5.15]],
2658                [20,  [10,   undef,    undef]],    
2659               ],
2660            entry = struct_val(metric_setscrew, diam),
2661            dummy=assert(drive=="none" || is_undef(drive) || is_def(entry), str("Screw size M",diam," unsupported for headless screws")),
2662            drive_dim = drive=="hex" ? [["drive_size", entry[0]], ["drive_depth", diam/2]]
2663                      : drive=="torx" ? [["drive_size", entry[1]], ["drive_depth", entry[2]]]
2664                      : drive=="slot" ? [["drive_size", entry[3]], ["drive_depth", entry[4]]]
2665                      : []
2666           )
2667           concat([["head","none"]], drive_dim) 
2668     : head=="hex" ? let(
2669            metric_hex = [
2670              // flat to flat width, height
2671              [5, [8, 3.5]],
2672              [6, [10,4]],
2673              [8, [13, 5.3]],
2674              [10, [17, 6.4]],
2675              [12, [19, 7.5]],
2676              [14, [22, 8.8]],
2677              [16, [24, 10]],
2678              [18, [27,11.5]],
2679              [20, [30, 12.5]],
2680              [24, [36, 15]],
2681              [30, [46, 18.7]],
2682            ],
2683            entry = struct_val(metric_hex, diam)
2684           )
2685           assert(is_def(entry), str("Screw size M",diam," unsupported for head type \"",head,"\""))
2686           [["head", "hex"], ["head_size", entry[0]], ["head_height", entry[1]]] 
2687     : in_list(head,["socket","socket ribbed"]) ? let(
2688            // ISO 14579 gives dimensions for Torx (hexalobular) socket heads
2689            metric_socket = [    // height = screw diameter
2690                      //diam, hex, torx size, torx depth
2691                [1.4, [2.5,   1.3]],
2692                [1.6, [3,     1.5]],
2693                [2,   [3.8,   1.5,    6,        0.775]],
2694                [2.5, [4.5,     2,    8,        0.975]],
2695                [2.6, [5,       2,    8,        1.05]],
2696                [3,   [5.5,   2.5,    10,       1.14]],
2697                [3.5, [6.2,   2.5]]   ,
2698                [4,   [7,       3,    25,       1.61]],
2699                [5,   [8.5,     4,    27,       1.84]],
2700                [6,   [10,      5,    30,       2.22]],
2701                [7,   [12,      6]],
2702                [8,   [13,      6,    45,       3.115]],
2703                [10,  [16,      8,    50,       3.82]],
2704                [12,  [18,     10,    55,       5.015]],
2705                [14,  [21,     12,    60,       5.805]],
2706                [16,  [24,     14,    70,       6.815]],
2707                [18,  [27,     14,    80,       7.75]],
2708                [20,  [30,     17,    90,       8.945]],
2709                [22,  [33,     17]],
2710                [24,  [36,     19,    100,     10.79]],
2711                [27,  [40,     19]],
2712                [30,  [45,     22]],
2713                [33,  [50,     24]],
2714                [36,  [54,     27]],
2715                [42,  [63,     32]],
2716                [48,  [72,     36]],
2717            ],
2718            entry = struct_val(metric_socket, diam),
2719            dummy=assert(is_def(entry), str("Screw size M",diam," unsupported for head type \"",head,"\"")),
2720            drive_size =  drive=="hex" ? [["drive_size",entry[1]],["drive_depth",diam/2]] :
2721                          drive=="torx" ? [["drive_size", entry[2]], ["drive_depth", entry[3]]] :
2722                          []
2723            )
2724            concat([["head",head],["head_size",entry[0]], ["head_height", diam]],drive_size) 
2725     : in_list(head,["pan","pan round","pan flat"]) ? let (
2726           metric_pan = [  // pan head for phillips or slotted, torx from ISO 14583
2727                      //          head height
2728                      // diam, slotted  phillips phillips size  phillips diam, phillips depth, ph width, slot width,slot depth, torx size, torx depth
2729                 [1.6,   [3.2,   1  ,     1.3,        0,          undef,         undef,        undef,       0.4,      0.35]],
2730                 [2,     [4,     1.3,     1.6,        1,          1.82,          1.19,         0.48,        0.5,      0.5,        6,         0.7]],
2731                 [2.5,   [5,     1.5,     2,          1,          2.68,          1.53,         0.70,        0.6,      0.6,        8,         0.975]],
2732                 [3,     [5.6,   1.8,     2.4,        1,          2.90,          1.76,         0.74,        0.8,      0.7,        10,        1.14]],
2733                 [3.5,   [7,     2.1,     3.1,        2,          3.92,          1.95,         0.87,        1.0,      0.8,        15,        1.2]],
2734                 [4,     [8,     2.4 ,    3.1,        2,          4.40,          2.45,         0.93,        1.2,      1.0,        20,        1.465]],
2735                 [5,     [9.5,   3,       3.8,        2,          4.90,          2.95,         1.00,        1.2,      1.2,        25,        1.715]],
2736                 [6,     [12,    3.6,     4.6,        3,          6.92,          3.81,         1.14,        1.6,      1.4,        30,        2.22]],
2737                 [8,     [16,    4.8,     6,          4,          9.02,          4.88,         1.69,        2.0,      1.9,        45,        2.985]],
2738                 [10,    [20,    6.0,     7.5,        4,          10.18,         5.09,         1.84,        2.5,      2.4,        50,        3.82]], 
2739            ],
2740            type = head=="pan" ? (drive=="slot" ? "pan flat" : "pan round") : head,
2741            htind = drive=="slot" ? 1 : 2,
2742            entry = struct_val(metric_pan, diam),
2743            dummy=assert(is_def(entry), str("Screw size M",diam," unsupported for head type \"",head,"\"")),
2744            drive_size = drive=="phillips" ? [["drive_size", entry[3]],
2745                                              //["drive_diameter", entry[4]],
2746                                              ["drive_depth",entry[5]],
2747                                              //["drive_width",entry[6]]
2748                                             ] 
2749                       : drive=="torx" ? [["drive_size", entry[9]], ["drive_depth", entry[10]]]
2750                       : drive=="slot" ? [["drive_size", entry[7]], ["drive_depth", entry[8]]] 
2751                       : []
2752           )
2753           concat([["head",type], ["head_size", entry[0]], ["head_height", entry[htind]]], drive_size) 
2754     : head=="button" || head=="cheese" ? let(
2755            // hex drive depth from ISO 7380-1
2756            metric_button = [    // button, hex drive
2757                 //   head diam, height, hex, phillips, hex drive depth, torx size, torx depth
2758                 [1.6, [2.9,     0.8,    0.9, undef,    0.55]], // These four cases,
2759                 [2,   [3.5,     1.3,    1.3, undef,    0.69]], // extrapolated hex depth
2760                 [2.2, [3.8,     0.9,    1.3, undef,    0.76]], //
2761                 [2.5, [4.6,     1.5,    1.5, undef,    0.87]], //
2762                 [3,   [5.7,     1.65,   2,   undef,    1.04,                8,      0.81]],
2763                 [3.5, [5.7,     1.65,   2,   undef,    1.21]], // interpolated hex depth
2764                 [4,   [7.6,     2.2,    2.5, undef,    1.30,                15,     1.3]],
2765                 [5,   [9.5,     2.75,   3,   undef,    1.56,                25,     1.56]],
2766                 [6,   [10.5,    3.3,    4,   undef,    2.08,                27,     2.08]],
2767                 [8,   [14,      4.4,    5,   undef,    2.60,                40,     2.3]],
2768                 [10,  [17.5,    5.5,    6,   undef,    3.12,                45,     2.69]],
2769                 [12,  [21,      6.6,    8,   undef,    4.16,                55,     4.02]],    
2770                 [16,  [28,      8.8,    10,  undef,    5.2]], 
2771             ],
2772             metric_cheese = [   // slotted, phillips     ISO 1207, ISO 7048
2773                                 // hex drive is not supported (hence undefs)
2774                // head diam, head height, hex drive, phillips drive, slot width, slot depth, ph diam
2775                [1,   [2,     0.7,         undef,      undef]],
2776                [1.2, [2.3,   0.8,         undef,      undef]],
2777                [1.4, [2.6,   0.9,         undef,      undef]],
2778                [1.6, [3,     1,           undef,      undef,         0.4,        0.45]],
2779                [2,   [3.8,   1.3,         undef,      1    ,         0.5,        0.6,        undef,       undef]],
2780                [2.5, [4.5,   1.6,         undef,      1    ,         0.6,        0.7,          2.7,        1.20]],
2781                [3,   [5.5,   2,           undef,      2    ,         0.8,        0.85,         3.5,        0.86]],
2782                [3.5, [6,     2.4,         undef,      2    ,         1.0,        1.0,          3.8,        1.15]],
2783                [4,   [7,     2.6,         undef,      2    ,         1.2,        1.1,          4.1,        1.45]],
2784                [5,   [8.5,   3.3,         undef,      2    ,         1.2,        1.3,          4.8,        2.14]],
2785                [6,   [10,    3.9,         undef,      3    ,         1.6,        1.6,          6.2,        2.25]],
2786                [8,   [13,    5,           undef,      3    ,         2.0,        2.0,          7.7,        3.73]],
2787                [10,  [16,    6,           undef,      undef,         2.5,        2.4,        undef,       undef]]
2788             ],
2789             metric_cheese_torx = [ // torx cheese, ISO 14580, the heads are taller than other cheese screws
2790                      //head diam, head height, torx size, torx depth
2791                [2,   [3.8,        1.55,         6,         0.775]],
2792                [2.5, [4.5,        1.85,         8,         0.845]],
2793                [3,   [5.5,        2.4,         10,         1.14]],
2794                [3.5, [6,          2.6,         15,         1.2]],
2795                [4,   [7,          3.1,         20,         1.465]],
2796                [5,   [8.5,        3.65,        25,         1.715]],
2797                [6,   [10,         4.4,         30,         2.095]],
2798                [8,   [13,         5.8,         45,         2.855]],
2799                [10,  [16,         6.9,         59,         3.235]]
2800             ],
2801
2802             entry = struct_val( head=="button" ? metric_button 
2803                               : drive=="torx"? metric_cheese_torx 
2804                               : metric_cheese, 
2805                            diam),
2806             dummy=assert(is_def(entry), str("Screw size M",diam," unsupported for head type \"",head,"\"")),
2807             drive_index = drive=="phillips" ? 3 
2808                         : drive=="hex" ? 2 
2809                         : undef,
2810             drive_dim = head=="button" && drive=="hex" ? [["drive_depth", entry[4]]] 
2811                       : head=="button" && drive=="torx" ? [["drive_size", entry[5]],["drive_depth", entry[6]]] 
2812                       : head=="cheese" && drive=="torx" ? [["drive_size", entry[2]],["drive_depth", entry[3]]] 
2813                       : head=="cheese" && drive=="slot" ? [["drive_size", entry[4]], ["drive_depth", entry[5]]] 
2814                       : head=="cheese" && drive=="phillips" ? [
2815                                                                //["drive_diameter", entry[6]],
2816                                                                ["drive_depth", entry[7]],
2817                                                                //["drive_width", entry[6]/4]  // Fabricated this width value to fill in missing field
2818                                                               ]  
2819                       :[],
2820             drive_size = is_def(drive_index) ? [["drive_size", entry[drive_index]]] : []
2821             )
2822             concat([["head",head],["head_size",entry[0]], ["head_height", entry[1]]],drive_size, drive_dim) 
2823     : starts_with(head,"flat ") || head=="flat" ?
2824         let(
2825             headparts = str_split(head," ",keep_nulls=false),
2826             partsok = [for (part=headparts) if (!in_list(part, ["flat","small","large","sharp","90"])) part], 
2827             dummy1=assert(partsok==[], str("Unknown flat head parameter(s) ",partsok)),
2828             dummy2=assert(!(in_list("small",headparts) && in_list("large",headparts)), "Cannot specify large and small flat head at the same time"),
2829             small = in_list("small",headparts) || (!in_list("large",headparts) && drive!="hex"),
2830             metric_flat_large = [ // for hex drive from ISO-10642, don't know where torx came from
2831                     // -- diam -----   hex size    hex depth     torx   torx depth
2832                     // theory  actual
2833                     //  max     min
2834                  [3,  [6.72,     5.54,      2  ,       1.1,        10,   0.96]],
2835                  [4,  [8.96,     7.53,      2.5,       1.5,        20,   1.34]],
2836                  [5,  [11.20,    9.43,      3  ,       1.9,        25,   1.54]],
2837                  [6,  [13.44,    11.34,     4  ,       2.2,        30,   1.91]],
2838                  [8,  [17.92,    15.24,     5  ,       3.0,        40,   2.3]],
2839                  [10, [22.4,     19.22,     6  ,       3.6,        50,   3.04]],
2840                  [12, [26.88,    23.12,     8  ,       4.3]], 
2841                  [14, [30.8,     26.52,    10  ,       4.5]],
2842                  [16, [33.6,     29.01,    10  ,       4.8]],
2843                  [20, [40.32,    36.05,    12  ,       5.6]]    
2844             ],
2845             metric_flat_small = [ // Phillips from ISO 7046
2846                                   // Slots from ISO 2009
2847                                   // Torx from ISO 14581
2848                    // theory    mean                                             nominal       mean             torx
2849                    //  diam, actual diam  ph size, ph diam, ph depth, ph width, slot width, slot depth  torx   mean depth
2850                 [1.6, [ 3.6,    2.85,         0,     1.6,    0.75,    undef,     0.4,         0.41,     undef,  undef  ]],
2851                 [2,   [ 4.4,    3.65,         0,     1.9,    1.05,     0.53,     0.5,         0.5,         6,    0.575 ]],
2852                 [2.5, [ 5.5,    4.55,         1,     2.9,    1.6,      0.74,     0.6,         0.625,       8,    0.725 ]],
2853                 [3,   [ 6.3,    5.35,         1,     3.2,    1.90,     0.79,     0.8,         0.725,      10,    0.765 ]],
2854                 [3.5, [ 8.2,    7.12,         2,     4.4,    2.15,     0.91,     1.0,         1.05,       15,    1.240 ]],
2855                 [4,   [ 9.4,    8.22,         2,     4.6,    2.35,     0.96,     1.2,         1.15,       10,    1.335 ]],
2856                 [5,   [10.4,    9.12,         2,     5.2,    2.95,     1.04,     1.2,         1.25,       25,    1.315 ]],
2857                 [6,   [12.6,   11.085,        3,     6.8,    3.25,     1.12,     1.6,         1.4,        30,    1.585 ]],
2858                 [8,   [17.3,   15.585,        4,     8.9,    4.30,     1.80,     2.0,         2.05,       45,    2.345 ]],
2859                 [10,  [20  ,   18.04,         4,    10.0,    5.40,    undef,     2.5,         2.3,        50,    2.605 ]],
2860                 [12,  [24  ,   21.75 ]],  // Additional screw head data from ISO 7721, but no driver data   
2861                 [14,  [28  ,   25.25 ]],
2862                 [16,  [32  ,   28.75 ]],
2863                 [18,  [36  ,   32.2  ]],
2864                 [20,  [40  ,   35.7  ]]
2865             ],
2866             entry = struct_val(small ? metric_flat_small : metric_flat_large, diam),
2867             dummy=assert(is_def(entry), str("Screw size M",diam," unsupported for head type \"",head,"\"")),
2868             driveind = small && drive=="phillips" ? 2
2869                      : !small && drive=="hex" ? 2
2870                      : !small && drive=="torx" ? 4
2871                      : small && drive=="torx" ? 8 : undef,
2872             drive_dim = small && drive=="phillips" ? [
2873                                                      // ["drive_diameter", entry[3]],
2874                                                       ["drive_depth",entry[4]],
2875                                                      // ["drive_width", entry[5]]
2876                                                      ] 
2877                       : small && drive=="slot" ? [["drive_size", entry[6]], ["drive_depth", entry[7]]] 
2878                       : drive=="torx" ? [["drive_depth", entry[driveind+1]]] 
2879                       : !small && drive=="hex" ? [["drive_depth", entry[3]]]
2880                       : [],
2881             sharpsize = entry[0]
2882         )
2883         [
2884           ["head","flat"],
2885           ["head_angle",90],
2886           ["head_size", in_list("sharp",headparts) ? sharpsize
2887                       : small ? entry[1]              // entry is mean diameter
2888                       : lerp(entry[1],entry[0],.2)],  // entry is min diameter, so enlarge it 20%
2889           ["head_size_sharp", sharpsize],
2890           if (is_def(driveind)) ["drive_size", entry[driveind]],
2891           each drive_dim
2892         ]
2893     : [] 
2894 )
2895 concat(
2896        [
2897          ["type","screw_info"],
2898          ["system","ISO"],
2899          ["diameter",diam],
2900          ["pitch", pitch],
2901          ["drive",drive]
2902        ],
2903        head_data
2904 );
2905
2906function _is_positive(x) = is_num(x) && x>0;
2907
2908
2909function _validate_nut_spec(spec) =
2910   let(
2911       //dummy=echo_struct(spec,"Screw Specification"),
2912       systemOK = in_list(struct_val(spec,"system"), ["UTS","ISO"]),
2913       diamOK = _is_positive(struct_val(spec, "diameter")),
2914       pitch = struct_val(spec,"pitch"),
2915       pitchOK = is_undef(pitch) || (is_num(pitch) && pitch>=0),
2916       shape = struct_val(spec, "shape"),
2917       shapeOK = shape=="hex" || shape=="square",
2918       thicknessOK = _is_positive(struct_val(spec, "thickness")),
2919       widthOK = _is_positive(struct_val(spec, "width"))
2920    )
2921    assert(systemOK, str("Nut spec has invalid \"system\", ", struct_val(spec,"system"), ".  Must be \"ISO\" or \"UTS\""))
2922    assert(diamOK, str("Nut spec has invalid \"diameter\", ", struct_val(spec,"diameter")))
2923    assert(pitchOK, str("Nut spec has invalid \"pitch\", ", pitch))
2924    assert(shapeOK, str("Nut spec has invalid \"shape\", ", shape, ".  Must be \"square\" or \"hex\""))
2925    assert(thicknessOK, str("Nut spec thickness is not a postive number: ",struct_val(spec,"thickness")))
2926    assert(widthOK, str("Nut spec width is not a postive number: ",struct_val(spec,"width")))
2927    spec;
2928
2929    
2930function _validate_screw_spec(spec) =
2931    let(
2932        //dummy=echo_struct(spec,"Screw Specification"),
2933        systemOK = in_list(struct_val(spec,"system"), ["UTS","ISO"]),
2934        diamOK = _is_positive(struct_val(spec, "diameter")),
2935        pitch = struct_val(spec,"pitch"),
2936        pitchOK = is_undef(pitch) || (is_num(pitch) && pitch>=0),
2937        head = struct_val(spec,"head"),
2938        headOK = head=="none" || 
2939                    (in_list(head, ["cheese","pan flat","pan round", "flat", "button","socket","socket ribbed", "fillister","round","hex"]) &&
2940                     _is_positive(struct_val(spec, "head_size"))),
2941        flatheadOK = (head!="flat" || _is_positive(struct_val(spec,"head_size_sharp"))),
2942        drive = struct_val(spec, "drive"),
2943        driveOK = is_undef(drive) || drive=="none"
2944                  || (_is_positive(struct_val(spec, "drive_depth")) && _is_positive(struct_val(spec, "drive_size")))
2945    )
2946    assert(systemOK, str("Screw spec has invalid \"system\", ", struct_val(spec,"system"), ".  Must be \"ISO\" or \"UTS\""))
2947    assert(diamOK, str("Screw spec has invalid \"diameter\", ", struct_val(spec,"diameter")))
2948    assert(pitchOK, str("Screw spec has invalid \"pitch\", ", pitch))
2949    assert(headOK, "Screw head type invalid or unknown for your screw type and size")  // head is "undef" for invalid heads; we don't know what the user specified
2950    assert(flatheadOK, "Flat head screw invalid because no \"head_size_sharp\" value is present.")
2951    assert(driveOK, str("Screw drive type \"",drive,"\" invalid or unknown for your screw size or head type, \"",head,"\""))
2952    spec;
2953
2954
2955
2956// Function: thread_specification()
2957// Synopsis: Returns the thread geometry for a given screw.
2958// Topics: Threading, Screws
2959// See Also: screw(), screw_hole()
2960// Usage:
2961//   thread_specification(screw_spec, [tolerance], [internal])
2962// Description:
2963//   Determines actual thread geometry for a given screw with specified tolerance and nominal size.  See [tolerance](#subsection-tolerance) for
2964//   information on tolerances.  If tolerance is omitted the default is used.  If tolerance
2965//   is "none" or 0 then return the nominal thread geometry.  When `internal=true` the nut tolerance is used.  
2966//   .
2967//   The return value is a structure with the following fields:
2968//   - pitch: the thread pitch
2969//   - d_major: major diameter range
2970//   - d_pitch: pitch diameter range
2971//   - d_minor: minor diameter range
2972//   - basic: vector `[minor, pitch, major]` of the nominal or "basic" diameters for the threads
2973// Arguments:
2974//   screw_spec = screw specification structure
2975//   tolerance = thread geometry tolerance.  Default: For ISO, "6g" for screws, "6H" for internal threading (nuts).  For UTS, "2A" for screws, "2B" for internal threading (nuts).
2976//   internal = true for internal threads.  Default: false
2977function thread_specification(screw_spec, tolerance=undef, internal=false) =
2978  let( 
2979       diam = _nominal_diam(screw_spec),
2980       pitch = struct_val(screw_spec, "pitch"),
2981       tspec = tolerance == 0 || tolerance=="none" ? _exact_thread_tolerance(diam, pitch)
2982             :  struct_val(screw_spec,"system") == "ISO" ? _ISO_thread_tolerance(diam, pitch, internal, tolerance)
2983             :  struct_val(screw_spec,"system") == "UTS" ? _UTS_thread_tolerance(diam, pitch, internal, tolerance)
2984             :  assert(false,"Unknown screw system ",struct_val(screw_spec,"system"))
2985  )
2986  assert(min(struct_val(tspec,"d_minor"))>0, "Thread specification is too coarse for the diameter")
2987  tspec;
2988
2989
2990
2991
2992
2993// recess sizing:
2994// http://www.fasnetdirect.com/refguide/Machinepancombo.pdf
2995//
2996/*   ASME B 18.6.3
2997http://www.smithfast.com/newproducts/screws/msflathead/
2998
2999
3000/* phillips recess diagram
3001
3002http://files.engineering.com/getfile.aspx?folder=76fb0d5e-1fff-4c49-87a5-05979477ca88&file=Noname.jpg&__hstc=212727627.6c577ef84c12d9cc69c819eea7be49d2.1563972499721.1563972499721.1563972499721.1&__hssc=212727627.1.1563972499721&__hsfp=165344926
3003
3004*/
3005
3006
3007//
3008// https://www.bayoucitybolt.com/socket-head-cap-screws-metric.html
3009//
3010// Torx drive depth for UTS and ISO (at least missing for "flat small", which means you can't select torx for this head type)
3011// Handle generic phillips (e.g. ph2) or remove it?
3012
3013// https://www.fasteners.eu/tech-info/ISO/7721-2/
3014//
3015//    JIS 
3016//https://www.garagejournal.com/forum/media/jis-b-4633-vs-iso-8764-1-din-5260-ph.84492/
3017
3018//square:
3019//https://www.aspenfasteners.com/content/pdf/square_drive_specification.pdf
3020//http://www.globalfastener.com/standards/index.php?narr58=149
3021//https://patents.google.com/patent/US1003657
3022
3023// thread standards:
3024// https://www.gewinde-normen.de/en/index.html
3025
3026/////////////////////////////////////////////////////////////////////////////////////////*
3027/////////////////////////////////////////////////////////////////////////////////////////*
3028/////////////////////////////////////////////////////////////////////////////////////////*
3029///  
3030///  TODO list:
3031///  
3032///  need to make holes at actual size instead of nominal?
3033///     or relative to actual size?
3034///     That means I need to preserve thread= to specify this
3035///  torx depth for UTS pan head
3036///  $fn control
3037///  phillips driver spec with ph# is confusing since it still looks up depth in tables
3038///     and can give an error if it's not found
3039///  torx depths missing for pan head
3040///  support for square drive?  (It's in the ASME standard)
3041///  
3042/////////////////////////////////////////////////////////////////////////////////////////*
3043/////////////////////////////////////////////////////////////////////////////////////////*
3044/////////////////////////////////////////////////////////////////////////////////////////*
3045
3046// vim: expandtab tabstop=4 shiftwidth=4 softtabstop=4 nowrap
3047