// Ball Bearing
// A ball bearing is a type of rolling-element bearing that uses balls to maintain the separation between the bearing races. The primary purpose of a ball bearing is to reduce rotational friction and support radial and axial loads.

// Set units
@settings(defaultLengthUnit = in, kclVersion = 1.0)

// Define parameters
outsideDiameter = 1.625
sphereDia = 0.25
shaftDia = 0.75
overallThickness = 0.313
wallThickness = 0.100
overHangLength = .3
nBalls = 10
chainWidth = sphereDia / 2
chainThickness = sphereDia / 8
linkDiameter = sphereDia / 4

// Sketch the inside bearing piece
insideWallSketch = startSketchOn(offsetPlane(XY, offset = -overallThickness / 2))
  |> circle(center = [0, 0], radius = shaftDia / 2 + wallThickness)
  |> subtract2d(tool = circle(center = [0, 0], radius = shaftDia / 2))

// Extrude the inside bearing piece
insideWall = extrude(insideWallSketch, length = overallThickness)

// Create the sketch of one of the balls
ballsSketch = startSketchOn(XY)
  |> startProfile(at = [shaftDia / 2 + wallThickness, 0.001])
  |> arc(angleStart = 180, angleEnd = 0, radius = sphereDia / 2)
  |> close()

// Revolve the ball to make a sphere and pattern around the inside wall
balls = revolve(ballsSketch, axis = X)
  |> patternCircular3d(
       arcDegrees = 360,
       axis = [0, 0, 1],
       center = [0, 0, 0],
       instances = nBalls,
       rotateDuplicates = true,
     )

// Create the sketch for the chain around the balls
chainSketch = startSketchOn(XY)
  |> startProfile(at = [
       shaftDia / 2 + wallThickness + sphereDia / 2 - (chainWidth / 2),
       0.125 * sin(60)
     ])
  |> arc(angleStart = 120, angleEnd = 60, radius = sphereDia / 2)
  |> line(end = [0, chainThickness])
  |> line(end = [-chainWidth, 0])
  |> close()

// Revolve the chain sketch
chainHead = revolve(chainSketch, axis = X)
  |> patternCircular3d(
       arcDegrees = 360,
       axis = [0, 0, 1],
       center = [0, 0, 0],
       instances = nBalls,
       rotateDuplicates = true,
     )

// Create the sketch for the links in between the chains
linkSketch = startSketchOn(XZ)
  |> circle(
       center = [
         shaftDia / 2 + wallThickness + sphereDia / 2,
         0
       ],
       radius = linkDiameter / 2,
     )

// Revolve the link sketch
linkRevolve = revolve(linkSketch, axis = Y, angle = 360 / nBalls)
  |> patternCircular3d(
       arcDegrees = 360,
       axis = [0, 0, 1],
       center = [0, 0, 0],
       instances = nBalls,
       rotateDuplicates = true,
     )

// Create the sketch for the outside walls
outsideWallSketch = startSketchOn(offsetPlane(XY, offset = -overallThickness / 2))
  |> circle(center = [0, 0], radius = outsideDiameter / 2)
  |> subtract2d(tool = circle(center = [0, 0], radius = shaftDia / 2 + wallThickness + sphereDia))

outsideWall = extrude(outsideWallSketch, length = overallThickness)
