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