MeshLib is a powerful library that can be used for your custom automations, and the beauty of MeshLib is that you don’t need any advanced programming skills for that.
With Python it’s very easy, and we are going to demonstrate it to you right now.
Imagine that you have a 3rd-party application producing STL files but those need to be decimated in order to have less amount of triangles, and thus as the result reduce their file size. If the files are dropped by the app into a folder, we can create a script which runs continuously, watches for new files in the folder, decimate meshes and saves the result into another folder.
First, you might need to install MeshLib into your Python environment.
Then, let’s write the script:
import os
import time
from meshlib import mrmeshpy as mm
import sys
# read input directory path from the script arguments
input_directory = sys.argv[1]
# read output directory path from the script arguments
output_directory = sys.argv[2]
# read max decimation deviation from the script arguments
max_deviation = sys.argv[3]
# define function to be called for each new file – in our example we decimate meshes
def process_file(filename):
# load mesh from file
mesh = mm.loadMesh(mm.Path(filename))
# decimate the mesh
settings = mm.DecimateSettings()
settings.maxError = float(max_deviation)
settings.maxEdgeLen = 1e38
settings.packMesh = True
res = mm.decimateMesh(mesh, settings)
# save decimated mesh into the same file
mm.saveMesh( mesh, mm.Path( os.path.join( output_directory, os.path.basename( filename ) ) ) )
print(filename +” max deviation: ” + str(res.errorIntroduced))
# initialize a set to keep track of files that have already been processed
processed_files = set()
# we use simple “while(True)” infinite cycle to watch for new files in the directory
while True:
# get list of files in directory
files = os.listdir(input_directory)
# filter out files that have already been processed
new_files = [f for f in files if f not in processed_files]
# call function for each new file
for f in new_files:
try:
process_file( os.path.join( input_directory, f ) )
except:
print(“Cannot process file: ” + f)
# add new files to set of processed files
processed_files.update(new_files)
# wait for a specified amount of time before checking for new files again
time.sleep(1)
Save the script above into a python file (let’s say we call it “listen_dir_and_decimate.py”) and launch it using the following command line:
python listen_dir_and_decimate.py “c:\\input_dir” “c:\\output_dir” 0.03
where:
“c:\\input_dir” is the directory where the 3rd party app stores new files,
“c:\\output_dir” is the directory where you want to store the decimated files,
“0.03” is the max deviation in mm for mesh decimation.