Skip to content

Instantly share code, notes, and snippets.

@yorikvanhavre
Last active June 5, 2020 12:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yorikvanhavre/e074713ab9447b84d636f94da0bb10a7 to your computer and use it in GitHub Desktop.
Save yorikvanhavre/e074713ab9447b84d636f94da0bb10a7 to your computer and use it in GitHub Desktop.
Renders a FreeCAD file to png
#!/usr/bin/python3
"""
This renders a FreeCAD .FCStd file to a .png file in the same directory
Usage: fcstd2png.py path/to/someFile.FCStd
Instructions:
- make sure you have the latest version of FreeCAD installed
- make sure you have the pivy (python bindongs for coin3D) package installed
- make sure FreeCAD is importable from python (use the commented line below if needed)
- on linux, the X server must have indirect rendering enabled in order to be able to do
offline PNG rendering. Unfortunatley, this is turned off by default on most recent
distros. The easiest way I found is to edit (or create if inexistant) /etc/X11/xorg.conf
and add this:
Section "ServerFlags"
Option "AllowIndirectGLX" "on"
Option "IndirectGLX" "on"
EndSection
(if your xorg.conf already has a "ServerFlags" section, just add the two options in it).
There might be other ways for other distros though, google for "enable indirect glx"
with your distro name and version
"""
IMAGE_WIDTH = 800
IMAGE_HEIGHT = 600
BACKGROUND = (1.0,1.,1.0) # white background
import os # builtin python lib
import sys # builtin python lib
# if needed, uncomment and set the path to your FreeCAD.so (or FreeCAD.pyd on windows) below:
# sys.path.append("/path/to/FreeCAD.so")
# Another way, more system-independent, is to symlink your FreeCAD.so file to
# .local/lib/Python3.7/site-packages (user-wide) or
# /usr/lib/python3.7/dis-packages (system-wide)
# (using your version of python3 instead of 3.7 in the links above if applicable)
import FreeCAD # main freecad lib, to be imported before any other FreeCAD component (will add their paths to sys)
import OfflineRenderingUtils # the offline rendering utilities module
# build full filepaths (not 100% required, relative paths work in python too, but always safer)
freecadFile = os.path.join(os.getcwd(),sys.argv[-1])
baseFileName = os.path.splitext(freecadFile)[0]
# open FreeCAD file
doc = FreeCAD.open(freecadFile)
# build color dict
colors = OfflineRenderingUtils.getColors(freecadFile)
# get the camera data from the file (used in some functions below)
camera = OfflineRenderingUtils.getCamera(freecadFile)
# build coin scene
scene = OfflineRenderingUtils.buildScene(doc.Objects,colors)
# export to PNG
OfflineRenderingUtils.render(baseFileName+".png",scene,camera,width=IMAGE_WIDTH,height=IMAGE_HEIGHT,background=BACKGROUND)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment