# export_glb.py: the slider crank of lesson 1 as one GLB file for Blender, with each part named, coloured and in place.
# In FreeCAD 1.1, with SliderCrank.FCStd open: paste this into View > Panels > Python console, or run it as a macro.
# Without a screen (FreeCAD 1.1.4; the snap works only under the home folder, not /tmp):
#   SC_FILE=/abs/path/SliderCrank.FCStd QT_QPA_PLATFORM=offscreen freecad /abs/path/export_glb.py
# Writes SliderCrank-render.glb next to the FCStd.
#
# The glTF export needs the FreeCAD GUI (ImportGui). Console-only Import.export writes a GLB with no parts in it.
# It also skips hidden objects, so the script shows the assembly and its parts first.
import os, FreeCAD as App, FreeCADGui as Gui, ImportGui

# The colour of each body, as the reader sets it with right-click > Appearance. Values 0 to 1 (sRGB).
COLOUR = {
    'Base': (0.70, 0.71, 0.73), 'Guide': (0.55, 0.57, 0.60),          # aluminium, clear anodised
    'Crank': (0.16, 0.55, 0.53), 'ConnectingRod': (0.80, 0.62, 0.20),  # aluminium, coloured anodised
    'Slider': (0.72, 0.52, 0.30),                                      # bronze
    'PivotPin': (0.85, 0.85, 0.87), 'CrankPin': (0.85, 0.85, 0.87), 'WristPin': (0.85, 0.85, 0.87),  # steel
}

path = os.environ.get('SC_FILE')
doc = App.openDocument(path, hidden=True) if path else App.ActiveDocument
asm = doc.getObject('Assembly')
parts = [o for o in asm.Group if o.TypeId == 'App::Link']
asm.Visibility = True
for lk in parts:
    lk.Visibility = True
    body = lk.LinkedObject
    if body.Name in COLOUR: body.ViewObject.ShapeColor = COLOUR[body.Name]

out = os.path.join(os.path.dirname(doc.FileName), 'SliderCrank-render.glb')
ImportGui.export([asm], out)
print('GLB', out, os.path.getsize(out), 'bytes,', len(parts), 'parts')
for lk in parts:
    p = lk.Placement
    print('  %-18s at x %7.2f  y %7.2f  z %6.2f mm, turned %6.2f deg' % (lk.Label, p.Base.x, p.Base.y, p.Base.z, p.Rotation.toEuler()[0]))
if path:
    os._exit(0)   # no screen: leave without the "save changes?" question
