# batch_export.py: a batch export. Five gears (12 to 36 teeth, module 2.5, 10 mm thick, 8 mm bore) are built, each saved
# as STEP (for any CAD program or a CNC shop) and STL (for a 3D printer), with a parts list, bom.csv, and one FreeCAD file
# with all five in a row. Then every file is read back and checked. Needs gear.py in FOLDER (loaded if it is not yet).
# Run: exec(open('/your/folder/batch_export.py').read())
#  or: freecad.cmd -c "exec(open('/your/folder/batch_export.py').read())"    (no window: the way to run a long batch)
# Tested in FreeCAD 1.1.4.
import os, csv, math
import FreeCAD as App, Part, Mesh, MeshPart
FOLDER = os.path.expanduser('~/gear-scripts')        # the folder where you saved gear.py: put its full path here
FOLDER = os.environ.get('PS_SCRIPTS', FOLDER)          # (a PS_SCRIPTS setting wins: used by the tests)
OUT = os.path.join(os.environ.get('PS_OUT', FOLDER), 'gear-family')            # where the files go
if 'create_involute_gear' not in globals():
    g = {'__name__': 'gear'}; exec(open(os.path.join(FOLDER, 'gear.py')).read(), g)
    create_involute_gear = g['create_involute_gear']
os.makedirs(OUT, exist_ok=True)

MODULE, THICK, BORE = 2.5, 10, 8
doc = App.newDocument('GearFamily')
bom, x = [], 0.0
for teeth in (12, 18, 24, 30, 36):
    name = 'Gear_m%s_%dT' % (str(MODULE).replace('.', 'p'), teeth)
    shape = create_involute_gear(module=MODULE, num_teeth=teeth, thickness=THICK, bore=BORE)
    shape.exportStep(os.path.join(OUT, name + '.step'))
    mesh = MeshPart.meshFromShape(Shape=shape, LinearDeflection=0.01, AngularDeflection=0.1)
    mesh.write(os.path.join(OUT, name + '.stl'))
    outer = MODULE * (teeth + 2)
    x += outer / 2
    obj = doc.addObject('Part::Feature', name); obj.Shape = shape
    obj.Placement.Base = App.Vector(x, 0, 0)
    x += outer / 2 + 10                                          # 10 mm between neighbours in the row
    bom.append({'part': name, 'teeth': teeth, 'module': MODULE, 'outer_d': outer, 'bore': BORE, 'thick': THICK,
                'volume_cm3': round(shape.Volume / 1000, 2), 'steel_g': round(shape.Volume / 1000 * 7.85),
                'step_kb': round(os.path.getsize(os.path.join(OUT, name + '.step')) / 1024),
                'stl_kb': round(os.path.getsize(os.path.join(OUT, name + '.stl')) / 1024), 'triangles': mesh.CountFacets})
    print('exported', name)
doc.recompute()
doc.saveAs(os.path.join(OUT, 'GearFamily.FCStd'))
with open(os.path.join(OUT, 'bom.csv'), 'w', newline='') as f:
    w = csv.DictWriter(f, fieldnames=list(bom[0])); w.writeheader(); w.writerows(bom)
print('Wrote %d STEP, %d STL, bom.csv and GearFamily.FCStd to %s' % (len(bom), len(bom), os.path.abspath(OUT)))

# ---- test: read every file back
for b in bom:
    s = Part.read(os.path.join(OUT, b['part'] + '.step'))
    assert s.isValid() and len(s.Solids) == 1, b['part']
    assert abs(s.Volume / 1000 - b['volume_cm3']) < 0.01, (b['part'], s.Volume)
    m = Mesh.Mesh(os.path.join(OUT, b['part'] + '.stl'))
    assert m.isSolid() and not m.hasNonManifolds(), b['part']
    assert abs(m.Volume / 1000 / b['volume_cm3'] - 1) < 0.005, (b['part'], m.Volume)   # the STL is within 0.5 % of the solid
d2 = App.openDocument(os.path.join(OUT, 'GearFamily.FCStd'))
assert len(d2.Objects) == len(bom) and all(o.Shape.isValid() for o in d2.Objects)
App.closeDocument(d2.Name)
print('TEST batch_export.py: PASS')
