import FreeCAD as App

import Part

import math

import os


# パラメータ

tooth_count = 12

pitch = 15 # mm

hole_radius = 1.1 # ピン用

thickness = 5 # mm

sprocket_radius = pitch / (2 * math.sin(math.pi / tooth_count)) # ピッチ円半径


# ドキュメント作成

doc = App.newDocument("Sprocket")

sprocket = Part.makeCylinder(sprocket_radius, thickness)


# 歯の生成

tooth_angle = 360 / tooth_count

tooth_width = 4 # mm

tooth_height = 3 # mm


for i in range(tooth_count):

    angle_rad = math.radians(i * tooth_angle)

    x = (sprocket_radius + tooth_height / 2) * math.cos(angle_rad)

    y = (sprocket_radius + tooth_height / 2) * math.sin(angle_rad)

    box = Part.makeBox(tooth_width, tooth_height, thickness)

    box.translate(App.Vector(-tooth_width/2, 0, 0))

    box.rotate(App.Vector(0,0,0), App.Vector(0,0,1), i * tooth_angle)

    box.translate(App.Vector(x, y, 0))

    sprocket = sprocket.fuse(box)


# 中心穴(オプション)

center_hole = Part.makeCylinder(2, thickness) # 軸穴

sprocket = sprocket.cut(center_hole)


# 表示と保存

Part.show(sprocket)


# ファイル保存(STLとしてデスクトップへ)

desktop = os.path.join(os.path.expanduser("~"), "Desktop")

file_path = os.path.join(desktop, "sprocket_12t.stl")

Part.export([sprocket], file_path)

print(f"スプロケットを保存しました: {file_path}")