// this macro produces a gear wheel. The parameters are the number of
// sprockets, the width/thickness of the wheel, the radius without
// the height of the sprockets, the height of the sprockets, and a parameter 
// from 0 to 1 specifying how round the sprockets are on the outer edge

#macro gearWheel(GW_sprocketNumber, GW_radius, GW_sprocketHeight, GW_thick, GW_rounding)
	
	// building a sprocket
	#local segmentAngle = 2*pi/GW_sprocketNumber;
	#local sprocketBase = 2*GW_radius*sin(segmentAngle/2);
	#local sprocketPeakHalfAngle = atan(sprocketBase/(2*GW_sprocketHeight));
	#local roundingCapRad = GW_rounding * sprocketBase /2 / cos(sprocketPeakHalfAngle);
	#local roundingOffset = GW_rounding * sprocketBase /2 * tan(sprocketPeakHalfAngle);
	#local sprocket = union {
		difference {
			box {
				<-GW_thick/2, -sprocketHeight, -sprocketBase/2>, <GW_thick/2, 0, sprocketBase/2>
			}
			box {
				<-GW_thick, 0, 0>, <GW_thick, -2*GW_sprocketHeight, -1>
				rotate x*180/pi *sprocketPeakHalfAngle
			}
			box {
				<-GW_thick, 0, 0>, <GW_thick, -2*GW_sprocketHeight, 1>
				rotate -x*180/pi *sprocketPeakHalfAngle
			}
			box {
				<-GW_thick, 0, -1>, <GW_thick, -GW_sprocketHeight*GW_rounding, 1>
			}
		}
		difference {
			cylinder {
				<-GW_thick/2, -sprocketHeight*sprocketRounding-roundingOffset,0>, <GW_thick/2, -sprocketHeight*sprocketRounding-roundingOffset, 0>, roundingCapRad
			}
			box {
				<0, -GW_sprocketHeight*GW_rounding, -1>, <-GW_thick, -GW_sprocketHeight, 1>
			}
		}
		translate y*(GW_sprocketHeight + GW_radius*cos(segmentAngle/2))
	}


	union {
		cylinder {
			<-GW_thick/2, 0, 0>, <GW_thick/2, 0, 0>, GW_radius
		}
		
		// adding the sprockets
		#declare i=0;
		#while (i < GW_sprocketNumber)
			object { sprocket
				rotate x*i*segmentAngle*180/pi
			}
		#declare i=i+1;
		#end
	}
	
#end
