Monday, 22 June 2020

OpenScad Useful Functions

Some useful OpenScad functions / code

row = array_lookup(search, array, column)

OpenSCad doesn't support variable as such, so things need to be done recursively.
function array_lookup(query, source, column) = _array_lookup_rec(query, source, column, 0) ;
function _array_lookup_rec(query, source, column, row) =
    row>=len(source) ? len(source)-1 :
   query==source[row][column] ? row :
  _array_lookup_rec(query,source,column,row+1) ;
srcarray = [
[ "green", "apple", 5 ],
[ "green", "pear", 9 ],
[ "yellow", "banana", 5 ],
[ "ERROR", "ERROR", 0 ]
] ;
row1 = array_lookup("pear", scarray ,1) ;

i = toint(s)

This function uses recursion to work along the string.  It converts the supplied 's' to a string just in case an integer is supplied to the function.

// Safe Convert Decimal String to integer
function toint(st) = _toint_rec(str(st),0, 0) ;
function _toint_rec(st, idx, value) = (
    idx>=len(st) ? value
    : _toint_rec(st, idx+1, ( value*10 + ord(st[idx])-ord("0")) ) ) ;

prism(x,y,xm1,xm2,ym1,ym2,z,center)

This module produces a prism with a base which is X x Y and a height Z
The top edges can be moved in with the X and Y margins.
// prism base = x by y. left margin = xm1, bottom margin = ym1 etc.
module prism(x, y, xm1, xm2, ym1, ym2, z, center){
    CubePoints = [
        [ 0,  0,  0 ],  //0
        [ x, 0, 0 ],  //1
        [ x, y, 0 ],  //2
        [ 0, y, 0 ],  //3
        [ xm1,ym1, z ],  //4
        [ x-xm1, ym1, z ],  //5
        [ x-xm1, y-ym2, z ],  //6
        [ xm1, y-ym2, z ]]; //7
    CubeFaces = [
        [0,1,2,3],  // bottom
        [4,5,1,0],  // front
        [7,6,5,4],  // top
        [5,6,2,1],  // right
        [6,7,3,2],  // back
        [7,4,0,3]]; // left
    if (center) {
        translate([-x/2,-y/2,-z/2]) polyhedron(CubePoints, CubeFaces);
    } else {
        polyhedron(CubePoints, CubeFaces);
    }
} ;


No comments:

Post a comment