Monday, December 28, 2015

Oblique Cylinder in OpenSCAD

While working in OpenSCAD I found the need to create an oblique cylinder, which is a combination between a rhombus and a cylinder. Unfortunately there is no easy way to create an oblique cylinder (at-least in version 2015.03-1) and by easy I mean something that can be done in three lines of code.

I ended up having to create a very trigonometry heavy module to accomplish this goal. Below is the code, which I hope saves some people a few hours. 

module ObliqueCylinder(height = 1, radius = 1, angle = 0, faces = 360) {
    theta = angle; 
    m = radius * sin(theta); 
    k = radius * sin(2 * theta);
    l = radius * pow(sin(theta), 2);
    hPrime = height/cos(theta) + 2 * m; 
    
    difference() {
        translate([0, -l, -1/2 * k]) {
            rotate(a = [-theta, 0, 0]) {
                linear_extrude(height = hPrime) {
                    rotate(a = [theta, 0, 0]) {
                        circle(r = radius, $fn = faces);
                    }
                }
            }
        }
        translate([0, 0, -1/2 * k]) {
            cube(size = [2 * radius, 2 * radius, k], center = true);
        }
        translate([0, height * tan(theta), height + k/2]) {
            cube(size = [2 * radius, 2 * radius, k], center = true);
        }
    }
}

Below is the result.